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/com/cyanogenmod/cmparts/activities/UIActivity.java b/src/com/cyanogenmod/cmparts/activities/UIActivity.java
index 5cfc6d0..1be6063 100644
--- a/src/com/cyanogenmod/cmparts/activities/UIActivity.java
+++ b/src/com/cyanogenmod/cmparts/activities/UIActivity.java
@@ -1,391 +1,392 @@
/*
* Copyright (C) 2011 The CyanogenMod 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.cyanogenmod.cmparts.activities;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.os.Environment;
import android.os.SystemProperties;
import android.preference.CheckBoxPreference;
import android.preference.ListPreference;
import android.preference.Preference;
import android.preference.Preference.OnPreferenceChangeListener;
import android.preference.PreferenceActivity;
import android.preference.PreferenceCategory;
import android.preference.PreferenceScreen;
import android.provider.Settings;
import android.net.Uri;
import android.util.Log;
import android.view.KeyEvent;
import java.io.FileOutputStream;
import java.io.File;
import java.io.IOException;
import com.cyanogenmod.cmparts.R;
import com.cyanogenmod.cmparts.utils.SurfaceFlingerUtils;
import com.cyanogenmod.cmparts.widgets.RenderColorPreference;
public class UIActivity extends PreferenceActivity implements OnPreferenceChangeListener {
/* Preference Screens */
private static final String NOTIFICATION_SCREEN = "notification_settings";
private static final String NOTIFICATION_TRACKBALL = "trackball_notifications";
private static final String PREF_SQUADZONE = "squadkeys";
private static final String EXTRAS_SCREEN = "tweaks_extras";
private static final String GENERAL_CATEGORY = "general_category";
/* private static final String HIDE_AVATAR_MESSAGE_PREF = "pref_hide_avatar_message"; */
private PreferenceScreen mStatusBarScreen;
private PreferenceScreen mNotificationScreen;
private PreferenceScreen mTrackballScreen;;
private PreferenceScreen mExtrasScreen;
/* Other */
private static final String BOOTANIMATION_PREF = "pref_bootanimation";
private static final String BOOTSOUND_PREF = "pref_bootsound";
private static final String SHUTDOWNANIMATION_PREF = "pref_shutdownanimation";
private static final String BOOTSOUND_RESET_PREF = "pref_bootsound_reset";
private static final String BOOTANIMATION_RESET_PREF = "pref_bootanimation_reset";
private static final String SHUTDOWNANIMATION_RESET_PREF = "pref_shutdownanimation_reset";
private static final String BOOTANIMATION_PREVIEW_PREF = "pref_bootanimation_preview";
private static final String PINCH_REFLOW_PREF = "pref_pinch_reflow";
public static final String RENDER_EFFECT_PREF = "pref_render_effect";
public static final String RENDER_COLORS_PREF = "pref_render_colors";
private static final String SHARE_SCREENSHOT_PREF = "pref_share_screenshot";
private CheckBoxPreference mPinchReflowPref;
private ListPreference mRenderEffectPref;
private RenderColorPreference mRenderColorPref;
private CheckBoxPreference mShareScreenshotPref;
private PreferenceScreen mBootPref;
private PreferenceScreen mBootsoundPref;
private PreferenceScreen mShutPref;
private PreferenceScreen mBootReset;
private PreferenceScreen mBootSoundReset;
private PreferenceScreen mShutReset;
private PreferenceScreen mBootPreview;
private static final int REQUEST_CODE_PICK_FILESHUT = 997;
private static final int REQUEST_CODE_PICK_FILESOUND = 998;
private static final int REQUEST_CODE_PICK_FILE = 999;
private static final int REQUEST_CODE_MOVE_FILE = 1000;
private static final int REQUEST_CODE_PREVIEW_FILE = 1001;
private static boolean mBootPreviewRunning;
private static int prevOrientation;
private Preference mSquadzone;
private static final String MOVE_BOOT_INTENT = "com.cyanogenmod.cmbootanimation.MOVE_BOOTANIMATION";
private static final String MOVE_BOOTSOUND_INTENT = "com.cyanogenmod.cmbootsound.COPY_BOOTSOUND";
private static final String MOVE_SHUT_INTENT = "com.cyanogenmod.cmshutdownanimation.MOVE_SHUTDOWNANIMATION";
private static final String BOOT_RESET = "com.cyanogenmod.cmbootanimation.RESET_DEFAULT";
private static final String BOOTSOUND_RESET = "com.cyanogenmod.cmbootsound.RESET_SOUND";
private static final String SHUT_RESET = "com.cyanogenmod.cmshutdownanimation.RESET_SHUT";
private static final String BOOT_PREVIEW_FILE = "preview_bootanim";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setTitle(R.string.interface_settings_title_head);
addPreferencesFromResource(R.xml.ui_settings);
PreferenceScreen prefSet = getPreferenceScreen();
mSquadzone = (Preference) prefSet.findPreference(PREF_SQUADZONE);
mSquadzone.setSummary("CyanMobile");
/* Preference Screens */
mNotificationScreen = (PreferenceScreen) prefSet.findPreference(NOTIFICATION_SCREEN);
mTrackballScreen = (PreferenceScreen) prefSet.findPreference(NOTIFICATION_TRACKBALL);
mExtrasScreen = (PreferenceScreen) prefSet.findPreference(EXTRAS_SCREEN);
boolean hasLed = getResources().getBoolean(R.bool.has_rgb_notification_led)
|| getResources().getBoolean(R.bool.has_dual_notification_led)
|| getResources().getBoolean(R.bool.has_single_notification_led);
if (!hasLed) {
((PreferenceCategory) prefSet.findPreference(GENERAL_CATEGORY))
.removePreference(mTrackballScreen);
}
/* Boot Animation Chooser */
mBootPref = (PreferenceScreen) prefSet.findPreference(BOOTANIMATION_PREF);
mBootReset = (PreferenceScreen) prefSet.findPreference(BOOTANIMATION_RESET_PREF);
mBootPreview = (PreferenceScreen) prefSet.findPreference(BOOTANIMATION_PREVIEW_PREF);
mBootsoundPref = (PreferenceScreen) prefSet.findPreference(BOOTSOUND_PREF);
mBootSoundReset = (PreferenceScreen) prefSet.findPreference(BOOTSOUND_RESET_PREF);
mShutPref = (PreferenceScreen) prefSet.findPreference(SHUTDOWNANIMATION_PREF);
mShutReset = (PreferenceScreen) prefSet.findPreference(SHUTDOWNANIMATION_RESET_PREF);
/* Pinch reflow */
mPinchReflowPref = (CheckBoxPreference) prefSet.findPreference(PINCH_REFLOW_PREF);
mPinchReflowPref.setChecked(Settings.System.getInt(getContentResolver(),
Settings.System.WEB_VIEW_PINCH_REFLOW, 0) == 1);
mRenderEffectPref = (ListPreference) prefSet.findPreference(RENDER_EFFECT_PREF);
mRenderEffectPref.setOnPreferenceChangeListener(this);
mRenderColorPref = (RenderColorPreference) prefSet.findPreference(RENDER_COLORS_PREF);
mRenderColorPref.setOnPreferenceChangeListener(this);
/* Share Screenshot */
mShareScreenshotPref = (CheckBoxPreference) prefSet.findPreference(SHARE_SCREENSHOT_PREF);
mShareScreenshotPref.setChecked(Settings.System.getInt(getContentResolver(),
Settings.System.SHARE_SCREENSHOT, 0) == 1);
}
@Override
protected void onResume() {
super.onResume();
SurfaceFlingerUtils.RenderEffectSettings renderSettings =
SurfaceFlingerUtils.getRenderEffectSettings(this);
mRenderEffectPref.setValue(String.valueOf(renderSettings.effectId));
updateRenderColorPrefState(renderSettings.effectId);
mRenderColorPref.setValue(renderSettings.getColorDefinition());
}
public boolean onPreferenceTreeClick(PreferenceScreen preferenceScreen, Preference preference) {
boolean value;
/* Preference Screens */
if (preference == mStatusBarScreen) {
startActivity(mStatusBarScreen.getIntent());
return true;
} else if (preference == mNotificationScreen) {
startActivity(mNotificationScreen.getIntent());
return true;
} else if (preference == mTrackballScreen) {
startActivity(mTrackballScreen.getIntent());
return true;
} else if (preference == mExtrasScreen) {
startActivity(mExtrasScreen.getIntent());
return true;
} else if (preference == mPinchReflowPref) {
value = mPinchReflowPref.isChecked();
Settings.System.putInt(getContentResolver(), Settings.System.WEB_VIEW_PINCH_REFLOW,
value ? 1 : 0);
return true;
} else if (preference == mShareScreenshotPref) {
value = mShareScreenshotPref.isChecked();
Settings.System.putInt(getContentResolver(), Settings.System.SHARE_SCREENSHOT,
value ? 1 : 0);
return true;
} else if (preference == mBootPref) {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setDataAndType(Uri.fromFile(new File("/sdcard/download")), "file/*");
startActivityForResult(intent, REQUEST_CODE_PICK_FILE);
return true;
} else if (preference == mBootsoundPref) {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setDataAndType(Uri.fromFile(new File("/sdcard/download")), "file/*");
startActivityForResult(intent, REQUEST_CODE_PICK_FILESOUND);
return true;
} else if (preference == mShutPref) {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setDataAndType(Uri.fromFile(new File("/sdcard/download")), "file/*");
startActivityForResult(intent, REQUEST_CODE_PICK_FILESHUT);
return true;
} else if (preference == mBootReset) {
Intent intent = new Intent(BOOT_RESET);
sendBroadcast(intent);
return true;
} else if (preference == mBootSoundReset) {
Intent intent = new Intent(BOOTSOUND_RESET);
sendBroadcast(intent);
return true;
} else if (preference == mShutReset) {
Intent intent = new Intent(SHUT_RESET);
sendBroadcast(intent);
return true;
} else if (preference == mBootPreview) {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setDataAndType(Uri.fromFile(new File("/sdcard/download")), "file/*");
startActivityForResult(intent, REQUEST_CODE_PREVIEW_FILE);
return true;
}
return false;
}
public boolean onPreferenceChange(Preference preference, Object newValue) {
String val = newValue.toString();
if (preference == mRenderEffectPref) {
int effectId = Integer.valueOf((String) newValue);
SurfaceFlingerUtils.setRenderEffect(this, effectId);
updateRenderColorPrefState(effectId);
return true;
} else if (preference == mRenderColorPref) {
SurfaceFlingerUtils.setRenderColors(this, (String) newValue);
return true;
}
return false;
}
private void updateRenderColorPrefState(int effectId) {
mRenderColorPref.setEnabled(effectId >= 7 && effectId <= 9);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Context context = getApplicationContext();
switch (requestCode) {
case REQUEST_CODE_PICK_FILESHUT:
if (resultCode == RESULT_OK && data != null) {
// obtain the filename
Uri fileUri = data.getData();
if (fileUri != null) {
String filePath = fileUri.getPath();
if (filePath != null) {
Intent mvShutIntent = new Intent();
mvShutIntent.setAction(MOVE_SHUT_INTENT);
mvShutIntent.putExtra("fileName", filePath);
sendBroadcast(mvShutIntent);
}
}
}
break;
case REQUEST_CODE_PICK_FILESOUND:
if (resultCode == RESULT_OK && data != null) {
// obtain the filename
Uri fileUri = data.getData();
if (fileUri != null) {
String filePath = fileUri.getPath();
if (filePath != null) {
Intent mvBootsoundIntent = new Intent();
mvBootsoundIntent.setAction(MOVE_BOOTSOUND_INTENT);
mvBootsoundIntent.putExtra("fileName", filePath);
sendBroadcast(mvBootsoundIntent);
}
}
}
break;
case REQUEST_CODE_PICK_FILE:
if (resultCode == RESULT_OK && data != null) {
// obtain the filename
Uri fileUri = data.getData();
if (fileUri != null) {
String filePath = fileUri.getPath();
if (filePath != null) {
Intent mvBootIntent = new Intent();
mvBootIntent.setAction(MOVE_BOOT_INTENT);
mvBootIntent.putExtra("fileName", filePath);
sendBroadcast(mvBootIntent);
}
}
}
break;
case REQUEST_CODE_PREVIEW_FILE:
if (resultCode == RESULT_OK && data != null) {
Uri fileUri = data.getData();
if (fileUri != null) {
String filePath = fileUri.getPath();
if (filePath != null) {
try {
FileOutputStream outfile = context.openFileOutput(BOOT_PREVIEW_FILE, Context.MODE_WORLD_READABLE);
outfile.write(filePath.getBytes());
outfile.close();
} catch (Exception e) { }
mBootPreviewRunning = true;
prevOrientation = getRequestedOrientation();
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
- SystemProperties.set("ctl.start", "bootanim");
+ SystemProperties.set( "service.bootanim.exit", "0");
+ SystemProperties.set("ctl.start", "bootanim");
}
}
}
break;
}
}
@Override
public void onPause() {
super.onPause();
Context context = getApplicationContext();
if(mBootPreviewRunning) {
File rmFile = new File(context.getFilesDir(), BOOT_PREVIEW_FILE);
if (rmFile.exists()) {
try {
rmFile.delete();
} catch (Exception e) { }
}
setRequestedOrientation(prevOrientation);
SystemProperties.set("ctl.stop", "bootanim");
mBootPreviewRunning = false;
}
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
Context context = getApplicationContext();
if (keyCode == KeyEvent.KEYCODE_BACK && mBootPreviewRunning) {
File rmFile = new File(context.getFilesDir(), BOOT_PREVIEW_FILE);
if (rmFile.exists()) {
try {
rmFile.delete();
} catch (Exception e) { }
}
SystemProperties.set("ctl.stop", "bootanim");
mBootPreviewRunning = false;
setRequestedOrientation(prevOrientation);
return true;
}
return super.onKeyDown(keyCode, event);
}
}
| true | true | protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Context context = getApplicationContext();
switch (requestCode) {
case REQUEST_CODE_PICK_FILESHUT:
if (resultCode == RESULT_OK && data != null) {
// obtain the filename
Uri fileUri = data.getData();
if (fileUri != null) {
String filePath = fileUri.getPath();
if (filePath != null) {
Intent mvShutIntent = new Intent();
mvShutIntent.setAction(MOVE_SHUT_INTENT);
mvShutIntent.putExtra("fileName", filePath);
sendBroadcast(mvShutIntent);
}
}
}
break;
case REQUEST_CODE_PICK_FILESOUND:
if (resultCode == RESULT_OK && data != null) {
// obtain the filename
Uri fileUri = data.getData();
if (fileUri != null) {
String filePath = fileUri.getPath();
if (filePath != null) {
Intent mvBootsoundIntent = new Intent();
mvBootsoundIntent.setAction(MOVE_BOOTSOUND_INTENT);
mvBootsoundIntent.putExtra("fileName", filePath);
sendBroadcast(mvBootsoundIntent);
}
}
}
break;
case REQUEST_CODE_PICK_FILE:
if (resultCode == RESULT_OK && data != null) {
// obtain the filename
Uri fileUri = data.getData();
if (fileUri != null) {
String filePath = fileUri.getPath();
if (filePath != null) {
Intent mvBootIntent = new Intent();
mvBootIntent.setAction(MOVE_BOOT_INTENT);
mvBootIntent.putExtra("fileName", filePath);
sendBroadcast(mvBootIntent);
}
}
}
break;
case REQUEST_CODE_PREVIEW_FILE:
if (resultCode == RESULT_OK && data != null) {
Uri fileUri = data.getData();
if (fileUri != null) {
String filePath = fileUri.getPath();
if (filePath != null) {
try {
FileOutputStream outfile = context.openFileOutput(BOOT_PREVIEW_FILE, Context.MODE_WORLD_READABLE);
outfile.write(filePath.getBytes());
outfile.close();
} catch (Exception e) { }
mBootPreviewRunning = true;
prevOrientation = getRequestedOrientation();
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
SystemProperties.set("ctl.start", "bootanim");
}
}
}
break;
}
}
| protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Context context = getApplicationContext();
switch (requestCode) {
case REQUEST_CODE_PICK_FILESHUT:
if (resultCode == RESULT_OK && data != null) {
// obtain the filename
Uri fileUri = data.getData();
if (fileUri != null) {
String filePath = fileUri.getPath();
if (filePath != null) {
Intent mvShutIntent = new Intent();
mvShutIntent.setAction(MOVE_SHUT_INTENT);
mvShutIntent.putExtra("fileName", filePath);
sendBroadcast(mvShutIntent);
}
}
}
break;
case REQUEST_CODE_PICK_FILESOUND:
if (resultCode == RESULT_OK && data != null) {
// obtain the filename
Uri fileUri = data.getData();
if (fileUri != null) {
String filePath = fileUri.getPath();
if (filePath != null) {
Intent mvBootsoundIntent = new Intent();
mvBootsoundIntent.setAction(MOVE_BOOTSOUND_INTENT);
mvBootsoundIntent.putExtra("fileName", filePath);
sendBroadcast(mvBootsoundIntent);
}
}
}
break;
case REQUEST_CODE_PICK_FILE:
if (resultCode == RESULT_OK && data != null) {
// obtain the filename
Uri fileUri = data.getData();
if (fileUri != null) {
String filePath = fileUri.getPath();
if (filePath != null) {
Intent mvBootIntent = new Intent();
mvBootIntent.setAction(MOVE_BOOT_INTENT);
mvBootIntent.putExtra("fileName", filePath);
sendBroadcast(mvBootIntent);
}
}
}
break;
case REQUEST_CODE_PREVIEW_FILE:
if (resultCode == RESULT_OK && data != null) {
Uri fileUri = data.getData();
if (fileUri != null) {
String filePath = fileUri.getPath();
if (filePath != null) {
try {
FileOutputStream outfile = context.openFileOutput(BOOT_PREVIEW_FILE, Context.MODE_WORLD_READABLE);
outfile.write(filePath.getBytes());
outfile.close();
} catch (Exception e) { }
mBootPreviewRunning = true;
prevOrientation = getRequestedOrientation();
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
SystemProperties.set( "service.bootanim.exit", "0");
SystemProperties.set("ctl.start", "bootanim");
}
}
}
break;
}
}
|
diff --git a/crypto/src/org/bouncycastle/cms/CMSEnvelopedDataStreamGenerator.java b/crypto/src/org/bouncycastle/cms/CMSEnvelopedDataStreamGenerator.java
index 21fc5c38..4aadc7f3 100644
--- a/crypto/src/org/bouncycastle/cms/CMSEnvelopedDataStreamGenerator.java
+++ b/crypto/src/org/bouncycastle/cms/CMSEnvelopedDataStreamGenerator.java
@@ -1,328 +1,328 @@
package org.bouncycastle.cms;
import org.bouncycastle.asn1.ASN1EncodableVector;
import org.bouncycastle.asn1.BEROctetStringGenerator;
import org.bouncycastle.asn1.BERSequenceGenerator;
import org.bouncycastle.asn1.BERSet;
import org.bouncycastle.asn1.DERInteger;
import org.bouncycastle.asn1.DERSet;
import org.bouncycastle.asn1.cms.CMSObjectIdentifiers;
import org.bouncycastle.asn1.pkcs.PKCSObjectIdentifiers;
import org.bouncycastle.asn1.x509.AlgorithmIdentifier;
import javax.crypto.Cipher;
import javax.crypto.CipherOutputStream;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import java.io.IOException;
import java.io.OutputStream;
import java.security.AlgorithmParameters;
import java.security.GeneralSecurityException;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.SecureRandom;
import java.util.Iterator;
/**
* General class for generating a CMS enveloped-data message stream.
* <p>
* A simple example of usage.
* <pre>
* CMSEnvelopedDataStreamGenerator edGen = new CMSEnvelopedDataStreamGenerator();
*
* edGen.addKeyTransRecipient(cert);
*
* ByteArrayOutputStream bOut = new ByteArrayOutputStream();
*
* OutputStream out = edGen.open(
* bOut, CMSEnvelopedDataGenerator.AES128_CBC, "BC");*
* out.write(data);
*
* out.close();
* </pre>
*/
public class CMSEnvelopedDataStreamGenerator
extends CMSEnvelopedGenerator
{
private Object _originatorInfo = null;
private Object _unprotectedAttributes = null;
private int _bufferSize;
private boolean _berEncodeRecipientSet;
/**
* base constructor
*/
public CMSEnvelopedDataStreamGenerator()
{
}
/**
* constructor allowing specific source of randomness
* @param rand instance of SecureRandom to use
*/
public CMSEnvelopedDataStreamGenerator(
SecureRandom rand)
{
super(rand);
}
/**
* Set the underlying string size for encapsulated data
*
* @param bufferSize length of octet strings to buffer the data.
*/
public void setBufferSize(
int bufferSize)
{
_bufferSize = bufferSize;
}
/**
* Use a BER Set to store the recipient information
*/
public void setBEREncodeRecipients(
boolean berEncodeRecipientSet)
{
_berEncodeRecipientSet = berEncodeRecipientSet;
}
private DERInteger getVersion()
{
if (_originatorInfo != null || _unprotectedAttributes != null)
{
return new DERInteger(2);
}
else
{
return new DERInteger(0);
}
}
/**
* generate an enveloped object that contains an CMS Enveloped Data
* object using the given provider and the passed in key generator.
* @throws IOException
*/
private OutputStream open(
OutputStream out,
String encryptionOID,
KeyGenerator keyGen,
String provider)
throws NoSuchAlgorithmException, NoSuchProviderException, CMSException
{
String encProvider = keyGen.getProvider().getName();
SecretKey encKey = keyGen.generateKey();
AlgorithmParameters params = generateParameters(encryptionOID, encKey, encProvider);
Iterator it = recipientInfs.iterator();
ASN1EncodableVector recipientInfos = new ASN1EncodableVector();
while (it.hasNext())
{
RecipientInf recipient = (RecipientInf)it.next();
try
{
recipientInfos.add(recipient.toRecipientInfo(encKey, rand, provider));
}
catch (IOException e)
{
throw new CMSException("encoding error.", e);
}
catch (InvalidKeyException e)
{
throw new CMSException("key inappropriate for algorithm.", e);
}
catch (GeneralSecurityException e)
{
throw new CMSException("error making encrypted content.", e);
}
}
return open(out, encryptionOID, encKey, params, recipientInfos, encProvider);
}
protected OutputStream open(
OutputStream out,
String encryptionOID,
SecretKey encKey,
AlgorithmParameters params,
ASN1EncodableVector recipientInfos,
String provider)
throws NoSuchAlgorithmException, NoSuchProviderException, CMSException
{
try
{
//
// ContentInfo
//
BERSequenceGenerator cGen = new BERSequenceGenerator(out);
cGen.addObject(CMSObjectIdentifiers.envelopedData);
//
// Encrypted Data
//
BERSequenceGenerator envGen = new BERSequenceGenerator(cGen.getRawOutputStream(), 0, true);
envGen.addObject(getVersion());
if (_berEncodeRecipientSet)
{
envGen.getRawOutputStream().write(new BERSet(recipientInfos).getEncoded());
}
else
{
envGen.getRawOutputStream().write(new DERSet(recipientInfos).getEncoded());
}
Cipher cipher = CMSEnvelopedHelper.INSTANCE.getSymmetricCipher(encryptionOID, provider);
cipher.init(Cipher.ENCRYPT_MODE, encKey, params, rand);
BERSequenceGenerator eiGen = new BERSequenceGenerator(envGen.getRawOutputStream());
eiGen.addObject(PKCSObjectIdentifiers.data);
//
// If params are null we try and second guess on them as some providers don't provide
- // algorithm parameter generation explicity but instead generate them under the hood.
+ // algorithm parameter generation explicitly but instead generate them under the hood.
//
if (params == null)
{
params = cipher.getParameters();
}
AlgorithmIdentifier encAlgId = getAlgorithmIdentifier(encryptionOID, params);
eiGen.getRawOutputStream().write(encAlgId.getEncoded());
BEROctetStringGenerator octGen = new BEROctetStringGenerator(eiGen.getRawOutputStream(), 0, false);
CipherOutputStream cOut;
if (_bufferSize != 0)
{
cOut = new CipherOutputStream(octGen.getOctetOutputStream(new byte[_bufferSize]), cipher);
}
else
{
cOut = new CipherOutputStream(octGen.getOctetOutputStream(), cipher);
}
return new CmsEnvelopedDataOutputStream(cOut, cGen, envGen, eiGen);
}
catch (InvalidKeyException e)
{
throw new CMSException("key invalid in message.", e);
}
catch (NoSuchPaddingException e)
{
throw new CMSException("required padding not supported.", e);
}
catch (InvalidAlgorithmParameterException e)
{
throw new CMSException("algorithm parameters invalid.", e);
}
catch (IOException e)
{
throw new CMSException("exception decoding algorithm parameters.", e);
}
}
/**
* generate an enveloped object that contains an CMS Enveloped Data
* object using the given provider.
* @throws IOException
*/
public OutputStream open(
OutputStream out,
String encryptionOID,
String provider)
throws NoSuchAlgorithmException, NoSuchProviderException, CMSException, IOException
{
KeyGenerator keyGen = CMSEnvelopedHelper.INSTANCE.createSymmetricKeyGenerator(encryptionOID, provider);
keyGen.init(rand);
return open(out, encryptionOID, keyGen, provider);
}
/**
* generate an enveloped object that contains an CMS Enveloped Data
* object using the given provider.
* @throws IOException
*/
public OutputStream open(
OutputStream out,
String encryptionOID,
int keySize,
String provider)
throws NoSuchAlgorithmException, NoSuchProviderException, CMSException, IOException
{
KeyGenerator keyGen = CMSEnvelopedHelper.INSTANCE.createSymmetricKeyGenerator(encryptionOID, provider);
keyGen.init(keySize, rand);
return open(out, encryptionOID, keyGen, provider);
}
private class CmsEnvelopedDataOutputStream
extends OutputStream
{
private CipherOutputStream _out;
private BERSequenceGenerator _cGen;
private BERSequenceGenerator _envGen;
private BERSequenceGenerator _eiGen;
public CmsEnvelopedDataOutputStream(
CipherOutputStream out,
BERSequenceGenerator cGen,
BERSequenceGenerator envGen,
BERSequenceGenerator eiGen)
{
_out = out;
_cGen = cGen;
_envGen = envGen;
_eiGen = eiGen;
}
public void write(
int b)
throws IOException
{
_out.write(b);
}
public void write(
byte[] bytes,
int off,
int len)
throws IOException
{
_out.write(bytes, off, len);
}
public void write(
byte[] bytes)
throws IOException
{
_out.write(bytes);
}
public void close()
throws IOException
{
_out.close();
_eiGen.close();
// [TODO] unprotected attributes go here
_envGen.close();
_cGen.close();
}
}
}
| true | true | protected OutputStream open(
OutputStream out,
String encryptionOID,
SecretKey encKey,
AlgorithmParameters params,
ASN1EncodableVector recipientInfos,
String provider)
throws NoSuchAlgorithmException, NoSuchProviderException, CMSException
{
try
{
//
// ContentInfo
//
BERSequenceGenerator cGen = new BERSequenceGenerator(out);
cGen.addObject(CMSObjectIdentifiers.envelopedData);
//
// Encrypted Data
//
BERSequenceGenerator envGen = new BERSequenceGenerator(cGen.getRawOutputStream(), 0, true);
envGen.addObject(getVersion());
if (_berEncodeRecipientSet)
{
envGen.getRawOutputStream().write(new BERSet(recipientInfos).getEncoded());
}
else
{
envGen.getRawOutputStream().write(new DERSet(recipientInfos).getEncoded());
}
Cipher cipher = CMSEnvelopedHelper.INSTANCE.getSymmetricCipher(encryptionOID, provider);
cipher.init(Cipher.ENCRYPT_MODE, encKey, params, rand);
BERSequenceGenerator eiGen = new BERSequenceGenerator(envGen.getRawOutputStream());
eiGen.addObject(PKCSObjectIdentifiers.data);
//
// If params are null we try and second guess on them as some providers don't provide
// algorithm parameter generation explicity but instead generate them under the hood.
//
if (params == null)
{
params = cipher.getParameters();
}
AlgorithmIdentifier encAlgId = getAlgorithmIdentifier(encryptionOID, params);
eiGen.getRawOutputStream().write(encAlgId.getEncoded());
BEROctetStringGenerator octGen = new BEROctetStringGenerator(eiGen.getRawOutputStream(), 0, false);
CipherOutputStream cOut;
if (_bufferSize != 0)
{
cOut = new CipherOutputStream(octGen.getOctetOutputStream(new byte[_bufferSize]), cipher);
}
else
{
cOut = new CipherOutputStream(octGen.getOctetOutputStream(), cipher);
}
return new CmsEnvelopedDataOutputStream(cOut, cGen, envGen, eiGen);
}
catch (InvalidKeyException e)
{
throw new CMSException("key invalid in message.", e);
}
catch (NoSuchPaddingException e)
{
throw new CMSException("required padding not supported.", e);
}
catch (InvalidAlgorithmParameterException e)
{
throw new CMSException("algorithm parameters invalid.", e);
}
catch (IOException e)
{
throw new CMSException("exception decoding algorithm parameters.", e);
}
}
| protected OutputStream open(
OutputStream out,
String encryptionOID,
SecretKey encKey,
AlgorithmParameters params,
ASN1EncodableVector recipientInfos,
String provider)
throws NoSuchAlgorithmException, NoSuchProviderException, CMSException
{
try
{
//
// ContentInfo
//
BERSequenceGenerator cGen = new BERSequenceGenerator(out);
cGen.addObject(CMSObjectIdentifiers.envelopedData);
//
// Encrypted Data
//
BERSequenceGenerator envGen = new BERSequenceGenerator(cGen.getRawOutputStream(), 0, true);
envGen.addObject(getVersion());
if (_berEncodeRecipientSet)
{
envGen.getRawOutputStream().write(new BERSet(recipientInfos).getEncoded());
}
else
{
envGen.getRawOutputStream().write(new DERSet(recipientInfos).getEncoded());
}
Cipher cipher = CMSEnvelopedHelper.INSTANCE.getSymmetricCipher(encryptionOID, provider);
cipher.init(Cipher.ENCRYPT_MODE, encKey, params, rand);
BERSequenceGenerator eiGen = new BERSequenceGenerator(envGen.getRawOutputStream());
eiGen.addObject(PKCSObjectIdentifiers.data);
//
// If params are null we try and second guess on them as some providers don't provide
// algorithm parameter generation explicitly but instead generate them under the hood.
//
if (params == null)
{
params = cipher.getParameters();
}
AlgorithmIdentifier encAlgId = getAlgorithmIdentifier(encryptionOID, params);
eiGen.getRawOutputStream().write(encAlgId.getEncoded());
BEROctetStringGenerator octGen = new BEROctetStringGenerator(eiGen.getRawOutputStream(), 0, false);
CipherOutputStream cOut;
if (_bufferSize != 0)
{
cOut = new CipherOutputStream(octGen.getOctetOutputStream(new byte[_bufferSize]), cipher);
}
else
{
cOut = new CipherOutputStream(octGen.getOctetOutputStream(), cipher);
}
return new CmsEnvelopedDataOutputStream(cOut, cGen, envGen, eiGen);
}
catch (InvalidKeyException e)
{
throw new CMSException("key invalid in message.", e);
}
catch (NoSuchPaddingException e)
{
throw new CMSException("required padding not supported.", e);
}
catch (InvalidAlgorithmParameterException e)
{
throw new CMSException("algorithm parameters invalid.", e);
}
catch (IOException e)
{
throw new CMSException("exception decoding algorithm parameters.", e);
}
}
|
diff --git a/grails/src/persistence/org/codehaus/groovy/grails/orm/hibernate/cfg/GrailsHibernateUtil.java b/grails/src/persistence/org/codehaus/groovy/grails/orm/hibernate/cfg/GrailsHibernateUtil.java
index 30997a4eb..daef30107 100644
--- a/grails/src/persistence/org/codehaus/groovy/grails/orm/hibernate/cfg/GrailsHibernateUtil.java
+++ b/grails/src/persistence/org/codehaus/groovy/grails/orm/hibernate/cfg/GrailsHibernateUtil.java
@@ -1,243 +1,243 @@
/* Copyright 2004-2005 Graeme Rocher
*
* 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.groovy.grails.orm.hibernate.cfg;
import groovy.lang.GroovyObject;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.codehaus.groovy.grails.commons.DomainClassArtefactHandler;
import org.codehaus.groovy.grails.commons.GrailsApplication;
import org.codehaus.groovy.grails.commons.GrailsClassUtils;
import org.codehaus.groovy.grails.commons.GrailsDomainClass;
import org.codehaus.groovy.grails.commons.metaclass.DynamicMethods;
import org.codehaus.groovy.grails.commons.spring.GrailsRuntimeConfigurator;
import org.codehaus.groovy.grails.orm.hibernate.GrailsHibernateDomainClass;
import org.codehaus.groovy.grails.orm.hibernate.metaclass.DomainClassMethods;
import org.hibernate.Criteria;
import org.hibernate.EntityMode;
import org.hibernate.FetchMode;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Order;
import org.hibernate.metadata.ClassMetadata;
import org.springframework.beans.SimpleTypeConverter;
import org.springframework.context.ApplicationContext;
import java.beans.IntrospectionException;
import java.io.Serializable;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.lang.reflect.InvocationTargetException;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
/**
* A class containing utility methods for configuring Hibernate inside Grails
*
* @author Graeme Rocher
* @since 0.4
* <p/>
* Created: Jan 19, 2007
* Time: 6:21:01 PM
*/
public class GrailsHibernateUtil {
private static final Log LOG = LogFactory.getLog(GrailsHibernateUtil.class);
public static SimpleTypeConverter converter = new SimpleTypeConverter();
public static final String ARGUMENT_MAX = "max";
public static final String ARGUMENT_OFFSET = "offset";
public static final String ARGUMENT_ORDER = "order";
public static final String ARGUMENT_SORT = "sort";
public static final String ORDER_DESC = "desc";
public static final String ORDER_ASC = "asc";
public static final String ARGUMENT_FETCH = "fetch";
public static final String ARGUMENT_IGNORE_CASE = "ignoreCase";
private static final Class[] EMPTY_CLASS_ARRAY = new Class[0];
public static Serializable getAssociationIdentifier(Object target, String propertyName, GrailsDomainClass referencedDomainClass) {
String getterName = GrailsClassUtils.getGetterName(propertyName);
try {
Method m = target.getClass().getDeclaredMethod(getterName, EMPTY_CLASS_ARRAY);
Object value = m.invoke(target, null);
if(value != null && referencedDomainClass != null) {
String identifierGetter = GrailsClassUtils.getGetterName(referencedDomainClass.getIdentifier().getName());
m = value.getClass().getDeclaredMethod(identifierGetter, EMPTY_CLASS_ARRAY);
return (Serializable)m.invoke(value, null);
}
} catch (NoSuchMethodException e) {
// ignore
} catch (IllegalAccessException e) {
// ignore
} catch (InvocationTargetException e) {
// ignore
}
return null;
}
public static void configureDynamicMethods(SessionFactory sessionFactory, GrailsApplication application) {
LOG.trace("Configuring dynamic methods");
// if its not a grails domain class and one written in java then add it
// to grails
Collection classMetaData = sessionFactory.getAllClassMetadata().values();
for (Iterator i = classMetaData.iterator(); i.hasNext();) {
ClassMetadata cmd = (ClassMetadata) i.next();
Class persistentClass = cmd.getMappedClass(EntityMode.POJO);
configureDynamicMethodsFor(sessionFactory, application, persistentClass);
}
}
/**
* Configures dynamic methods on all Hibernate mapped domain classes that are found in the application context
*
* @param applicationContext The session factory instance
* @param application The grails application instance
*/
public static void configureDynamicMethods(ApplicationContext applicationContext, GrailsApplication application) {
LOG.trace("Configuring dynamic methods");
if (applicationContext == null)
throw new IllegalArgumentException("Cannot configure dynamic methods for null ApplicationContext");
SessionFactory sessionFactory = (SessionFactory) applicationContext.getBean(GrailsRuntimeConfigurator.SESSION_FACTORY_BEAN);
configureDynamicMethods(sessionFactory, application);
}
public static DynamicMethods configureDynamicMethodsFor(SessionFactory sessionFactory, GrailsApplication application, Class persistentClass) {
if (LOG.isTraceEnabled()) {
LOG.trace("Registering dynamic methods on class [" + persistentClass + "]");
}
DynamicMethods dm = null;
try {
dm = new DomainClassMethods(application, persistentClass, sessionFactory, application.getClassLoader());
} catch (IntrospectionException e) {
LOG.warn("Introspection exception registering dynamic methods for [" + persistentClass + "]:" + e.getMessage(), e);
}
return dm;
}
public static void configureHibernateDomainClasses(SessionFactory sessionFactory, GrailsApplication application) {
Map hibernateDomainClassMap = new HashMap();
for (Iterator i = sessionFactory.getAllClassMetadata().values().iterator(); i.hasNext();) {
ClassMetadata classMetadata = (ClassMetadata) i.next();
configureDomainClass(sessionFactory, application, classMetadata, classMetadata.getMappedClass(EntityMode.POJO), hibernateDomainClassMap);
}
configureInheritanceMappings(hibernateDomainClassMap);
}
public static void configureInheritanceMappings(Map hibernateDomainClassMap) {
// now get through all domainclasses, and add all subclasses to root class
for (Iterator it = hibernateDomainClassMap.values().iterator(); it.hasNext();) {
GrailsDomainClass baseClass = (GrailsDomainClass) it.next();
if (!baseClass.isRoot()) {
Class superClass = baseClass
.getClazz().getSuperclass();
while (!superClass.equals(Object.class) && !superClass.equals(GroovyObject.class)) {
GrailsDomainClass gdc = (GrailsDomainClass) hibernateDomainClassMap.get(superClass.getName());
if (gdc == null || gdc.getSubClasses() == null) {
LOG.error("did not find superclass names when mapping inheritance....");
break;
}
gdc.getSubClasses().add(baseClass);
superClass = superClass.getSuperclass();
}
}
}
}
private static void configureDomainClass(SessionFactory sessionFactory, GrailsApplication application, ClassMetadata cmd, Class persistentClass, Map hibernateDomainClassMap) {
if (!Modifier.isAbstract(persistentClass.getModifiers())) {
LOG.trace("Configuring domain class [" + persistentClass + "]");
GrailsDomainClass dc = (GrailsDomainClass) application.getArtefact(DomainClassArtefactHandler.TYPE, persistentClass.getName());
if (dc == null) {
// a patch to add inheritance to this system
GrailsHibernateDomainClass ghdc = new
GrailsHibernateDomainClass(persistentClass, sessionFactory, cmd);
hibernateDomainClassMap.put(persistentClass.getName(),
ghdc);
dc = (GrailsDomainClass) application.addArtefact(DomainClassArtefactHandler.TYPE, ghdc);
}
}
}
public static void populateArgumentsForCriteria(Criteria c, Map argMap) {
Integer maxParam = null;
Integer offsetParam = null;
if(argMap.containsKey(ARGUMENT_MAX)) {
maxParam = (Integer)converter.convertIfNecessary(argMap.get(ARGUMENT_MAX),Integer.class);
}
if(argMap.containsKey(ARGUMENT_OFFSET)) {
offsetParam = (Integer)converter.convertIfNecessary(argMap.get(ARGUMENT_OFFSET),Integer.class);
}
String orderParam = (String)argMap.get(ARGUMENT_ORDER);
Object fetchObj = argMap.get(ARGUMENT_FETCH);
if(fetchObj instanceof Map) {
Map fetch = (Map)fetchObj;
for (Iterator i = fetch.keySet().iterator(); i.hasNext();) {
String associationName = (String) i.next();
- c.setFetchMode(associationName, getFetchMode(fetch.get(i)));
+ c.setFetchMode(associationName, getFetchMode(fetch.get(associationName)));
}
}
final String sort = (String)argMap.get(ARGUMENT_SORT);
final String order = ORDER_DESC.equalsIgnoreCase(orderParam) ? ORDER_DESC : ORDER_ASC;
final int max = maxParam == null ? -1 : maxParam.intValue();
final int offset = offsetParam == null ? -1 : offsetParam.intValue();
if(max > -1)
c.setMaxResults(max);
if(offset > -1)
c.setFirstResult(offset);
if(sort != null) {
boolean ignoreCase = true;
Object caseArg = argMap.get(ARGUMENT_IGNORE_CASE);
if(caseArg instanceof Boolean) {
ignoreCase = ((Boolean)caseArg).booleanValue();
}
if(ORDER_DESC.equals(order)) {
c.addOrder( ignoreCase ? Order.desc(sort).ignoreCase() : Order.desc(sort));
}
else {
c.addOrder( ignoreCase ? Order.asc(sort).ignoreCase() : Order.asc(sort) );
}
}
}
/**
* Will retrieve the fetch mode for the specified instance other wise return the
* default FetchMode
*
* @param object The object, converted to a string
* @return The FetchMode
*/
public static FetchMode getFetchMode(Object object) {
String name = object != null ? object.toString() : "default";
if(name.equals(FetchMode.JOIN.toString()) || name.equals("eager")) {
return FetchMode.JOIN;
}
else if(name.equals(FetchMode.SELECT.toString()) || name.equals("lazy")) {
return FetchMode.SELECT;
}
return FetchMode.DEFAULT;
}
}
| true | true | public static void populateArgumentsForCriteria(Criteria c, Map argMap) {
Integer maxParam = null;
Integer offsetParam = null;
if(argMap.containsKey(ARGUMENT_MAX)) {
maxParam = (Integer)converter.convertIfNecessary(argMap.get(ARGUMENT_MAX),Integer.class);
}
if(argMap.containsKey(ARGUMENT_OFFSET)) {
offsetParam = (Integer)converter.convertIfNecessary(argMap.get(ARGUMENT_OFFSET),Integer.class);
}
String orderParam = (String)argMap.get(ARGUMENT_ORDER);
Object fetchObj = argMap.get(ARGUMENT_FETCH);
if(fetchObj instanceof Map) {
Map fetch = (Map)fetchObj;
for (Iterator i = fetch.keySet().iterator(); i.hasNext();) {
String associationName = (String) i.next();
c.setFetchMode(associationName, getFetchMode(fetch.get(i)));
}
}
final String sort = (String)argMap.get(ARGUMENT_SORT);
final String order = ORDER_DESC.equalsIgnoreCase(orderParam) ? ORDER_DESC : ORDER_ASC;
final int max = maxParam == null ? -1 : maxParam.intValue();
final int offset = offsetParam == null ? -1 : offsetParam.intValue();
if(max > -1)
c.setMaxResults(max);
if(offset > -1)
c.setFirstResult(offset);
if(sort != null) {
boolean ignoreCase = true;
Object caseArg = argMap.get(ARGUMENT_IGNORE_CASE);
if(caseArg instanceof Boolean) {
ignoreCase = ((Boolean)caseArg).booleanValue();
}
if(ORDER_DESC.equals(order)) {
c.addOrder( ignoreCase ? Order.desc(sort).ignoreCase() : Order.desc(sort));
}
else {
c.addOrder( ignoreCase ? Order.asc(sort).ignoreCase() : Order.asc(sort) );
}
}
}
| public static void populateArgumentsForCriteria(Criteria c, Map argMap) {
Integer maxParam = null;
Integer offsetParam = null;
if(argMap.containsKey(ARGUMENT_MAX)) {
maxParam = (Integer)converter.convertIfNecessary(argMap.get(ARGUMENT_MAX),Integer.class);
}
if(argMap.containsKey(ARGUMENT_OFFSET)) {
offsetParam = (Integer)converter.convertIfNecessary(argMap.get(ARGUMENT_OFFSET),Integer.class);
}
String orderParam = (String)argMap.get(ARGUMENT_ORDER);
Object fetchObj = argMap.get(ARGUMENT_FETCH);
if(fetchObj instanceof Map) {
Map fetch = (Map)fetchObj;
for (Iterator i = fetch.keySet().iterator(); i.hasNext();) {
String associationName = (String) i.next();
c.setFetchMode(associationName, getFetchMode(fetch.get(associationName)));
}
}
final String sort = (String)argMap.get(ARGUMENT_SORT);
final String order = ORDER_DESC.equalsIgnoreCase(orderParam) ? ORDER_DESC : ORDER_ASC;
final int max = maxParam == null ? -1 : maxParam.intValue();
final int offset = offsetParam == null ? -1 : offsetParam.intValue();
if(max > -1)
c.setMaxResults(max);
if(offset > -1)
c.setFirstResult(offset);
if(sort != null) {
boolean ignoreCase = true;
Object caseArg = argMap.get(ARGUMENT_IGNORE_CASE);
if(caseArg instanceof Boolean) {
ignoreCase = ((Boolean)caseArg).booleanValue();
}
if(ORDER_DESC.equals(order)) {
c.addOrder( ignoreCase ? Order.desc(sort).ignoreCase() : Order.desc(sort));
}
else {
c.addOrder( ignoreCase ? Order.asc(sort).ignoreCase() : Order.asc(sort) );
}
}
}
|
diff --git a/code/src/gui.java b/code/src/gui.java
index b203020..f96f083 100644
--- a/code/src/gui.java
+++ b/code/src/gui.java
@@ -1,148 +1,148 @@
import java.awt.Color;
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import javax.swing.JButton;
import javax.swing.JFrame;
@SuppressWarnings("serial")
public class gui extends JFrame{
private JButton login = new JButton("login");
private JButton zoek = new JButton("zoek");
private JButton home = new JButton("home");
private JButton nee = new JButton("nee");
private JButton ja = new JButton("ja");
private inlogPanel inlog = new inlogPanel();
private liedjeInvoerPanel invoer = new liedjeInvoerPanel();
private static verificatiePanel verificatieUser = new verificatiePanel();
private static feedbackSysteemPanel recommendation = new feedbackSysteemPanel() ;
private Lied gezocht;
private User naam;
private Container container;
public gui (){
setTitle("groep5");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(1200,700);
setLocation(0,0);
container = getContentPane();
container.setLayout(new FlowLayout());
container.setBackground(Color.white);
startScreen();
setVisible(true);
}
public void startScreen(){
container.add(inlog);
container.add(login);
login.addMouseListener(new mouseHandler());
inlog.setVisible(true);
login.setVisible(true);
}
public void liedjeInvoerScreen(){
container.add(invoer);
container.add(zoek);
zoek.addMouseListener(new mouseHandler());
invoer.setVisible(true);
zoek.setVisible(true);
}
public void verificatieScreen(){
container.add(verificatieUser);
container.add(ja);
container.add(nee);
ja.addMouseListener(new mouseHandler());
nee.addMouseListener(new mouseHandler());
verificatieUser.setVisible(true);
nee.setVisible(true);
ja.setVisible(true);
}
public void reccomendatieScreen(){
container.setLayout(null);
recommendation.addPanelSong();
container.add(recommendation);
container.add(home);
recommendation.setBounds(30, 30, 1130,300);
home.setBounds(550, 350, 60, 30);
recommendation.setVisible(true);
home.setVisible(true);
home.addMouseListener(new mouseHandler());
}
public Lied getInvoer(){
return invoer.getLiedje();
}
public User getNaamInvoer(){
return inlog.getUser();
}
public static void setVerificatie(Lied invoer){
verificatieUser.setVerificatie(invoer);
}
public static void setFeedbackPanel(ArrayList<Lied> invoer){
recommendation.makeTable(invoer.size());
for(int i = 0; i < invoer.size(); i++)
{
recommendation.addSong(invoer.get(i), i);
}
recommendation.adjustColumns();
}
//hier worden de mouse inputs verwerkt
class mouseHandler extends MouseAdapter{
public void mouseClicked(MouseEvent e){
if(e.getSource()==login){
inlog.setVisible(false);
login.setVisible(false);
container.remove(inlog);
container.remove(login);
naam = getNaamInvoer();
liedjeInvoerScreen();
}
if(e.getSource()==zoek){
invoer.setVisible(false);
zoek.setVisible(false);
container.remove(invoer);
container.remove(zoek);
gezocht = getInvoer();
controller.findSong(gezocht);
verificatieScreen();
}
if(e.getSource()==ja){
ja.setVisible(false);
nee.setVisible(false);
verificatieUser.setVisible(false);
container.remove(ja);
container.remove(nee);
container.remove(verificatieUser);
//hier wordt er van de verificatie weer een Lied object gemaakt
//Als we weten wat voor object er wordt gemaakt in de controller zouden we deze ook in de gui opslaan
//zo hoeven we niet twee keer te zoeken
recommendation.clearList();
controller.findSimilarSongs(gezocht);
reccomendatieScreen();
}
if(e.getSource()==nee){
ja.setVisible(false);
nee.setVisible(false);
verificatieUser.setVisible(false);
container.remove(ja);
container.remove(nee);
container.remove(verificatieUser);
- startScreen();
+ liedjeInvoerScreen();
}
if(e.getSource()==home){
home.setVisible(false);
recommendation.setVisible(false);
container.remove(recommendation);
container.remove(home);
container.setLayout(new FlowLayout());
- startScreen();
+ liedjeInvoerScreen();
}
}
}
}
| false | true | public void mouseClicked(MouseEvent e){
if(e.getSource()==login){
inlog.setVisible(false);
login.setVisible(false);
container.remove(inlog);
container.remove(login);
naam = getNaamInvoer();
liedjeInvoerScreen();
}
if(e.getSource()==zoek){
invoer.setVisible(false);
zoek.setVisible(false);
container.remove(invoer);
container.remove(zoek);
gezocht = getInvoer();
controller.findSong(gezocht);
verificatieScreen();
}
if(e.getSource()==ja){
ja.setVisible(false);
nee.setVisible(false);
verificatieUser.setVisible(false);
container.remove(ja);
container.remove(nee);
container.remove(verificatieUser);
//hier wordt er van de verificatie weer een Lied object gemaakt
//Als we weten wat voor object er wordt gemaakt in de controller zouden we deze ook in de gui opslaan
//zo hoeven we niet twee keer te zoeken
recommendation.clearList();
controller.findSimilarSongs(gezocht);
reccomendatieScreen();
}
if(e.getSource()==nee){
ja.setVisible(false);
nee.setVisible(false);
verificatieUser.setVisible(false);
container.remove(ja);
container.remove(nee);
container.remove(verificatieUser);
startScreen();
}
if(e.getSource()==home){
home.setVisible(false);
recommendation.setVisible(false);
container.remove(recommendation);
container.remove(home);
container.setLayout(new FlowLayout());
startScreen();
}
}
| public void mouseClicked(MouseEvent e){
if(e.getSource()==login){
inlog.setVisible(false);
login.setVisible(false);
container.remove(inlog);
container.remove(login);
naam = getNaamInvoer();
liedjeInvoerScreen();
}
if(e.getSource()==zoek){
invoer.setVisible(false);
zoek.setVisible(false);
container.remove(invoer);
container.remove(zoek);
gezocht = getInvoer();
controller.findSong(gezocht);
verificatieScreen();
}
if(e.getSource()==ja){
ja.setVisible(false);
nee.setVisible(false);
verificatieUser.setVisible(false);
container.remove(ja);
container.remove(nee);
container.remove(verificatieUser);
//hier wordt er van de verificatie weer een Lied object gemaakt
//Als we weten wat voor object er wordt gemaakt in de controller zouden we deze ook in de gui opslaan
//zo hoeven we niet twee keer te zoeken
recommendation.clearList();
controller.findSimilarSongs(gezocht);
reccomendatieScreen();
}
if(e.getSource()==nee){
ja.setVisible(false);
nee.setVisible(false);
verificatieUser.setVisible(false);
container.remove(ja);
container.remove(nee);
container.remove(verificatieUser);
liedjeInvoerScreen();
}
if(e.getSource()==home){
home.setVisible(false);
recommendation.setVisible(false);
container.remove(recommendation);
container.remove(home);
container.setLayout(new FlowLayout());
liedjeInvoerScreen();
}
}
|
diff --git a/src/com/android/contacts/ImportVCardActivity.java b/src/com/android/contacts/ImportVCardActivity.java
index 9b2ca2ceb..30b6cbf5a 100644
--- a/src/com/android/contacts/ImportVCardActivity.java
+++ b/src/com/android/contacts/ImportVCardActivity.java
@@ -1,877 +1,875 @@
/*
* Copyright (C) 2009 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.contacts;
import android.accounts.Account;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.DialogInterface.OnCancelListener;
import android.content.DialogInterface.OnClickListener;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.PowerManager;
import android.pim.vcard.VCardConfig;
import android.pim.vcard.VCardEntryCommitter;
import android.pim.vcard.VCardEntryConstructor;
import android.pim.vcard.VCardEntryCounter;
import android.pim.vcard.VCardInterpreter;
import android.pim.vcard.VCardInterpreterCollection;
import android.pim.vcard.VCardParser_V21;
import android.pim.vcard.VCardParser_V30;
import android.pim.vcard.VCardSourceDetector;
import android.pim.vcard.exception.VCardException;
import android.pim.vcard.exception.VCardNestedException;
import android.pim.vcard.exception.VCardNotSupportedException;
import android.pim.vcard.exception.VCardVersionException;
import android.provider.ContactsContract.RawContacts;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.style.RelativeSizeSpan;
import android.util.Log;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Set;
import java.util.Vector;
class VCardFile {
private String mName;
private String mCanonicalPath;
private long mLastModified;
public VCardFile(String name, String canonicalPath, long lastModified) {
mName = name;
mCanonicalPath = canonicalPath;
mLastModified = lastModified;
}
public String getName() {
return mName;
}
public String getCanonicalPath() {
return mCanonicalPath;
}
public long getLastModified() {
return mLastModified;
}
}
/**
* Class for importing vCard. Several user interaction will be required while reading
* (selecting a file, waiting a moment, etc.)
*
* Note that this Activity assumes that the instance is a "one-shot Activity", which will be
* finished (with the method {@link Activity#finish()}) after the import and never reuse
* any Dialog in the instance. So this code is careless about the management around managed
* dialogs stuffs (like how onCreateDialog() is used).
*/
public class ImportVCardActivity extends Activity {
private static final String LOG_TAG = "ImportVCardActivity";
private static final boolean DO_PERFORMANCE_PROFILE = false;
private Handler mHandler = new Handler();
private Account mAccount;
private ProgressDialog mProgressDialogForScanVCard;
private List<VCardFile> mAllVCardFileList;
private VCardScanThread mVCardScanThread;
private VCardReadThread mVCardReadThread;
private ProgressDialog mProgressDialogForReadVCard;
private String mErrorMessage;
private boolean mNeedReview = false;
private class DialogDisplayer implements Runnable {
private final int mResId;
public DialogDisplayer(int resId) {
mResId = resId;
}
public DialogDisplayer(String errorMessage) {
mResId = R.id.dialog_error_with_message;
mErrorMessage = errorMessage;
}
public void run() {
// Show the Dialog only when the parent Activity is still alive.
if (!ImportVCardActivity.this.isFinishing()) {
showDialog(mResId);
}
}
}
private class CancelListener
implements DialogInterface.OnClickListener, DialogInterface.OnCancelListener {
public void onClick(DialogInterface dialog, int which) {
finish();
}
public void onCancel(DialogInterface dialog) {
finish();
}
}
private CancelListener mCancelListener = new CancelListener();
private class VCardReadThread extends Thread
implements DialogInterface.OnCancelListener {
private ContentResolver mResolver;
private VCardParser_V21 mVCardParser;
private boolean mCanceled;
private PowerManager.WakeLock mWakeLock;
private Uri mUri;
private List<VCardFile> mSelectedVCardFileList;
private List<String> mErrorFileNameList;
public VCardReadThread(Uri uri) {
mUri = uri;
init();
}
public VCardReadThread(final List<VCardFile> selectedVCardFileList) {
mSelectedVCardFileList = selectedVCardFileList;
mErrorFileNameList = new ArrayList<String>();
init();
}
private void init() {
Context context = ImportVCardActivity.this;
mResolver = context.getContentResolver();
PowerManager powerManager = (PowerManager)context.getSystemService(
Context.POWER_SERVICE);
mWakeLock = powerManager.newWakeLock(
PowerManager.SCREEN_DIM_WAKE_LOCK |
PowerManager.ON_AFTER_RELEASE, LOG_TAG);
}
@Override
public void finalize() {
if (mWakeLock != null && mWakeLock.isHeld()) {
mWakeLock.release();
}
}
@Override
public void run() {
boolean shouldCallFinish = true;
mWakeLock.acquire();
Uri createdUri = null;
// Some malicious vCard data may make this thread broken
// (e.g. OutOfMemoryError).
// Even in such cases, some should be done.
try {
if (mUri != null) { // Read one vCard expressed by mUri
mProgressDialogForReadVCard.setProgressNumberFormat("");
mProgressDialogForReadVCard.setProgress(0);
// Count the number of VCard entries
mProgressDialogForReadVCard.setIndeterminate(true);
long start;
if (DO_PERFORMANCE_PROFILE) {
start = System.currentTimeMillis();
}
VCardEntryCounter counter = new VCardEntryCounter();
VCardSourceDetector detector = new VCardSourceDetector();
VCardInterpreterCollection builderCollection = new VCardInterpreterCollection(
Arrays.asList(counter, detector));
boolean result;
try {
result = readOneVCardFile(mUri,
VCardConfig.DEFAULT_CHARSET, builderCollection, null, true, null);
} catch (VCardNestedException e) {
try {
// Assume that VCardSourceDetector was able to detect the source.
// Try again with the detector.
result = readOneVCardFile(mUri,
VCardConfig.DEFAULT_CHARSET, counter, detector, false, null);
} catch (VCardNestedException e2) {
result = false;
Log.e(LOG_TAG, "Must not reach here. " + e2);
}
}
if (DO_PERFORMANCE_PROFILE) {
long time = System.currentTimeMillis() - start;
Log.d(LOG_TAG, "time for counting the number of vCard entries: " +
time + " ms");
}
if (!result) {
shouldCallFinish = false;
return;
}
mProgressDialogForReadVCard.setProgressNumberFormat(
getString(R.string.reading_vcard_contacts));
mProgressDialogForReadVCard.setIndeterminate(false);
mProgressDialogForReadVCard.setMax(counter.getCount());
String charset = detector.getEstimatedCharset();
createdUri = doActuallyReadOneVCard(mUri, null, charset, true, detector,
mErrorFileNameList);
} else { // Read multiple files.
mProgressDialogForReadVCard.setProgressNumberFormat(
getString(R.string.reading_vcard_files));
mProgressDialogForReadVCard.setMax(mSelectedVCardFileList.size());
mProgressDialogForReadVCard.setProgress(0);
for (VCardFile vcardFile : mSelectedVCardFileList) {
if (mCanceled) {
return;
}
final Uri uri = Uri.parse("file://" + vcardFile.getCanonicalPath());
VCardSourceDetector detector = new VCardSourceDetector();
try {
if (!readOneVCardFile(uri, VCardConfig.DEFAULT_CHARSET,
detector, null, true, mErrorFileNameList)) {
continue;
}
} catch (VCardNestedException e) {
// Assume that VCardSourceDetector was able to detect the source.
}
String charset = detector.getEstimatedCharset();
createdUri = doActuallyReadOneVCard(uri, mAccount,
charset, false, detector, mErrorFileNameList);
mProgressDialogForReadVCard.incrementProgressBy(1);
}
}
} finally {
mWakeLock.release();
mProgressDialogForReadVCard.dismiss();
// finish() is called via mCancelListener, which is used in DialogDisplayer.
if (shouldCallFinish && !isFinishing()) {
if (mErrorFileNameList == null || mErrorFileNameList.isEmpty()) {
finish();
if (mNeedReview) {
mNeedReview = false;
Log.v("importVCardActivity", "Prepare to review the imported contact");
// get contact_id of this raw_contact
- Log.v("importVCardActivity", "RawContactUri: " + createdUri);
final long rawContactId = ContentUris.parseId(createdUri);
- Log.v("importVCardActivity", "RawContactId: " + rawContactId);
Uri contactUri = RawContacts.getContactLookupUri(getContentResolver(),
- ContentUris.withAppendedId(RawContacts.CONTENT_URI, rawContactId));
- Log.v("importVCardActivity", "Contact Uri: " + contactUri);
+ ContentUris.withAppendedId(RawContacts.CONTENT_URI,
+ rawContactId));
Intent viewIntent = new Intent(Intent.ACTION_VIEW, contactUri);
startActivity(viewIntent);
}
} else {
StringBuilder builder = new StringBuilder();
boolean first = true;
for (String fileName : mErrorFileNameList) {
if (first) {
first = false;
} else {
builder.append(", ");
}
builder.append(fileName);
}
mHandler.post(new DialogDisplayer(
getString(R.string.fail_reason_failed_to_read_files,
builder.toString())));
}
}
}
}
private Uri doActuallyReadOneVCard(Uri uri, Account account,
String charset, boolean showEntryParseProgress,
VCardSourceDetector detector, List<String> errorFileNameList) {
final Context context = ImportVCardActivity.this;
VCardEntryConstructor builder;
final String currentLanguage = Locale.getDefault().getLanguage();
int vcardType = VCardConfig.getVCardTypeFromString(
context.getString(R.string.config_import_vcard_type));
if (charset != null) {
builder = new VCardEntryConstructor(charset, charset, false, vcardType, mAccount);
} else {
charset = VCardConfig.DEFAULT_CHARSET;
builder = new VCardEntryConstructor(null, null, false, vcardType, mAccount);
}
VCardEntryCommitter committer = new VCardEntryCommitter(mResolver);
builder.addEntryHandler(committer);
if (showEntryParseProgress) {
builder.addEntryHandler(new ProgressShower(mProgressDialogForReadVCard,
context.getString(R.string.reading_vcard_message),
ImportVCardActivity.this,
mHandler));
}
try {
if (!readOneVCardFile(uri, charset, builder, detector, false, null)) {
return null;
}
} catch (VCardNestedException e) {
Log.e(LOG_TAG, "Never reach here.");
}
return committer.getLastCreatedUri();
}
private boolean readOneVCardFile(Uri uri, String charset,
VCardInterpreter builder, VCardSourceDetector detector,
boolean throwNestedException, List<String> errorFileNameList)
throws VCardNestedException {
InputStream is;
try {
is = mResolver.openInputStream(uri);
mVCardParser = new VCardParser_V21(detector);
try {
mVCardParser.parse(is, charset, builder, mCanceled);
} catch (VCardVersionException e1) {
try {
is.close();
} catch (IOException e) {
}
if (builder instanceof VCardEntryConstructor) {
// Let the object clean up internal temporal objects,
((VCardEntryConstructor)builder).clear();
}
is = mResolver.openInputStream(uri);
try {
mVCardParser = new VCardParser_V30();
mVCardParser.parse(is, charset, builder, mCanceled);
} catch (VCardVersionException e2) {
throw new VCardException("vCard with unspported version.");
}
} finally {
if (is != null) {
try {
is.close();
} catch (IOException e) {
}
}
}
} catch (IOException e) {
Log.e(LOG_TAG, "IOException was emitted: " + e.getMessage());
mProgressDialogForReadVCard.dismiss();
if (errorFileNameList != null) {
errorFileNameList.add(uri.toString());
} else {
mHandler.post(new DialogDisplayer(
getString(R.string.fail_reason_io_error) +
": " + e.getLocalizedMessage()));
}
return false;
} catch (VCardNotSupportedException e) {
if ((e instanceof VCardNestedException) && throwNestedException) {
throw (VCardNestedException)e;
}
if (errorFileNameList != null) {
errorFileNameList.add(uri.toString());
} else {
mHandler.post(new DialogDisplayer(
getString(R.string.fail_reason_vcard_not_supported_error) +
" (" + e.getMessage() + ")"));
}
return false;
} catch (VCardException e) {
if (errorFileNameList != null) {
errorFileNameList.add(uri.toString());
} else {
mHandler.post(new DialogDisplayer(
getString(R.string.fail_reason_vcard_parse_error) +
" (" + e.getMessage() + ")"));
}
return false;
}
return true;
}
public void cancel() {
mCanceled = true;
if (mVCardParser != null) {
mVCardParser.cancel();
}
}
public void onCancel(DialogInterface dialog) {
cancel();
}
}
private class ImportTypeSelectedListener implements
DialogInterface.OnClickListener {
public static final int IMPORT_ONE = 0;
public static final int IMPORT_MULTIPLE = 1;
public static final int IMPORT_ALL = 2;
public static final int IMPORT_TYPE_SIZE = 3;
private int mCurrentIndex;
public void onClick(DialogInterface dialog, int which) {
if (which == DialogInterface.BUTTON_POSITIVE) {
switch (mCurrentIndex) {
case IMPORT_ALL:
importMultipleVCardFromSDCard(mAllVCardFileList);
break;
case IMPORT_MULTIPLE:
showDialog(R.id.dialog_select_multiple_vcard);
break;
default:
showDialog(R.id.dialog_select_one_vcard);
break;
}
} else if (which == DialogInterface.BUTTON_NEGATIVE) {
finish();
} else {
mCurrentIndex = which;
}
}
}
private class VCardSelectedListener implements
DialogInterface.OnClickListener, DialogInterface.OnMultiChoiceClickListener {
private int mCurrentIndex;
private Set<Integer> mSelectedIndexSet;
public VCardSelectedListener(boolean multipleSelect) {
mCurrentIndex = 0;
if (multipleSelect) {
mSelectedIndexSet = new HashSet<Integer>();
}
}
public void onClick(DialogInterface dialog, int which) {
if (which == DialogInterface.BUTTON_POSITIVE) {
if (mSelectedIndexSet != null) {
List<VCardFile> selectedVCardFileList = new ArrayList<VCardFile>();
int size = mAllVCardFileList.size();
// We'd like to sort the files by its index, so we do not use Set iterator.
for (int i = 0; i < size; i++) {
if (mSelectedIndexSet.contains(i)) {
selectedVCardFileList.add(mAllVCardFileList.get(i));
}
}
importMultipleVCardFromSDCard(selectedVCardFileList);
} else {
String canonicalPath = mAllVCardFileList.get(mCurrentIndex).getCanonicalPath();
final Uri uri = Uri.parse("file://" + canonicalPath);
importOneVCardFromSDCard(uri);
}
} else if (which == DialogInterface.BUTTON_NEGATIVE) {
finish();
} else {
// Some file is selected.
mCurrentIndex = which;
if (mSelectedIndexSet != null) {
if (mSelectedIndexSet.contains(which)) {
mSelectedIndexSet.remove(which);
} else {
mSelectedIndexSet.add(which);
}
}
}
}
public void onClick(DialogInterface dialog, int which, boolean isChecked) {
if (mSelectedIndexSet == null || (mSelectedIndexSet.contains(which) == isChecked)) {
Log.e(LOG_TAG, String.format("Inconsist state in index %d (%s)", which,
mAllVCardFileList.get(which).getCanonicalPath()));
} else {
onClick(dialog, which);
}
}
}
/**
* Thread scanning VCard from SDCard. After scanning, the dialog which lets a user select
* a vCard file is shown. After the choice, VCardReadThread starts running.
*/
private class VCardScanThread extends Thread implements OnCancelListener, OnClickListener {
private boolean mCanceled;
private boolean mGotIOException;
private File mRootDirectory;
// To avoid recursive link.
private Set<String> mCheckedPaths;
private PowerManager.WakeLock mWakeLock;
private class CanceledException extends Exception {
}
public VCardScanThread(File sdcardDirectory) {
mCanceled = false;
mGotIOException = false;
mRootDirectory = sdcardDirectory;
mCheckedPaths = new HashSet<String>();
PowerManager powerManager = (PowerManager)ImportVCardActivity.this.getSystemService(
Context.POWER_SERVICE);
mWakeLock = powerManager.newWakeLock(
PowerManager.SCREEN_DIM_WAKE_LOCK |
PowerManager.ON_AFTER_RELEASE, LOG_TAG);
}
@Override
public void run() {
mAllVCardFileList = new Vector<VCardFile>();
try {
mWakeLock.acquire();
getVCardFileRecursively(mRootDirectory);
} catch (CanceledException e) {
mCanceled = true;
} catch (IOException e) {
mGotIOException = true;
} finally {
mWakeLock.release();
}
if (mCanceled) {
mAllVCardFileList = null;
}
mProgressDialogForScanVCard.dismiss();
mProgressDialogForScanVCard = null;
if (mGotIOException) {
mHandler.post(new DialogDisplayer(R.id.dialog_io_exception));
} else if (mCanceled) {
finish();
} else {
int size = mAllVCardFileList.size();
final Context context = ImportVCardActivity.this;
if (size == 0) {
mHandler.post(new DialogDisplayer(R.id.dialog_vcard_not_found));
} else {
startVCardSelectAndImport();
}
}
}
private void getVCardFileRecursively(File directory)
throws CanceledException, IOException {
if (mCanceled) {
throw new CanceledException();
}
// e.g. secured directory may return null toward listFiles().
final File[] files = directory.listFiles();
if (files == null) {
Log.w(LOG_TAG, "listFiles() returned null (directory: " + directory + ")");
return;
}
for (File file : directory.listFiles()) {
if (mCanceled) {
throw new CanceledException();
}
String canonicalPath = file.getCanonicalPath();
if (mCheckedPaths.contains(canonicalPath)) {
continue;
}
mCheckedPaths.add(canonicalPath);
if (file.isDirectory()) {
getVCardFileRecursively(file);
} else if (canonicalPath.toLowerCase().endsWith(".vcf") &&
file.canRead()){
String fileName = file.getName();
VCardFile vcardFile = new VCardFile(
fileName, canonicalPath, file.lastModified());
mAllVCardFileList.add(vcardFile);
}
}
}
public void onCancel(DialogInterface dialog) {
mCanceled = true;
}
public void onClick(DialogInterface dialog, int which) {
if (which == DialogInterface.BUTTON_NEGATIVE) {
mCanceled = true;
}
}
}
private void startVCardSelectAndImport() {
int size = mAllVCardFileList.size();
if (getResources().getBoolean(R.bool.config_import_all_vcard_from_sdcard_automatically)) {
importMultipleVCardFromSDCard(mAllVCardFileList);
} else if (size == 1) {
String canonicalPath = mAllVCardFileList.get(0).getCanonicalPath();
Uri uri = Uri.parse("file://" + canonicalPath);
importOneVCardFromSDCard(uri);
} else if (getResources().getBoolean(R.bool.config_allow_users_select_all_vcard_import)) {
mHandler.post(new DialogDisplayer(R.id.dialog_select_import_type));
} else {
mHandler.post(new DialogDisplayer(R.id.dialog_select_one_vcard));
}
}
private void importMultipleVCardFromSDCard(final List<VCardFile> selectedVCardFileList) {
mHandler.post(new Runnable() {
public void run() {
mVCardReadThread = new VCardReadThread(selectedVCardFileList);
showDialog(R.id.dialog_reading_vcard);
}
});
}
private void importOneVCardFromSDCard(final Uri uri) {
mHandler.post(new Runnable() {
public void run() {
mVCardReadThread = new VCardReadThread(uri);
showDialog(R.id.dialog_reading_vcard);
}
});
}
private Dialog getSelectImportTypeDialog() {
DialogInterface.OnClickListener listener =
new ImportTypeSelectedListener();
AlertDialog.Builder builder = new AlertDialog.Builder(this)
.setTitle(R.string.select_vcard_title)
.setPositiveButton(android.R.string.ok, listener)
.setOnCancelListener(mCancelListener)
.setNegativeButton(android.R.string.cancel, mCancelListener);
String[] items = new String[ImportTypeSelectedListener.IMPORT_TYPE_SIZE];
items[ImportTypeSelectedListener.IMPORT_ONE] =
getString(R.string.import_one_vcard_string);
items[ImportTypeSelectedListener.IMPORT_MULTIPLE] =
getString(R.string.import_multiple_vcard_string);
items[ImportTypeSelectedListener.IMPORT_ALL] =
getString(R.string.import_all_vcard_string);
builder.setSingleChoiceItems(items, ImportTypeSelectedListener.IMPORT_ONE, listener);
return builder.create();
}
private Dialog getVCardFileSelectDialog(boolean multipleSelect) {
int size = mAllVCardFileList.size();
VCardSelectedListener listener = new VCardSelectedListener(multipleSelect);
AlertDialog.Builder builder =
new AlertDialog.Builder(this)
.setTitle(R.string.select_vcard_title)
.setPositiveButton(android.R.string.ok, listener)
.setOnCancelListener(mCancelListener)
.setNegativeButton(android.R.string.cancel, mCancelListener);
CharSequence[] items = new CharSequence[size];
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
for (int i = 0; i < size; i++) {
VCardFile vcardFile = mAllVCardFileList.get(i);
SpannableStringBuilder stringBuilder = new SpannableStringBuilder();
stringBuilder.append(vcardFile.getName());
stringBuilder.append('\n');
int indexToBeSpanned = stringBuilder.length();
// Smaller date text looks better, since each file name becomes easier to read.
// The value set to RelativeSizeSpan is arbitrary. You can change it to any other
// value (but the value bigger than 1.0f would not make nice appearance :)
stringBuilder.append(
"(" + dateFormat.format(new Date(vcardFile.getLastModified())) + ")");
stringBuilder.setSpan(
new RelativeSizeSpan(0.7f), indexToBeSpanned, stringBuilder.length(),
Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
items[i] = stringBuilder;
}
if (multipleSelect) {
builder.setMultiChoiceItems(items, (boolean[])null, listener);
} else {
builder.setSingleChoiceItems(items, 0, listener);
}
return builder.create();
}
@Override
protected void onCreate(Bundle bundle) {
super.onCreate(bundle);
Intent intent = getIntent();
if (intent != null) {
final String accountName = intent.getStringExtra("account_name");
final String accountType = intent.getStringExtra("account_type");
if (!TextUtils.isEmpty(accountName) && !TextUtils.isEmpty(accountType)) {
mAccount = new Account(accountName, accountType);
}
} else {
Log.e(LOG_TAG, "intent does not exist");
}
final String action = intent.getAction();
final Uri uri = intent.getData();
Log.v(LOG_TAG, "action = " + action + " ; path = " + uri);
if (Intent.ACTION_VIEW.equals(action)) {
// Import the file directly and then go to EDIT screen
mNeedReview = true;
}
if (uri != null) {
importOneVCardFromSDCard(uri);
} else {
startImportVCardFromSdCard();
}
}
@Override
protected Dialog onCreateDialog(int resId) {
switch (resId) {
case R.id.dialog_searching_vcard: {
if (mProgressDialogForScanVCard == null) {
String title = getString(R.string.searching_vcard_title);
String message = getString(R.string.searching_vcard_message);
mProgressDialogForScanVCard =
ProgressDialog.show(this, title, message, true, false);
mProgressDialogForScanVCard.setOnCancelListener(mVCardScanThread);
mVCardScanThread.start();
}
return mProgressDialogForScanVCard;
}
case R.id.dialog_sdcard_not_found: {
AlertDialog.Builder builder = new AlertDialog.Builder(this)
.setTitle(R.string.no_sdcard_title)
.setIcon(android.R.drawable.ic_dialog_alert)
.setMessage(R.string.no_sdcard_message)
.setOnCancelListener(mCancelListener)
.setPositiveButton(android.R.string.ok, mCancelListener);
return builder.create();
}
case R.id.dialog_vcard_not_found: {
String message = (getString(R.string.scanning_sdcard_failed_message,
getString(R.string.fail_reason_no_vcard_file)));
AlertDialog.Builder builder = new AlertDialog.Builder(this)
.setTitle(R.string.scanning_sdcard_failed_title)
.setMessage(message)
.setOnCancelListener(mCancelListener)
.setPositiveButton(android.R.string.ok, mCancelListener);
return builder.create();
}
case R.id.dialog_select_import_type: {
return getSelectImportTypeDialog();
}
case R.id.dialog_select_multiple_vcard: {
return getVCardFileSelectDialog(true);
}
case R.id.dialog_select_one_vcard: {
return getVCardFileSelectDialog(false);
}
case R.id.dialog_reading_vcard: {
if (mProgressDialogForReadVCard == null) {
String title = getString(R.string.reading_vcard_title);
String message = getString(R.string.reading_vcard_message);
mProgressDialogForReadVCard = new ProgressDialog(this);
mProgressDialogForReadVCard.setTitle(title);
mProgressDialogForReadVCard.setMessage(message);
mProgressDialogForReadVCard.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
mProgressDialogForReadVCard.setOnCancelListener(mVCardReadThread);
mVCardReadThread.start();
}
return mProgressDialogForReadVCard;
}
case R.id.dialog_io_exception: {
String message = (getString(R.string.scanning_sdcard_failed_message,
getString(R.string.fail_reason_io_error)));
AlertDialog.Builder builder = new AlertDialog.Builder(this)
.setTitle(R.string.scanning_sdcard_failed_title)
.setIcon(android.R.drawable.ic_dialog_alert)
.setMessage(message)
.setOnCancelListener(mCancelListener)
.setPositiveButton(android.R.string.ok, mCancelListener);
return builder.create();
}
case R.id.dialog_error_with_message: {
String message = mErrorMessage;
if (TextUtils.isEmpty(message)) {
Log.e(LOG_TAG, "Error message is null while it must not.");
message = getString(R.string.fail_reason_unknown);
}
AlertDialog.Builder builder = new AlertDialog.Builder(this)
.setTitle(getString(R.string.reading_vcard_failed_title))
.setIcon(android.R.drawable.ic_dialog_alert)
.setMessage(message)
.setOnCancelListener(mCancelListener)
.setPositiveButton(android.R.string.ok, mCancelListener);
return builder.create();
}
}
return super.onCreateDialog(resId);
}
@Override
protected void onStop() {
super.onStop();
if (mVCardReadThread != null) {
// The Activity is no longer visible. Stop the thread.
mVCardReadThread.cancel();
mVCardReadThread = null;
}
// ImportVCardActivity should not be persistent. In other words, if there's some
// event calling onStop(), this Activity should finish its work and give the main
// screen back to the caller Activity.
if (!isFinishing()) {
finish();
}
}
@Override
public void finalize() {
if (mVCardReadThread != null) {
// Not sure this procedure is really needed, but just in case...
Log.w(LOG_TAG, "VCardReadThread exists while this Activity is now being killed!");
mVCardReadThread.cancel();
mVCardReadThread = null;
}
}
/* public methods */
/**
* Tries to start importing VCard. If there's no SDCard available,
* an error dialog is shown. If there is, start scanning using another thread
* and shows a progress dialog. Several interactions will occur.
* This method should be called from a thread with a looper (like Activity).
*/
public void startImportVCardFromSdCard() {
// TODO: should use getExternalStorageState().
final File file = Environment.getExternalStorageDirectory();
if (!file.exists() || !file.isDirectory() || !file.canRead()) {
showDialog(R.id.dialog_sdcard_not_found);
} else {
mVCardScanThread = new VCardScanThread(file);
showDialog(R.id.dialog_searching_vcard);
}
}
}
| false | true | public void run() {
boolean shouldCallFinish = true;
mWakeLock.acquire();
Uri createdUri = null;
// Some malicious vCard data may make this thread broken
// (e.g. OutOfMemoryError).
// Even in such cases, some should be done.
try {
if (mUri != null) { // Read one vCard expressed by mUri
mProgressDialogForReadVCard.setProgressNumberFormat("");
mProgressDialogForReadVCard.setProgress(0);
// Count the number of VCard entries
mProgressDialogForReadVCard.setIndeterminate(true);
long start;
if (DO_PERFORMANCE_PROFILE) {
start = System.currentTimeMillis();
}
VCardEntryCounter counter = new VCardEntryCounter();
VCardSourceDetector detector = new VCardSourceDetector();
VCardInterpreterCollection builderCollection = new VCardInterpreterCollection(
Arrays.asList(counter, detector));
boolean result;
try {
result = readOneVCardFile(mUri,
VCardConfig.DEFAULT_CHARSET, builderCollection, null, true, null);
} catch (VCardNestedException e) {
try {
// Assume that VCardSourceDetector was able to detect the source.
// Try again with the detector.
result = readOneVCardFile(mUri,
VCardConfig.DEFAULT_CHARSET, counter, detector, false, null);
} catch (VCardNestedException e2) {
result = false;
Log.e(LOG_TAG, "Must not reach here. " + e2);
}
}
if (DO_PERFORMANCE_PROFILE) {
long time = System.currentTimeMillis() - start;
Log.d(LOG_TAG, "time for counting the number of vCard entries: " +
time + " ms");
}
if (!result) {
shouldCallFinish = false;
return;
}
mProgressDialogForReadVCard.setProgressNumberFormat(
getString(R.string.reading_vcard_contacts));
mProgressDialogForReadVCard.setIndeterminate(false);
mProgressDialogForReadVCard.setMax(counter.getCount());
String charset = detector.getEstimatedCharset();
createdUri = doActuallyReadOneVCard(mUri, null, charset, true, detector,
mErrorFileNameList);
} else { // Read multiple files.
mProgressDialogForReadVCard.setProgressNumberFormat(
getString(R.string.reading_vcard_files));
mProgressDialogForReadVCard.setMax(mSelectedVCardFileList.size());
mProgressDialogForReadVCard.setProgress(0);
for (VCardFile vcardFile : mSelectedVCardFileList) {
if (mCanceled) {
return;
}
final Uri uri = Uri.parse("file://" + vcardFile.getCanonicalPath());
VCardSourceDetector detector = new VCardSourceDetector();
try {
if (!readOneVCardFile(uri, VCardConfig.DEFAULT_CHARSET,
detector, null, true, mErrorFileNameList)) {
continue;
}
} catch (VCardNestedException e) {
// Assume that VCardSourceDetector was able to detect the source.
}
String charset = detector.getEstimatedCharset();
createdUri = doActuallyReadOneVCard(uri, mAccount,
charset, false, detector, mErrorFileNameList);
mProgressDialogForReadVCard.incrementProgressBy(1);
}
}
} finally {
mWakeLock.release();
mProgressDialogForReadVCard.dismiss();
// finish() is called via mCancelListener, which is used in DialogDisplayer.
if (shouldCallFinish && !isFinishing()) {
if (mErrorFileNameList == null || mErrorFileNameList.isEmpty()) {
finish();
if (mNeedReview) {
mNeedReview = false;
Log.v("importVCardActivity", "Prepare to review the imported contact");
// get contact_id of this raw_contact
Log.v("importVCardActivity", "RawContactUri: " + createdUri);
final long rawContactId = ContentUris.parseId(createdUri);
Log.v("importVCardActivity", "RawContactId: " + rawContactId);
Uri contactUri = RawContacts.getContactLookupUri(getContentResolver(),
ContentUris.withAppendedId(RawContacts.CONTENT_URI, rawContactId));
Log.v("importVCardActivity", "Contact Uri: " + contactUri);
Intent viewIntent = new Intent(Intent.ACTION_VIEW, contactUri);
startActivity(viewIntent);
}
} else {
StringBuilder builder = new StringBuilder();
boolean first = true;
for (String fileName : mErrorFileNameList) {
if (first) {
first = false;
} else {
builder.append(", ");
}
builder.append(fileName);
}
mHandler.post(new DialogDisplayer(
getString(R.string.fail_reason_failed_to_read_files,
builder.toString())));
}
}
}
}
| public void run() {
boolean shouldCallFinish = true;
mWakeLock.acquire();
Uri createdUri = null;
// Some malicious vCard data may make this thread broken
// (e.g. OutOfMemoryError).
// Even in such cases, some should be done.
try {
if (mUri != null) { // Read one vCard expressed by mUri
mProgressDialogForReadVCard.setProgressNumberFormat("");
mProgressDialogForReadVCard.setProgress(0);
// Count the number of VCard entries
mProgressDialogForReadVCard.setIndeterminate(true);
long start;
if (DO_PERFORMANCE_PROFILE) {
start = System.currentTimeMillis();
}
VCardEntryCounter counter = new VCardEntryCounter();
VCardSourceDetector detector = new VCardSourceDetector();
VCardInterpreterCollection builderCollection = new VCardInterpreterCollection(
Arrays.asList(counter, detector));
boolean result;
try {
result = readOneVCardFile(mUri,
VCardConfig.DEFAULT_CHARSET, builderCollection, null, true, null);
} catch (VCardNestedException e) {
try {
// Assume that VCardSourceDetector was able to detect the source.
// Try again with the detector.
result = readOneVCardFile(mUri,
VCardConfig.DEFAULT_CHARSET, counter, detector, false, null);
} catch (VCardNestedException e2) {
result = false;
Log.e(LOG_TAG, "Must not reach here. " + e2);
}
}
if (DO_PERFORMANCE_PROFILE) {
long time = System.currentTimeMillis() - start;
Log.d(LOG_TAG, "time for counting the number of vCard entries: " +
time + " ms");
}
if (!result) {
shouldCallFinish = false;
return;
}
mProgressDialogForReadVCard.setProgressNumberFormat(
getString(R.string.reading_vcard_contacts));
mProgressDialogForReadVCard.setIndeterminate(false);
mProgressDialogForReadVCard.setMax(counter.getCount());
String charset = detector.getEstimatedCharset();
createdUri = doActuallyReadOneVCard(mUri, null, charset, true, detector,
mErrorFileNameList);
} else { // Read multiple files.
mProgressDialogForReadVCard.setProgressNumberFormat(
getString(R.string.reading_vcard_files));
mProgressDialogForReadVCard.setMax(mSelectedVCardFileList.size());
mProgressDialogForReadVCard.setProgress(0);
for (VCardFile vcardFile : mSelectedVCardFileList) {
if (mCanceled) {
return;
}
final Uri uri = Uri.parse("file://" + vcardFile.getCanonicalPath());
VCardSourceDetector detector = new VCardSourceDetector();
try {
if (!readOneVCardFile(uri, VCardConfig.DEFAULT_CHARSET,
detector, null, true, mErrorFileNameList)) {
continue;
}
} catch (VCardNestedException e) {
// Assume that VCardSourceDetector was able to detect the source.
}
String charset = detector.getEstimatedCharset();
createdUri = doActuallyReadOneVCard(uri, mAccount,
charset, false, detector, mErrorFileNameList);
mProgressDialogForReadVCard.incrementProgressBy(1);
}
}
} finally {
mWakeLock.release();
mProgressDialogForReadVCard.dismiss();
// finish() is called via mCancelListener, which is used in DialogDisplayer.
if (shouldCallFinish && !isFinishing()) {
if (mErrorFileNameList == null || mErrorFileNameList.isEmpty()) {
finish();
if (mNeedReview) {
mNeedReview = false;
Log.v("importVCardActivity", "Prepare to review the imported contact");
// get contact_id of this raw_contact
final long rawContactId = ContentUris.parseId(createdUri);
Uri contactUri = RawContacts.getContactLookupUri(getContentResolver(),
ContentUris.withAppendedId(RawContacts.CONTENT_URI,
rawContactId));
Intent viewIntent = new Intent(Intent.ACTION_VIEW, contactUri);
startActivity(viewIntent);
}
} else {
StringBuilder builder = new StringBuilder();
boolean first = true;
for (String fileName : mErrorFileNameList) {
if (first) {
first = false;
} else {
builder.append(", ");
}
builder.append(fileName);
}
mHandler.post(new DialogDisplayer(
getString(R.string.fail_reason_failed_to_read_files,
builder.toString())));
}
}
}
}
|
diff --git a/source/de/anomic/server/serverSystem.java b/source/de/anomic/server/serverSystem.java
index 7c70b882b..afac6c399 100644
--- a/source/de/anomic/server/serverSystem.java
+++ b/source/de/anomic/server/serverSystem.java
@@ -1,430 +1,431 @@
// serverSystem.java
// -------------------------------------------
// (C) by Michael Peter Christen; [email protected]
// first published on http://www.anomic.de
// Frankfurt, Germany, 2004
// last major change: 11.03.2004
//
// 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 de.anomic.server;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.util.Hashtable;
import java.util.Properties;
import java.util.Vector;
import de.anomic.server.logging.serverLog;
public final class serverSystem {
// constants for system identification
public static final int systemMacOSC = 0; // 'classic' Mac OS 7.6.1/8.*/9.*
public static final int systemMacOSX = 1; // all Mac OS X
public static final int systemUnix = 2; // all Unix/Linux type systems
public static final int systemWindows = 3; // all Windows 95/98/NT/2K/XP
public static final int systemUnknown = -1; // any other system
// constants for file type identification (Mac only)
public static final String blankTypeString = "____";
// system-identification statics
public static int systemOS = systemUnknown;
public static boolean isMacArchitecture = false;
public static boolean isUnixFS = false;
public static boolean canExecUnix = false;
public static boolean isWindows = false;
// calculated system constants
public static int maxPathLength = 65535;
// Macintosh-specific statics
private static Class<?> macMRJFileUtils = null;
private static Class<?> macMRJOSType = null;
private static Constructor<?> macMRJOSTypeConstructor = null;
private static Object macMRJOSNullObj = null;
private static Method macGetFileCreator = null;
private static Method macGetFileType = null;
private static Method macSetFileCreator = null;
private static Method macSetFileType = null;
private static Method macOpenURL = null;
public static Hashtable<String, String> macFSTypeCache = null;
public static Hashtable<String, String> macFSCreatorCache = null;
// static initialization
static {
// check operation system type
Properties sysprop = System.getProperties();
String sysname = sysprop.getProperty("os.name","").toLowerCase();
if (sysname.startsWith("mac os x")) systemOS = systemMacOSX;
else if (sysname.startsWith("mac os")) systemOS = systemMacOSC;
else if (sysname.startsWith("windows")) systemOS = systemWindows;
else if ((sysname.startsWith("linux")) || (sysname.startsWith("unix"))) systemOS = systemUnix;
else systemOS = systemUnknown;
isMacArchitecture = ((systemOS == systemMacOSC) || (systemOS == systemMacOSX));
isUnixFS = ((systemOS == systemMacOSX) || (systemOS == systemUnix));
canExecUnix = ((isUnixFS) || (!((systemOS == systemMacOSC) || (systemOS == systemWindows))));
isWindows = (systemOS == systemWindows);
// set up the MRJ Methods through reflection
if (isMacArchitecture) try {
macMRJFileUtils = Class.forName("com.apple.mrj.MRJFileUtils");
macMRJOSType = Class.forName("com.apple.mrj.MRJOSType");
macGetFileType = macMRJFileUtils.getMethod("getFileType", new Class[] {Class.forName("java.io.File")});
macGetFileCreator = macMRJFileUtils.getMethod("getFileCreator", new Class[] {Class.forName("java.io.File")});
macSetFileType = macMRJFileUtils.getMethod("setFileType", new Class[] {Class.forName("java.io.File"), macMRJOSType});
macSetFileCreator = macMRJFileUtils.getMethod("setFileCreator", new Class[] {Class.forName("java.io.File"), macMRJOSType});
macMRJOSTypeConstructor = macMRJOSType.getConstructor(new Class[] {Class.forName("java.lang.String")});
macOpenURL = macMRJFileUtils.getMethod("openURL", new Class[] {Class.forName("java.lang.String")});
byte[] nullb = new byte[4];
for (int i = 0; i < 4; i++) nullb[i] = 0;
macMRJOSNullObj = macMRJOSTypeConstructor.newInstance(new Object[] {new String(nullb)});
macFSTypeCache = new Hashtable<String, String>();
macFSCreatorCache = new Hashtable<String, String>();
} catch (Exception e) {
//e.printStackTrace();
macMRJFileUtils = null; macMRJOSType = null;
}
// set up maximum path length according to system
if (isWindows) maxPathLength = 255; else maxPathLength = 65535;
}
/* public static boolean isWindows() {
return systemOS == systemWindows;
}*/
public static Object getMacOSTS(String s) {
if ((isMacArchitecture) && (macMRJFileUtils != null)) try {
if ((s == null) || (s.equals(blankTypeString))) return macMRJOSNullObj;
else return macMRJOSTypeConstructor.newInstance(new Object[] {s});
} catch (Exception e) {
return macMRJOSNullObj;
} else return null;
}
public static String getMacFSType(File f) {
if ((isMacArchitecture) && (macMRJFileUtils != null)) try {
String s = macGetFileType.invoke(null, new Object[] {f}).toString();
if ((s == null) || (s.charAt(0) == 0)) return blankTypeString; else return s;
} catch (Exception e) {
return null;
} else return null;
}
public static String getMacFSCreator(File f) {
if ((isMacArchitecture) && (macMRJFileUtils != null)) try {
String s = macGetFileCreator.invoke(null, new Object[] {f}).toString();
if ((s == null) || (s.charAt(0) == 0)) return blankTypeString; else return s;
} catch (Exception e) {
return null;
} else return null;
}
public static void setMacFSType(File f, String t) {
if ((isMacArchitecture) && (macMRJFileUtils != null)) try {
macSetFileType.invoke(null, new Object[] {f, getMacOSTS(t)});
} catch (Exception e) {/*System.out.println(e.getMessage()); e.printStackTrace();*/}
}
public static void setMacFSCreator(File f, String t) {
if ((isMacArchitecture) && (macMRJFileUtils != null)) try {
macSetFileCreator.invoke(null, new Object[] {f, getMacOSTS(t)});
} catch (Exception e) {/*System.out.println(e.getMessage()); e.printStackTrace();*/}
}
public static boolean aquireMacFSType(File f) {
if ((!(isMacArchitecture)) || (macMRJFileUtils == null)) return false;
String name = f.toString();
// check file type
int dot = name.lastIndexOf(".");
if ((dot < 0) || (dot + 1 >= name.length())) return false;
String type = getMacFSType(f);
if ((type == null) || (type.equals(blankTypeString))) return false;
String ext = name.substring(dot + 1).toLowerCase();
String oldType = macFSTypeCache.get(ext);
if ((oldType != null) && (oldType.equals(type))) return false;
macFSTypeCache.put(ext, type);
return true;
}
public static boolean aquireMacFSCreator(File f) {
if ((!(isMacArchitecture)) || (macMRJFileUtils == null)) return false;
String name = f.toString();
// check creator
String creator = getMacFSCreator(f);
if ((creator == null) || (creator.equals(blankTypeString))) return false;
String oldCreator = macFSCreatorCache.get(name);
if ((oldCreator != null) && (oldCreator.equals(creator))) return false;
macFSCreatorCache.put(name, creator);
return true;
}
public static boolean applyMacFSType(File f) {
if ((!(isMacArchitecture)) || (macMRJFileUtils == null)) return false;
String name = f.toString();
// reconstruct file type
int dot = name.lastIndexOf(".");
if ((dot < 0) || (dot + 1 >= name.length())) return false;
String type = macFSTypeCache.get(name.substring(dot + 1).toLowerCase());
if (type == null) return false;
String oldType = getMacFSType(f);
if ((oldType != null) && (oldType.equals(type))) return false;
setMacFSType(f, type);
return getMacFSType(f).equals(type);
}
public static boolean applyMacFSCreator(File f) {
if ((!(isMacArchitecture)) || (macMRJFileUtils == null)) return false;
String name = f.toString();
// reconstruct file creator
String creator = macFSCreatorCache.get(name);
if (creator == null) return false;
String oldCreator = getMacFSCreator(f);
if ((oldCreator != null) && (oldCreator.equals(creator))) return false;
//System.out.println("***Setting creator for " + f.toString() + " to " + creator);
setMacFSCreator(f, creator);
return getMacFSCreator(f).equals(creator); // this is not always true! I guess it's caused by deprecation of the interface in 1.4er Apple Extensions
}
public static String infoString() {
String s = "System=";
if (systemOS == systemUnknown) s += "unknown";
else if (systemOS == systemMacOSC) s += "Mac OS Classic";
else if (systemOS == systemMacOSX) s += "Mac OS X";
else if (systemOS == systemUnix) s += "Unix/Linux";
else if (systemOS == systemWindows) s += "Windows";
else s += "unknown";
if (isMacArchitecture) s += ", Mac System Architecture";
if (isUnixFS) s += ", has Unix-like File System";
if (canExecUnix) s += ", can execute Unix-Shell Commands";
return s;
}
/** generates a 2-character string containing information about the OS-type*/
public static String infoKey() {
String s = "";
if (systemOS == systemUnknown) s += "o";
else if (systemOS == systemMacOSC) s += "c";
else if (systemOS == systemMacOSX) s += "x";
else if (systemOS == systemUnix) s += "u";
else if (systemOS == systemWindows) s += "w";
else s += "o";
if (isMacArchitecture) s += "m";
if (isUnixFS) s += "f";
if (canExecUnix) s += "e";
return s;
}
private static String errorResponse(Process p) {
BufferedReader err = new BufferedReader(new InputStreamReader(p.getErrorStream()));
String line, error = "";
try {
while ((line = err.readLine()) != null) {
error = line + "\n";
}
return error;
} catch (IOException e) {
return null;
}
}
/*
public static void openBrowser(URL url) {
if (openBrowserJNLP(url)) return;
openBrowserExec(url.toString(), "firefox");
}
private static boolean openBrowserJNLP(URL url) {
try {
// Lookup the javax.jnlp.BasicService object
javax.jnlp.BasicService bs = (javax.jnlp.BasicService) javax.jnlp.ServiceManager.lookup("javax.jnlp.BasicService");
// Invoke the showDocument method
return bs.showDocument(url);
} catch (Exception ue) {
// Service is not supported
return false;
}
}
*/
public static void openBrowser(String url) {
openBrowser(url, "firefox");
}
public static void openBrowser(String url, String app) {
try {
String cmd;
Process p;
if (systemOS != systemUnknown) {
if (systemOS == systemMacOSC) {
if ((isMacArchitecture) && (macMRJFileUtils != null)) {
macOpenURL.invoke(null, new Object[] {url});
}
} else if (systemOS == systemMacOSX) {
p = Runtime.getRuntime().exec(new String[] {"/usr/bin/osascript", "-e", "open location \"" + url + "\""});
p.waitFor();
if (p.exitValue() != 0) throw new RuntimeException("EXEC ERROR: " + errorResponse(p));
} else if (systemOS == systemUnix) {
cmd = app + " -remote openURL(" + url + ") &";
p = Runtime.getRuntime().exec(cmd);
p.waitFor();
if (p.exitValue() != 0) {
cmd = app + " " + url + " &";
p = Runtime.getRuntime().exec(cmd);
p.waitFor();
}
if (p.exitValue() != 0) throw new RuntimeException("EXEC ERROR: " + errorResponse(p));
} else if (systemOS == systemWindows) {
// see forum at http://forum.java.sun.com/thread.jsp?forum=57&thread=233364&message=838441
- cmd = "rundll32 url.dll,FileProtocolHandler \"" + url + "\"";
+ if (System.getProperty("os.name").contains("2000")) cmd = "rundll32 url.dll,FileProtocolHandler " + url;
+ else cmd = "rundll32 url.dll,FileProtocolHandler \"" + url + "\"";
//cmd = "cmd.exe /c start javascript:document.location='" + url + "'";
p = Runtime.getRuntime().exec(cmd);
p.waitFor();
if (p.exitValue() != 0) throw new RuntimeException("EXEC ERROR: " + errorResponse(p));
}
}
} catch (Exception e) {
System.out.println("please start your browser and open the following location: " + url);
}
}
public static void deployScript(File scriptFile, String theScript) throws IOException {
serverFileUtils.copy(theScript.getBytes(), scriptFile);
if(!isWindows){ // set executable
try {
Runtime.getRuntime().exec("chmod 755 " + scriptFile.getAbsolutePath().replaceAll(" ", "\\ ")).waitFor();
} catch (InterruptedException e) {
serverLog.logSevere("DEPLOY", "deploy of script file failed. file = " + scriptFile.getAbsolutePath(), e);
throw new IOException(e.getMessage());
}
}
}
public static void execAsynchronous(File scriptFile) throws IOException {
// runs a script as separate thread
String starterFileExtension = null;
String script = null;
if(isWindows){
starterFileExtension = ".starter.bat";
// use /K to debug, /C for release
script = "start /MIN CMD /C \"" + scriptFile.getAbsolutePath() + "\"";
} else { // unix/linux
starterFileExtension = ".starter.sh";
script = "#!/bin/sh" + serverCore.LF_STRING + scriptFile.getAbsolutePath().replaceAll(" ", "\\ ") + " &" + serverCore.LF_STRING;
}
File starterFile = new File(scriptFile.getAbsolutePath().replaceAll(" ", "\\ ") + starterFileExtension);
deployScript(starterFile, script);
try {
Runtime.getRuntime().exec(starterFile.getAbsolutePath().replaceAll(" ", "\\ ")).waitFor();
} catch (InterruptedException e) {
throw new IOException(e.getMessage());
}
starterFile.delete();
}
public static Vector<String> execSynchronous(String command) throws IOException {
// runs a unix/linux command and returns output as Vector of Strings
// this method blocks until the command is executed
Process p = Runtime.getRuntime().exec(command);
BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()));
String text;
Vector<String> output = new Vector<String>();
while ((text = in.readLine()) != null) {
output.add(text);
}
return output;
}
public static void main(String[] args) {
//try{System.getProperties().list(new PrintStream(new FileOutputStream(new File("system.properties.txt"))));} catch (FileNotFoundException e) {}
//System.out.println("nullstr=" + macMRJOSNullObj.toString());
if (args[0].equals("-f")) {
File f = new File(args[1]);
System.out.println("File " + f.toString() + ": creator = " + getMacFSCreator(f) + "; type = " + getMacFSType(f));
}
if (args[0].equals("-u")) {
openBrowser(args[1]);
}
}
}
/*
table of common system properties
comparisment between different operation systems
property |Mac OS 9.22 |Mac OSX 10.1.5 |Windows 98 |Linux Kernel 2.4.22 |
-------------------+----------------------+----------------------+----------------------+----------------------+
file.encoding |MacTEC |MacRoman |Cp1252 |ANSI_X3.4-1968 |
file.separator |/ |/ |\ |/ |
java.class.path |/hdisc/... |. |. |/usr/lib/j2se/ext |
java.class.version |45.3 |47.0 |48.0 |47.0 |
java.home |/hdisc/... |/System/Library/... |C:\PROGRAM\... |/usr/lib/j2se/1.3/jre |
java.vendor |Apple Computer, Inc. |Apple Computer, Inc. |Sun Microsystems Inc. |Blackdown Java-Linux |
java.version |1.1.8 |1.3.1 |1.4.0_02 |1.3.1 |
os.arch |PowerPC |ppc |x86 |i386 |
os.name |Mac OS |Mac OS X |Windows 98 |Linux |
os.version |9.2.2 |10.1.5 |4.10 |2.4.22 |
path.separator |: |: |; |: |
user.dir |/hdisc/... |/mydir/... |C:\mydir\... |/home/public |
user.home |/hdisc/... |/Users/myself |C:\WINDOWS |/home/public |
user.language |de |de |de |en |
user.name |Bob |myself |User |public |
user.timezone |ECT |Europe/Berlin |Europe/Berlin | |
-------------------+----------------------+----------------------+----------------------+----------------------+
*/
/*
static struct browser possible_browsers[] = {
{N_("Opera"), "opera"},
{N_("Netscape"), "netscape"},
{N_("Mozilla"), "mozilla"},
{N_("Konqueror"), "kfmclient"},
{N_("Galeon"), "galeon"},
{N_("Firebird"), "mozilla-firebird"},
{N_("Firefox"), "firefox"},
{N_("Gnome Default"), "gnome-open"}
};
new:
command = exec("netscape -remote " "\" openURL(\"%s\",new-window) "", uri);
command = exec("opera -newwindow \"%s\"", uri);
command = exec("opera -newpage \"%s\"", uri);
command = exec("galeon -w \"%s\"", uri);
command = exec("galeon -n \"%s\"", uri);
command = exec("%s -remote \"openURL(\"%s\"," "new-window)\"", web_browser, uri);
command = exec("%s -remote \"openURL(\"%s\"," "new-tab)\"", web_browser, uri);
current:
command = exec("netscape -remote " "\"openURL(\"%s\")\"", uri);
command = exec("opera -remote " "\"openURL(\"%s\")\"", uri);
command = exec("galeon \"%s\"", uri);
command = exec("%s -remote \"openURL(\"%s\")\"", web_browser, uri);
no option:
command = exec("kfmclient openURL \"%s\"", uri);
command = exec("gnome-open \"%s\"", uri);
*/
| true | true | public static void openBrowser(String url, String app) {
try {
String cmd;
Process p;
if (systemOS != systemUnknown) {
if (systemOS == systemMacOSC) {
if ((isMacArchitecture) && (macMRJFileUtils != null)) {
macOpenURL.invoke(null, new Object[] {url});
}
} else if (systemOS == systemMacOSX) {
p = Runtime.getRuntime().exec(new String[] {"/usr/bin/osascript", "-e", "open location \"" + url + "\""});
p.waitFor();
if (p.exitValue() != 0) throw new RuntimeException("EXEC ERROR: " + errorResponse(p));
} else if (systemOS == systemUnix) {
cmd = app + " -remote openURL(" + url + ") &";
p = Runtime.getRuntime().exec(cmd);
p.waitFor();
if (p.exitValue() != 0) {
cmd = app + " " + url + " &";
p = Runtime.getRuntime().exec(cmd);
p.waitFor();
}
if (p.exitValue() != 0) throw new RuntimeException("EXEC ERROR: " + errorResponse(p));
} else if (systemOS == systemWindows) {
// see forum at http://forum.java.sun.com/thread.jsp?forum=57&thread=233364&message=838441
cmd = "rundll32 url.dll,FileProtocolHandler \"" + url + "\"";
//cmd = "cmd.exe /c start javascript:document.location='" + url + "'";
p = Runtime.getRuntime().exec(cmd);
p.waitFor();
if (p.exitValue() != 0) throw new RuntimeException("EXEC ERROR: " + errorResponse(p));
}
}
} catch (Exception e) {
System.out.println("please start your browser and open the following location: " + url);
}
}
| public static void openBrowser(String url, String app) {
try {
String cmd;
Process p;
if (systemOS != systemUnknown) {
if (systemOS == systemMacOSC) {
if ((isMacArchitecture) && (macMRJFileUtils != null)) {
macOpenURL.invoke(null, new Object[] {url});
}
} else if (systemOS == systemMacOSX) {
p = Runtime.getRuntime().exec(new String[] {"/usr/bin/osascript", "-e", "open location \"" + url + "\""});
p.waitFor();
if (p.exitValue() != 0) throw new RuntimeException("EXEC ERROR: " + errorResponse(p));
} else if (systemOS == systemUnix) {
cmd = app + " -remote openURL(" + url + ") &";
p = Runtime.getRuntime().exec(cmd);
p.waitFor();
if (p.exitValue() != 0) {
cmd = app + " " + url + " &";
p = Runtime.getRuntime().exec(cmd);
p.waitFor();
}
if (p.exitValue() != 0) throw new RuntimeException("EXEC ERROR: " + errorResponse(p));
} else if (systemOS == systemWindows) {
// see forum at http://forum.java.sun.com/thread.jsp?forum=57&thread=233364&message=838441
if (System.getProperty("os.name").contains("2000")) cmd = "rundll32 url.dll,FileProtocolHandler " + url;
else cmd = "rundll32 url.dll,FileProtocolHandler \"" + url + "\"";
//cmd = "cmd.exe /c start javascript:document.location='" + url + "'";
p = Runtime.getRuntime().exec(cmd);
p.waitFor();
if (p.exitValue() != 0) throw new RuntimeException("EXEC ERROR: " + errorResponse(p));
}
}
} catch (Exception e) {
System.out.println("please start your browser and open the following location: " + url);
}
}
|
diff --git a/projects/base/src/main/java/org/muis/base/style/ButtonTexture.java b/projects/base/src/main/java/org/muis/base/style/ButtonTexture.java
index 962b2d17..a9a20b4b 100644
--- a/projects/base/src/main/java/org/muis/base/style/ButtonTexture.java
+++ b/projects/base/src/main/java/org/muis/base/style/ButtonTexture.java
@@ -1,177 +1,177 @@
package org.muis.base.style;
import java.awt.Color;
import org.muis.core.MuisElement;
/** Renders a button-looking texture over an element */
public class ButtonTexture implements org.muis.core.style.Texture
{
@Override
public void render(java.awt.Graphics2D graphics, MuisElement element, java.awt.Rectangle area)
{
int w = element.getWidth();
int h = element.getHeight();
int startX = area == null ? 0 : area.x;
int startY = area == null ? 0 : area.y;
int endX = area == null ? w : startX + area.width;
int endY = area == null ? h : startY + area.height;
- Color orig = graphics.getBackground();
+ Color orig = graphics.getColor();
int radius = element.getStyle().get(ButtonStyles.radius);
float source = element.getStyle().get(org.muis.core.style.TextureStyle.lightSource);
float sin = (float) Math.sin(source * Math.PI / 180);
float cos = (float) Math.cos(source * Math.PI / 180);
// Find the intersection of the ray from the center of the rectangle to the light source with the border
boolean left = source >= 180;
boolean top = source <= 90 || source > 270;
if(left)
{
source -= 180;
if(top)
source -= 90;
}
else if(!top)
source -= 90;
try
{
- /*for(int i = 0; i < radius; i++)
+ for(int i = 0; i < radius; i++)
{
float brighten;
// Vertical edges
int lineStartY = i;
int lineEndY = h - i;
if(lineStartY < startY)
lineStartY = startY;
if(lineEndY > endY)
lineEndY = endY;
if(lineStartY < lineEndY)
{
int x = i;
// Left edge
if(x >= startX || x < endX)
{
brighten = -sin * (radius - i) / radius;
if(brighten > 0)
- graphics.setBackground(new Color(255, 255, 255, (int) (brighten * 255)));
+ graphics.setColor(new Color(255, 255, 255, (int) (brighten * 255)));
else
- graphics.setBackground(new Color(0, 0, 0, (int) (-brighten * 255)));
+ graphics.setColor(new Color(0, 0, 0, (int) (-brighten * 255)));
graphics.drawLine(x, lineStartY, x, lineEndY);
}
x = w - i - 1;
// Right edge
if(x >= startX || x < endX)
{
brighten = sin * (radius - i) / radius;
if(brighten > 0)
- graphics.setBackground(new Color(255, 255, 255, (int) (brighten * 255)));
+ graphics.setColor(new Color(255, 255, 255, (int) (brighten * 255)));
else
- graphics.setBackground(new Color(0, 0, 0, (int) (-brighten * 255)));
+ graphics.setColor(new Color(0, 0, 0, (int) (-brighten * 255)));
graphics.drawLine(x, lineStartY, x, lineEndY);
}
}
int lineStartX = i;
int lineEndX = w - i;
if(lineStartX < startX)
lineStartX = startX;
if(lineEndX > endX)
lineEndX = endX;
if(lineStartX < lineEndX)
{
int y = i;
// Top edge
if(y >= startY || y < endY)
{
brighten = cos * (radius - i) / radius;
if(brighten > 0)
- graphics.setBackground(new Color(255, 255, 255, (int) (brighten * 255)));
+ graphics.setColor(new Color(255, 255, 255, (int) (brighten * 255)));
else
- graphics.setBackground(new Color(0, 0, 0, (int) (-brighten * 255)));
+ graphics.setColor(new Color(0, 0, 0, (int) (-brighten * 255)));
graphics.drawLine(lineStartX, y, lineEndX, y);
}
y = h - i - 1;
// Right edge
if(y >= startY || y < endY)
{
brighten = -cos * (radius - i) / radius;
if(brighten > 0)
- graphics.setBackground(new Color(255, 255, 255, (int) (brighten * 255)));
+ graphics.setColor(new Color(255, 255, 255, (int) (brighten * 255)));
else
- graphics.setBackground(new Color(0, 0, 0, (int) (-brighten * 255)));
+ graphics.setColor(new Color(0, 0, 0, (int) (-brighten * 255)));
graphics.drawLine(lineStartX, y, lineEndX, y);
}
}
- }*/
- for(int y = startY; y < endY; y++)
+ }
+ /*for(int y = startY; y < endY; y++)
for(int x = startX; x < endX; x++)
{
float brighten = getBrighten(x, y, w, h, radius, sin, cos);
if(brighten < 0)
{
graphics.setColor(new Color(0, 0, 0, (int) (-brighten * 255)));
graphics.drawRect(x, y, 1, 1);
}
else if(brighten > 0)
{
graphics.setColor(new Color(255, 255, 255, (int) (brighten * 255)));
graphics.drawRect(x, y, 1, 1);
}
- }
+ }*/
} finally
{
- graphics.setBackground(orig);
+ graphics.setColor(orig);
}
}
/** @param x The x-value of the pixel to brighten or darken
* @param y The y-value of the pixel to brighten or darken
* @param w The width of the element being rendered
* @param h The height of the element being rendered
* @param radius The button radius to render with
* @param sinSource The sin of the light source angle from the vertical
* @param cosSource The cosine of the light source angle from the vertical
* @return A number between -1 (to darken completely) and 1 (to wash out completely) to lighten or darken the background color */
public float getBrighten(int x, int y, int w, int h, int radius, float sinSource, float cosSource)
{
int minDist;
minDist = x;
boolean horizEdge = true;
boolean negOrPos = false;
if(w - x < minDist)
{
minDist = w - x;
negOrPos = true;
}
if(y < minDist)
{
minDist = y;
horizEdge = false;
negOrPos = false;
}
if(h - y < minDist)
{
minDist = h - y;
horizEdge = false;
negOrPos = true;
}
if(minDist > radius)
return 0;
if(!horizEdge)
{ // Top or bottom edge
if(!negOrPos) // Top edge
return cosSource * (radius - minDist) / radius;
else
// Bottom edge
return -cosSource * (radius - minDist) / radius;
}
else
{
if(!negOrPos) // Left edge
return -sinSource * (radius - minDist) / radius;
else
// Right edge
return sinSource * (radius - minDist) / radius;
}
}
}
| false | true | public void render(java.awt.Graphics2D graphics, MuisElement element, java.awt.Rectangle area)
{
int w = element.getWidth();
int h = element.getHeight();
int startX = area == null ? 0 : area.x;
int startY = area == null ? 0 : area.y;
int endX = area == null ? w : startX + area.width;
int endY = area == null ? h : startY + area.height;
Color orig = graphics.getBackground();
int radius = element.getStyle().get(ButtonStyles.radius);
float source = element.getStyle().get(org.muis.core.style.TextureStyle.lightSource);
float sin = (float) Math.sin(source * Math.PI / 180);
float cos = (float) Math.cos(source * Math.PI / 180);
// Find the intersection of the ray from the center of the rectangle to the light source with the border
boolean left = source >= 180;
boolean top = source <= 90 || source > 270;
if(left)
{
source -= 180;
if(top)
source -= 90;
}
else if(!top)
source -= 90;
try
{
/*for(int i = 0; i < radius; i++)
{
float brighten;
// Vertical edges
int lineStartY = i;
int lineEndY = h - i;
if(lineStartY < startY)
lineStartY = startY;
if(lineEndY > endY)
lineEndY = endY;
if(lineStartY < lineEndY)
{
int x = i;
// Left edge
if(x >= startX || x < endX)
{
brighten = -sin * (radius - i) / radius;
if(brighten > 0)
graphics.setBackground(new Color(255, 255, 255, (int) (brighten * 255)));
else
graphics.setBackground(new Color(0, 0, 0, (int) (-brighten * 255)));
graphics.drawLine(x, lineStartY, x, lineEndY);
}
x = w - i - 1;
// Right edge
if(x >= startX || x < endX)
{
brighten = sin * (radius - i) / radius;
if(brighten > 0)
graphics.setBackground(new Color(255, 255, 255, (int) (brighten * 255)));
else
graphics.setBackground(new Color(0, 0, 0, (int) (-brighten * 255)));
graphics.drawLine(x, lineStartY, x, lineEndY);
}
}
int lineStartX = i;
int lineEndX = w - i;
if(lineStartX < startX)
lineStartX = startX;
if(lineEndX > endX)
lineEndX = endX;
if(lineStartX < lineEndX)
{
int y = i;
// Top edge
if(y >= startY || y < endY)
{
brighten = cos * (radius - i) / radius;
if(brighten > 0)
graphics.setBackground(new Color(255, 255, 255, (int) (brighten * 255)));
else
graphics.setBackground(new Color(0, 0, 0, (int) (-brighten * 255)));
graphics.drawLine(lineStartX, y, lineEndX, y);
}
y = h - i - 1;
// Right edge
if(y >= startY || y < endY)
{
brighten = -cos * (radius - i) / radius;
if(brighten > 0)
graphics.setBackground(new Color(255, 255, 255, (int) (brighten * 255)));
else
graphics.setBackground(new Color(0, 0, 0, (int) (-brighten * 255)));
graphics.drawLine(lineStartX, y, lineEndX, y);
}
}
}*/
for(int y = startY; y < endY; y++)
for(int x = startX; x < endX; x++)
{
float brighten = getBrighten(x, y, w, h, radius, sin, cos);
if(brighten < 0)
{
graphics.setColor(new Color(0, 0, 0, (int) (-brighten * 255)));
graphics.drawRect(x, y, 1, 1);
}
else if(brighten > 0)
{
graphics.setColor(new Color(255, 255, 255, (int) (brighten * 255)));
graphics.drawRect(x, y, 1, 1);
}
}
} finally
{
graphics.setBackground(orig);
}
}
| public void render(java.awt.Graphics2D graphics, MuisElement element, java.awt.Rectangle area)
{
int w = element.getWidth();
int h = element.getHeight();
int startX = area == null ? 0 : area.x;
int startY = area == null ? 0 : area.y;
int endX = area == null ? w : startX + area.width;
int endY = area == null ? h : startY + area.height;
Color orig = graphics.getColor();
int radius = element.getStyle().get(ButtonStyles.radius);
float source = element.getStyle().get(org.muis.core.style.TextureStyle.lightSource);
float sin = (float) Math.sin(source * Math.PI / 180);
float cos = (float) Math.cos(source * Math.PI / 180);
// Find the intersection of the ray from the center of the rectangle to the light source with the border
boolean left = source >= 180;
boolean top = source <= 90 || source > 270;
if(left)
{
source -= 180;
if(top)
source -= 90;
}
else if(!top)
source -= 90;
try
{
for(int i = 0; i < radius; i++)
{
float brighten;
// Vertical edges
int lineStartY = i;
int lineEndY = h - i;
if(lineStartY < startY)
lineStartY = startY;
if(lineEndY > endY)
lineEndY = endY;
if(lineStartY < lineEndY)
{
int x = i;
// Left edge
if(x >= startX || x < endX)
{
brighten = -sin * (radius - i) / radius;
if(brighten > 0)
graphics.setColor(new Color(255, 255, 255, (int) (brighten * 255)));
else
graphics.setColor(new Color(0, 0, 0, (int) (-brighten * 255)));
graphics.drawLine(x, lineStartY, x, lineEndY);
}
x = w - i - 1;
// Right edge
if(x >= startX || x < endX)
{
brighten = sin * (radius - i) / radius;
if(brighten > 0)
graphics.setColor(new Color(255, 255, 255, (int) (brighten * 255)));
else
graphics.setColor(new Color(0, 0, 0, (int) (-brighten * 255)));
graphics.drawLine(x, lineStartY, x, lineEndY);
}
}
int lineStartX = i;
int lineEndX = w - i;
if(lineStartX < startX)
lineStartX = startX;
if(lineEndX > endX)
lineEndX = endX;
if(lineStartX < lineEndX)
{
int y = i;
// Top edge
if(y >= startY || y < endY)
{
brighten = cos * (radius - i) / radius;
if(brighten > 0)
graphics.setColor(new Color(255, 255, 255, (int) (brighten * 255)));
else
graphics.setColor(new Color(0, 0, 0, (int) (-brighten * 255)));
graphics.drawLine(lineStartX, y, lineEndX, y);
}
y = h - i - 1;
// Right edge
if(y >= startY || y < endY)
{
brighten = -cos * (radius - i) / radius;
if(brighten > 0)
graphics.setColor(new Color(255, 255, 255, (int) (brighten * 255)));
else
graphics.setColor(new Color(0, 0, 0, (int) (-brighten * 255)));
graphics.drawLine(lineStartX, y, lineEndX, y);
}
}
}
/*for(int y = startY; y < endY; y++)
for(int x = startX; x < endX; x++)
{
float brighten = getBrighten(x, y, w, h, radius, sin, cos);
if(brighten < 0)
{
graphics.setColor(new Color(0, 0, 0, (int) (-brighten * 255)));
graphics.drawRect(x, y, 1, 1);
}
else if(brighten > 0)
{
graphics.setColor(new Color(255, 255, 255, (int) (brighten * 255)));
graphics.drawRect(x, y, 1, 1);
}
}*/
} finally
{
graphics.setColor(orig);
}
}
|
diff --git a/src/jumpignon/Player.java b/src/jumpignon/Player.java
index baa6a5e..f51f355 100644
--- a/src/jumpignon/Player.java
+++ b/src/jumpignon/Player.java
@@ -1,227 +1,227 @@
package jumpignon;
import org.newdawn.slick.*;
public class Player extends RenderItem{
private int health;
private int player_id;
private int kill_score;
private int death_score;
private float y_velocity;
private float x_velocity;
private boolean isInAir;
private Sound jumpSound;
private Sound loseHealthSound;
private Sound dieSound;
// Infos zum Rendern
// Ein Spieler hat immer 3 Bilder, die er brauch.
// Eines für den Zustand in dem er noch "gesund" ist,
// eines in dem er "angeschlagen" ist und noch eines
// wenn er nochmals getroffen wurde.
private Image image;
private Image image2;
private Image image3;
public Player(int h_id, int h_x, int h_y) throws SlickException
{
health = 3;
player_id = h_id;
kill_score = 0;
death_score = 0;
width = 48;
height = 54;
isInAir = false;
y_velocity = 0.0f;
jumpSound = new Sound("resources/sound/player_jump.wav");
loseHealthSound = new Sound("resources/sound/player_lose_health.wav");
dieSound = new Sound("resources/sound/player_die.wav");
this.respawn(h_x, h_y);
}
public void setImage(Image a, Image b, Image c){image = a;image2 = b;image3 = c;}
public int showKills(){return kill_score;}
public int showDeaths(){return death_score;}
public boolean isFalling()
{
if(isInAir == true)
{
if(y_velocity > 0) // Der Spieler springt offensichtlich
{
return false;
}
else // Nur wenn eine Abwärtsbewegung stattfindet fällt der Spieler tatsächlich
{
return true;
}
}
else{ return false; }
}
public void jump()
{
y_velocity = 12.0f;
}
public void die()
{
death_score += 1;
dieSound.play();
respawn(getSpawnPoint(player_id), 420-height);
}
public void setFalling()
{
isInAir = true;
}
@Override
public void renderMe(Graphics g) throws SlickException
{
if(health == 3){g.drawImage(image, pos_x, pos_y);}
else if(health == 2){g.drawImage(image2, pos_x, pos_y);}
else if(health ==1){g.drawImage(image3, pos_x, pos_y);}
if(this.follower != null)
{
this.follower.renderMe(g);
}
}
public void checkBottomCollisionWithPlayer(Player p1)
{
float linkerRandPlayer1 = this.pos_x;
float rechterRandPlayer1 = this.pos_x + this.width;
float linkerRandPlayer2 = p1.pos_x;
float rechterRandPlayer2 = p1.pos_x + p1.width;
if( this.pos_y <= ( p1.get_height() + p1.get_pos_y() ) &&
this.pos_y >= ( p1.get_height() + p1.get_pos_y() - 25) &&
linkerRandPlayer1 <= rechterRandPlayer2 &&
rechterRandPlayer1 >= linkerRandPlayer2 &&
p1.isFalling() == true )
{
if(this.health == 1){p1.gainKill();}
p1.jump();
this.loseHp();
}
}
public void gainKill()
{
kill_score += 1;
}
public void bottomCollisionWithObject(RenderItem i1)
{
isInAir = false; // der Spieler muss zuvor gesprungen sein, also wird dieser Zustand gelöscht
y_velocity = 0.0f; // die Gravitation greift nicht wenn der Spieler auf einem Objekt steht
this.pos_y = i1.pos_y - (this.height); // der Spieler soll auf dem Objekt stehen
}
public void update(GameContainer container, int delta)
{
if(isInAir == true) {x_velocity = 0.35f;}
else {x_velocity = 0.5f;}
switch(player_id)
{
case(1):
// [<-] Links bewegung
if(container.getInput().isKeyDown(Input.KEY_LEFT)){
pos_x -= x_velocity * delta;
}
// [<-] Rechts bewegung
if(container.getInput().isKeyDown(Input.KEY_RIGHT)){
pos_x += x_velocity * delta;
}
// [↕] Oben bewegung
if(container.getInput().isKeyDown(Input.KEY_UP) && isInAir == false){
y_velocity = 1.0f * delta;
isInAir = true;
jumpSound.play();
}
break;
case(2):
// [<-] Links bewegung
if(container.getInput().isKeyDown(Input.KEY_A)){
- pos_x -= 0.5f * delta;
+ pos_x -= x_velocity * delta;
}
// [<-] Rechts bewegung
if(container.getInput().isKeyDown(Input.KEY_D)){
- pos_x += 0.5f * delta;
+ pos_x += x_velocity * delta;
}
// [↕] Oben bewegung
if(container.getInput().isKeyDown(Input.KEY_W) && isInAir == false){
y_velocity = 1.0f * delta;
isInAir = true;
jumpSound.play();
}
break;
}
if(isInAir == true && y_velocity >= -12.0f)
{
y_velocity -= 0.05f * delta;
}
pos_y -= y_velocity;
}
public int getSpawnPoint(int pid)
{
switch(pid)
{
case(1):
return 100;
case(2):
return 770;
default:
return 450;
}
}
public void loseHp()
{
health -= 1;
loseHealthSound.play();
if(health == 0)
{
death_score++;
dieSound.play();
int respawn_x = getSpawnPoint(player_id);
this.respawn(respawn_x, 420-54); // PLAYER 1 KONSTANTE!!
}
}
public void gainHp()
{
if(health != 2)
{
health++;
}
}
public void respawn(int h_x, int h_y)
{
pos_x = h_x;
pos_y = h_y;
health = 3;
}
}
| false | true | public void update(GameContainer container, int delta)
{
if(isInAir == true) {x_velocity = 0.35f;}
else {x_velocity = 0.5f;}
switch(player_id)
{
case(1):
// [<-] Links bewegung
if(container.getInput().isKeyDown(Input.KEY_LEFT)){
pos_x -= x_velocity * delta;
}
// [<-] Rechts bewegung
if(container.getInput().isKeyDown(Input.KEY_RIGHT)){
pos_x += x_velocity * delta;
}
// [↕] Oben bewegung
if(container.getInput().isKeyDown(Input.KEY_UP) && isInAir == false){
y_velocity = 1.0f * delta;
isInAir = true;
jumpSound.play();
}
break;
case(2):
// [<-] Links bewegung
if(container.getInput().isKeyDown(Input.KEY_A)){
pos_x -= 0.5f * delta;
}
// [<-] Rechts bewegung
if(container.getInput().isKeyDown(Input.KEY_D)){
pos_x += 0.5f * delta;
}
// [↕] Oben bewegung
if(container.getInput().isKeyDown(Input.KEY_W) && isInAir == false){
y_velocity = 1.0f * delta;
isInAir = true;
jumpSound.play();
}
break;
}
if(isInAir == true && y_velocity >= -12.0f)
{
y_velocity -= 0.05f * delta;
}
pos_y -= y_velocity;
}
| public void update(GameContainer container, int delta)
{
if(isInAir == true) {x_velocity = 0.35f;}
else {x_velocity = 0.5f;}
switch(player_id)
{
case(1):
// [<-] Links bewegung
if(container.getInput().isKeyDown(Input.KEY_LEFT)){
pos_x -= x_velocity * delta;
}
// [<-] Rechts bewegung
if(container.getInput().isKeyDown(Input.KEY_RIGHT)){
pos_x += x_velocity * delta;
}
// [↕] Oben bewegung
if(container.getInput().isKeyDown(Input.KEY_UP) && isInAir == false){
y_velocity = 1.0f * delta;
isInAir = true;
jumpSound.play();
}
break;
case(2):
// [<-] Links bewegung
if(container.getInput().isKeyDown(Input.KEY_A)){
pos_x -= x_velocity * delta;
}
// [<-] Rechts bewegung
if(container.getInput().isKeyDown(Input.KEY_D)){
pos_x += x_velocity * delta;
}
// [↕] Oben bewegung
if(container.getInput().isKeyDown(Input.KEY_W) && isInAir == false){
y_velocity = 1.0f * delta;
isInAir = true;
jumpSound.play();
}
break;
}
if(isInAir == true && y_velocity >= -12.0f)
{
y_velocity -= 0.05f * delta;
}
pos_y -= y_velocity;
}
|
diff --git a/commons/web/ontology/src/main/java/org/apache/stanbol/ontologymanager/store/rest/resources/Ontologies.java b/commons/web/ontology/src/main/java/org/apache/stanbol/ontologymanager/store/rest/resources/Ontologies.java
index 1939984b3..64b264759 100755
--- a/commons/web/ontology/src/main/java/org/apache/stanbol/ontologymanager/store/rest/resources/Ontologies.java
+++ b/commons/web/ontology/src/main/java/org/apache/stanbol/ontologymanager/store/rest/resources/Ontologies.java
@@ -1,164 +1,164 @@
package org.apache.stanbol.ontologymanager.store.rest.resources;
import static javax.ws.rs.core.MediaType.TEXT_HTML;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.ServletContext;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.FormParam;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import javax.ws.rs.core.UriInfo;
import org.apache.stanbol.commons.web.base.ContextHelper;
import org.apache.stanbol.commons.web.base.resource.BaseStanbolResource;
import org.apache.stanbol.ontologymanager.store.api.LockManager;
import org.apache.stanbol.ontologymanager.store.api.PersistenceStore;
import org.apache.stanbol.ontologymanager.store.api.ResourceManager;
import org.apache.stanbol.ontologymanager.store.model.AdministeredOntologies;
import org.apache.stanbol.ontologymanager.store.model.OntologyMetaInformation;
import org.apache.stanbol.ontologymanager.store.rest.LockManagerImp;
import org.apache.stanbol.ontologymanager.store.rest.ResourceManagerImp;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.sun.jersey.api.view.Viewable;
@Path("/ontology")
public class Ontologies extends BaseStanbolResource {
private static final Logger logger = LoggerFactory.getLogger(Ontologies.class);
private static final String VIEWABLE_PATH = "/org/apache/stanbol/ontologymanager/store/rest/resources/ontologies";
private PersistenceStore persistenceStore;
public Ontologies(@Context ServletContext context) {
this.persistenceStore = ContextHelper.getServiceFromContext(PersistenceStore.class, context);
}
@GET
@Produces({MediaType.APPLICATION_XML})
public Object getClichedMessage() {
LockManager lockManager = LockManagerImp.getInstance();
lockManager.obtainReadLockFor(LockManagerImp.GLOBAL_SPACE);
Response response = null;
try {
AdministeredOntologies administeredOntologies = persistenceStore.retrieveAdministeredOntologies();
response = Response.ok(administeredOntologies, MediaType.APPLICATION_XML_TYPE).build();
} catch (Exception e) {
throw new WebApplicationException(Response.Status.INTERNAL_SERVER_ERROR);
} finally {
lockManager.releaseReadLockFor(LockManagerImp.GLOBAL_SPACE);
}
return response;
}
@POST
@Consumes("application/x-www-form-urlencoded")
@Produces(MediaType.APPLICATION_XML)
public Response saveOntology(@FormParam("ontologyURI") String ontologyURI,
@FormParam("ontologyContent") String ontologyContent,
@FormParam("ontologyURL") String ontologyURL) {
Response response = null;
LockManager lockManager = LockManagerImp.getInstance();
lockManager.obtainReadLockFor(LockManagerImp.GLOBAL_SPACE);
lockManager.obtainWriteLockFor(ontologyURI);
try {
OntologyMetaInformation ontologyMetaInformation = null;
- if (ontologyContent != null && ontologyContent.isEmpty()) {
+ if (ontologyContent != null && !ontologyContent.isEmpty()) {
ontologyMetaInformation = persistenceStore
.saveOntology(ontologyContent, ontologyURI, "UTF-8");
- } else if (ontologyURL != null && ontologyURL.isEmpty()) {
+ } else if (ontologyURL != null && !ontologyURL.isEmpty()) {
try{
ontologyMetaInformation = persistenceStore.saveOntology(new URL(ontologyURL), ontologyURI,
"UTF-8");
}catch (MalformedURLException e) {
throw new WebApplicationException(e, Status.BAD_REQUEST);
}
}else{
throw new WebApplicationException(new IllegalArgumentException("Ontology Content or URL can not be both null"),Status.BAD_REQUEST);
}
response = Response.ok(ontologyMetaInformation, MediaType.APPLICATION_XML_TYPE).build();
} catch (Exception e) {
logger.error("Error ", e);
throw new WebApplicationException(Response.Status.INTERNAL_SERVER_ERROR);
} finally {
lockManager.releaseReadLockFor(LockManagerImp.GLOBAL_SPACE);
lockManager.releaseWriteLockFor(ontologyURI);
}
return response;
}
// The Java method will process HTTP DELETE requests
@DELETE
public void delete() {
LockManager lockManager = LockManagerImp.getInstance();
lockManager.obtainWriteLockFor(LockManagerImp.GLOBAL_SPACE);
try {
persistenceStore.clearPersistenceStore();
ResourceManager resourceManager = ResourceManagerImp.getInstance();
resourceManager.clearResourceManager();
} catch (Exception e) {
logger.error("Error ", e);
throw new WebApplicationException(Response.Status.INTERNAL_SERVER_ERROR);
} finally {
lockManager.releaseWriteLockFor(LockManagerImp.GLOBAL_SPACE);
}
}
// Methods for HTML View
@GET
@Produces(TEXT_HTML + ";qs=2")
public Viewable getViewable(@Context UriInfo uriInfo) {
return new Viewable(VIEWABLE_PATH, this);
}
@POST
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
@Produces(MediaType.TEXT_HTML + ";qs=2")
public Response createAndRedirect(@FormParam("ontologyURI") String ontologyURI,
@FormParam("ontologyContent") String ontologyContent,
@FormParam("ontologyURL") String ontologyURL ) {
Response response = this.saveOntology(ontologyURI, ontologyContent, ontologyURL);
OntologyMetaInformation ont = ((OntologyMetaInformation) response.getEntity());
try {
return Response.seeOther(URI.create(ont.getHref())).type(MediaType.TEXT_HTML)
.header("Accept", MediaType.TEXT_HTML).build();
} catch (Exception e) {
logger.error("Error ", e);
throw new WebApplicationException(Status.INTERNAL_SERVER_ERROR);
}
}
public List<OntologyMetaInformation> getOntologies() {
LockManager lockManager = LockManagerImp.getInstance();
lockManager.obtainReadLockFor(LockManagerImp.GLOBAL_SPACE);
List<OntologyMetaInformation> onts = new ArrayList<OntologyMetaInformation>();
try {
onts = persistenceStore.retrieveAdministeredOntologies().getOntologyMetaInformation();
} catch (Exception e) {
logger.error("Error ", e);
throw new RuntimeException(e);
} finally {
lockManager.releaseReadLockFor(LockManagerImp.GLOBAL_SPACE);
}
return onts;
}
}
| false | true | public Response saveOntology(@FormParam("ontologyURI") String ontologyURI,
@FormParam("ontologyContent") String ontologyContent,
@FormParam("ontologyURL") String ontologyURL) {
Response response = null;
LockManager lockManager = LockManagerImp.getInstance();
lockManager.obtainReadLockFor(LockManagerImp.GLOBAL_SPACE);
lockManager.obtainWriteLockFor(ontologyURI);
try {
OntologyMetaInformation ontologyMetaInformation = null;
if (ontologyContent != null && ontologyContent.isEmpty()) {
ontologyMetaInformation = persistenceStore
.saveOntology(ontologyContent, ontologyURI, "UTF-8");
} else if (ontologyURL != null && ontologyURL.isEmpty()) {
try{
ontologyMetaInformation = persistenceStore.saveOntology(new URL(ontologyURL), ontologyURI,
"UTF-8");
}catch (MalformedURLException e) {
throw new WebApplicationException(e, Status.BAD_REQUEST);
}
}else{
throw new WebApplicationException(new IllegalArgumentException("Ontology Content or URL can not be both null"),Status.BAD_REQUEST);
}
response = Response.ok(ontologyMetaInformation, MediaType.APPLICATION_XML_TYPE).build();
} catch (Exception e) {
logger.error("Error ", e);
throw new WebApplicationException(Response.Status.INTERNAL_SERVER_ERROR);
} finally {
lockManager.releaseReadLockFor(LockManagerImp.GLOBAL_SPACE);
lockManager.releaseWriteLockFor(ontologyURI);
}
return response;
}
| public Response saveOntology(@FormParam("ontologyURI") String ontologyURI,
@FormParam("ontologyContent") String ontologyContent,
@FormParam("ontologyURL") String ontologyURL) {
Response response = null;
LockManager lockManager = LockManagerImp.getInstance();
lockManager.obtainReadLockFor(LockManagerImp.GLOBAL_SPACE);
lockManager.obtainWriteLockFor(ontologyURI);
try {
OntologyMetaInformation ontologyMetaInformation = null;
if (ontologyContent != null && !ontologyContent.isEmpty()) {
ontologyMetaInformation = persistenceStore
.saveOntology(ontologyContent, ontologyURI, "UTF-8");
} else if (ontologyURL != null && !ontologyURL.isEmpty()) {
try{
ontologyMetaInformation = persistenceStore.saveOntology(new URL(ontologyURL), ontologyURI,
"UTF-8");
}catch (MalformedURLException e) {
throw new WebApplicationException(e, Status.BAD_REQUEST);
}
}else{
throw new WebApplicationException(new IllegalArgumentException("Ontology Content or URL can not be both null"),Status.BAD_REQUEST);
}
response = Response.ok(ontologyMetaInformation, MediaType.APPLICATION_XML_TYPE).build();
} catch (Exception e) {
logger.error("Error ", e);
throw new WebApplicationException(Response.Status.INTERNAL_SERVER_ERROR);
} finally {
lockManager.releaseReadLockFor(LockManagerImp.GLOBAL_SPACE);
lockManager.releaseWriteLockFor(ontologyURI);
}
return response;
}
|
diff --git a/core/java/android/widget/AbsListView.java b/core/java/android/widget/AbsListView.java
index b408f27a..767c7e79 100644
--- a/core/java/android/widget/AbsListView.java
+++ b/core/java/android/widget/AbsListView.java
@@ -1,3518 +1,3519 @@
/*
* Copyright (C) 2006 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package android.widget;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.TransitionDrawable;
import android.os.Debug;
import android.os.Handler;
import android.os.Parcel;
import android.os.Parcelable;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.HapticFeedbackConstants;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.VelocityTracker;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.ViewDebug;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.view.inputmethod.BaseInputConnection;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputConnection;
import android.view.inputmethod.InputConnectionWrapper;
import android.view.inputmethod.InputMethodManager;
import android.view.ContextMenu.ContextMenuInfo;
import com.android.internal.R;
import java.util.ArrayList;
import java.util.List;
/**
* Common code shared between ListView and GridView
*
* @attr ref android.R.styleable#AbsListView_listSelector
* @attr ref android.R.styleable#AbsListView_drawSelectorOnTop
* @attr ref android.R.styleable#AbsListView_stackFromBottom
* @attr ref android.R.styleable#AbsListView_scrollingCache
* @attr ref android.R.styleable#AbsListView_textFilterEnabled
* @attr ref android.R.styleable#AbsListView_transcriptMode
* @attr ref android.R.styleable#AbsListView_cacheColorHint
* @attr ref android.R.styleable#AbsListView_fastScrollEnabled
* @attr ref android.R.styleable#AbsListView_smoothScrollbar
*/
public abstract class AbsListView extends AdapterView<ListAdapter> implements TextWatcher,
ViewTreeObserver.OnGlobalLayoutListener, Filter.FilterListener,
ViewTreeObserver.OnTouchModeChangeListener {
/**
* Disables the transcript mode.
*
* @see #setTranscriptMode(int)
*/
public static final int TRANSCRIPT_MODE_DISABLED = 0;
/**
* The list will automatically scroll to the bottom when a data set change
* notification is received and only if the last item is already visible
* on screen.
*
* @see #setTranscriptMode(int)
*/
public static final int TRANSCRIPT_MODE_NORMAL = 1;
/**
* The list will automatically scroll to the bottom, no matter what items
* are currently visible.
*
* @see #setTranscriptMode(int)
*/
public static final int TRANSCRIPT_MODE_ALWAYS_SCROLL = 2;
/**
* Indicates that we are not in the middle of a touch gesture
*/
static final int TOUCH_MODE_REST = -1;
/**
* Indicates we just received the touch event and we are waiting to see if the it is a tap or a
* scroll gesture.
*/
static final int TOUCH_MODE_DOWN = 0;
/**
* Indicates the touch has been recognized as a tap and we are now waiting to see if the touch
* is a longpress
*/
static final int TOUCH_MODE_TAP = 1;
/**
* Indicates we have waited for everything we can wait for, but the user's finger is still down
*/
static final int TOUCH_MODE_DONE_WAITING = 2;
/**
* Indicates the touch gesture is a scroll
*/
static final int TOUCH_MODE_SCROLL = 3;
/**
* Indicates the view is in the process of being flung
*/
static final int TOUCH_MODE_FLING = 4;
/**
* Indicates that the user is currently dragging the fast scroll thumb
*/
static final int TOUCH_MODE_FAST_SCROLL = 5;
/**
* Regular layout - usually an unsolicited layout from the view system
*/
static final int LAYOUT_NORMAL = 0;
/**
* Show the first item
*/
static final int LAYOUT_FORCE_TOP = 1;
/**
* Force the selected item to be on somewhere on the screen
*/
static final int LAYOUT_SET_SELECTION = 2;
/**
* Show the last item
*/
static final int LAYOUT_FORCE_BOTTOM = 3;
/**
* Make a mSelectedItem appear in a specific location and build the rest of
* the views from there. The top is specified by mSpecificTop.
*/
static final int LAYOUT_SPECIFIC = 4;
/**
* Layout to sync as a result of a data change. Restore mSyncPosition to have its top
* at mSpecificTop
*/
static final int LAYOUT_SYNC = 5;
/**
* Layout as a result of using the navigation keys
*/
static final int LAYOUT_MOVE_SELECTION = 6;
/**
* Controls how the next layout will happen
*/
int mLayoutMode = LAYOUT_NORMAL;
/**
* Should be used by subclasses to listen to changes in the dataset
*/
AdapterDataSetObserver mDataSetObserver;
/**
* The adapter containing the data to be displayed by this view
*/
ListAdapter mAdapter;
/**
* Indicates whether the list selector should be drawn on top of the children or behind
*/
boolean mDrawSelectorOnTop = false;
/**
* The drawable used to draw the selector
*/
Drawable mSelector;
/**
* Defines the selector's location and dimension at drawing time
*/
Rect mSelectorRect = new Rect();
/**
* The data set used to store unused views that should be reused during the next layout
* to avoid creating new ones
*/
final RecycleBin mRecycler = new RecycleBin();
/**
* The selection's left padding
*/
int mSelectionLeftPadding = 0;
/**
* The selection's top padding
*/
int mSelectionTopPadding = 0;
/**
* The selection's right padding
*/
int mSelectionRightPadding = 0;
/**
* The selection's bottom padding
*/
int mSelectionBottomPadding = 0;
/**
* This view's padding
*/
Rect mListPadding = new Rect();
/**
* Subclasses must retain their measure spec from onMeasure() into this member
*/
int mWidthMeasureSpec = 0;
/**
* The top scroll indicator
*/
View mScrollUp;
/**
* The down scroll indicator
*/
View mScrollDown;
/**
* When the view is scrolling, this flag is set to true to indicate subclasses that
* the drawing cache was enabled on the children
*/
boolean mCachingStarted;
/**
* The position of the view that received the down motion event
*/
int mMotionPosition;
/**
* The offset to the top of the mMotionPosition view when the down motion event was received
*/
int mMotionViewOriginalTop;
/**
* The desired offset to the top of the mMotionPosition view after a scroll
*/
int mMotionViewNewTop;
/**
* The X value associated with the the down motion event
*/
int mMotionX;
/**
* The Y value associated with the the down motion event
*/
int mMotionY;
/**
* One of TOUCH_MODE_REST, TOUCH_MODE_DOWN, TOUCH_MODE_TAP, TOUCH_MODE_SCROLL, or
* TOUCH_MODE_DONE_WAITING
*/
int mTouchMode = TOUCH_MODE_REST;
/**
* Y value from on the previous motion event (if any)
*/
int mLastY;
/**
* How far the finger moved before we started scrolling
*/
int mMotionCorrection;
/**
* Determines speed during touch scrolling
*/
private VelocityTracker mVelocityTracker;
/**
* Handles one frame of a fling
*/
private FlingRunnable mFlingRunnable;
/**
* The offset in pixels form the top of the AdapterView to the top
* of the currently selected view. Used to save and restore state.
*/
int mSelectedTop = 0;
/**
* Indicates whether the list is stacked from the bottom edge or
* the top edge.
*/
boolean mStackFromBottom;
/**
* When set to true, the list automatically discards the children's
* bitmap cache after scrolling.
*/
boolean mScrollingCacheEnabled;
/**
* Whether or not to enable the fast scroll feature on this list
*/
boolean mFastScrollEnabled;
/**
* Optional callback to notify client when scroll position has changed
*/
private OnScrollListener mOnScrollListener;
/**
* Keeps track of our accessory window
*/
PopupWindow mPopup;
/**
* Used with type filter window
*/
EditText mTextFilter;
/**
* Indicates whether to use pixels-based or position-based scrollbar
* properties.
*/
private boolean mSmoothScrollbarEnabled = true;
/**
* Indicates that this view supports filtering
*/
private boolean mTextFilterEnabled;
/**
* Indicates that this view is currently displaying a filtered view of the data
*/
private boolean mFiltered;
/**
* Rectangle used for hit testing children
*/
private Rect mTouchFrame;
/**
* The position to resurrect the selected position to.
*/
int mResurrectToPosition = INVALID_POSITION;
private ContextMenuInfo mContextMenuInfo = null;
/**
* Used to request a layout when we changed touch mode
*/
private static final int TOUCH_MODE_UNKNOWN = -1;
private static final int TOUCH_MODE_ON = 0;
private static final int TOUCH_MODE_OFF = 1;
private int mLastTouchMode = TOUCH_MODE_UNKNOWN;
private static final boolean PROFILE_SCROLLING = false;
private boolean mScrollProfilingStarted = false;
private static final boolean PROFILE_FLINGING = false;
private boolean mFlingProfilingStarted = false;
/**
* The last CheckForLongPress runnable we posted, if any
*/
private CheckForLongPress mPendingCheckForLongPress;
/**
* The last CheckForTap runnable we posted, if any
*/
private Runnable mPendingCheckForTap;
/**
* The last CheckForKeyLongPress runnable we posted, if any
*/
private CheckForKeyLongPress mPendingCheckForKeyLongPress;
/**
* Acts upon click
*/
private AbsListView.PerformClick mPerformClick;
/**
* This view is in transcript mode -- it shows the bottom of the list when the data
* changes
*/
private int mTranscriptMode;
/**
* Indicates that this list is always drawn on top of a solid, single-color, opaque
* background
*/
private int mCacheColorHint;
/**
* The select child's view (from the adapter's getView) is enabled.
*/
private boolean mIsChildViewEnabled;
/**
* The last scroll state reported to clients through {@link OnScrollListener}.
*/
private int mLastScrollState = OnScrollListener.SCROLL_STATE_IDLE;
/**
* Helper object that renders and controls the fast scroll thumb.
*/
private FastScroller mFastScroller;
private int mTouchSlop;
private float mDensityScale;
private InputConnection mDefInputConnection;
private InputConnectionWrapper mPublicInputConnection;
/**
* Interface definition for a callback to be invoked when the list or grid
* has been scrolled.
*/
public interface OnScrollListener {
/**
* The view is not scrolling. Note navigating the list using the trackball counts as
* being in the idle state since these transitions are not animated.
*/
public static int SCROLL_STATE_IDLE = 0;
/**
* The user is scrolling using touch, and their finger is still on the screen
*/
public static int SCROLL_STATE_TOUCH_SCROLL = 1;
/**
* The user had previously been scrolling using touch and had performed a fling. The
* animation is now coasting to a stop
*/
public static int SCROLL_STATE_FLING = 2;
/**
* Callback method to be invoked while the list view or grid view is being scrolled. If the
* view is being scrolled, this method will be called before the next frame of the scroll is
* rendered. In particular, it will be called before any calls to
* {@link Adapter#getView(int, View, ViewGroup)}.
*
* @param view The view whose scroll state is being reported
*
* @param scrollState The current scroll state. One of {@link #SCROLL_STATE_IDLE},
* {@link #SCROLL_STATE_TOUCH_SCROLL} or {@link #SCROLL_STATE_IDLE}.
*/
public void onScrollStateChanged(AbsListView view, int scrollState);
/**
* Callback method to be invoked when the list or grid has been scrolled. This will be
* called after the scroll has completed
* @param view The view whose scroll state is being reported
* @param firstVisibleItem the index of the first visible cell (ignore if
* visibleItemCount == 0)
* @param visibleItemCount the number of visible cells
* @param totalItemCount the number of items in the list adaptor
*/
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount,
int totalItemCount);
}
public AbsListView(Context context) {
super(context);
initAbsListView();
setVerticalScrollBarEnabled(true);
TypedArray a = context.obtainStyledAttributes(R.styleable.View);
initializeScrollbars(a);
a.recycle();
}
public AbsListView(Context context, AttributeSet attrs) {
this(context, attrs, com.android.internal.R.attr.absListViewStyle);
}
public AbsListView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
initAbsListView();
TypedArray a = context.obtainStyledAttributes(attrs,
com.android.internal.R.styleable.AbsListView, defStyle, 0);
Drawable d = a.getDrawable(com.android.internal.R.styleable.AbsListView_listSelector);
if (d != null) {
setSelector(d);
}
mDrawSelectorOnTop = a.getBoolean(
com.android.internal.R.styleable.AbsListView_drawSelectorOnTop, false);
boolean stackFromBottom = a.getBoolean(R.styleable.AbsListView_stackFromBottom, false);
setStackFromBottom(stackFromBottom);
boolean scrollingCacheEnabled = a.getBoolean(R.styleable.AbsListView_scrollingCache, true);
setScrollingCacheEnabled(scrollingCacheEnabled);
boolean useTextFilter = a.getBoolean(R.styleable.AbsListView_textFilterEnabled, false);
setTextFilterEnabled(useTextFilter);
int transcriptMode = a.getInt(R.styleable.AbsListView_transcriptMode,
TRANSCRIPT_MODE_DISABLED);
setTranscriptMode(transcriptMode);
int color = a.getColor(R.styleable.AbsListView_cacheColorHint, 0);
setCacheColorHint(color);
boolean enableFastScroll = a.getBoolean(R.styleable.AbsListView_fastScrollEnabled, false);
setFastScrollEnabled(enableFastScroll);
boolean smoothScrollbar = a.getBoolean(R.styleable.AbsListView_smoothScrollbar, true);
setSmoothScrollbarEnabled(smoothScrollbar);
a.recycle();
}
/**
* Enables fast scrolling by letting the user quickly scroll through lists by
* dragging the fast scroll thumb. The adapter attached to the list may want
* to implement {@link SectionIndexer} if it wishes to display alphabet preview and
* jump between sections of the list.
* @see SectionIndexer
* @see #isFastScrollEnabled()
* @param enabled whether or not to enable fast scrolling
*/
public void setFastScrollEnabled(boolean enabled) {
mFastScrollEnabled = enabled;
if (enabled) {
if (mFastScroller == null) {
mFastScroller = new FastScroller(getContext(), this);
}
} else {
if (mFastScroller != null) {
mFastScroller.stop();
mFastScroller = null;
}
}
}
/**
* Returns the current state of the fast scroll feature.
* @see #setFastScrollEnabled(boolean)
* @return true if fast scroll is enabled, false otherwise
*/
@ViewDebug.ExportedProperty
public boolean isFastScrollEnabled() {
return mFastScrollEnabled;
}
/**
* If fast scroll is visible, then don't draw the vertical scrollbar.
* @hide
*/
@Override
protected boolean isVerticalScrollBarHidden() {
return mFastScroller != null && mFastScroller.isVisible();
}
/**
* When smooth scrollbar is enabled, the position and size of the scrollbar thumb
* is computed based on the number of visible pixels in the visible items. This
* however assumes that all list items have the same height. If you use a list in
* which items have different heights, the scrollbar will change appearance as the
* user scrolls through the list. To avoid this issue, you need to disable this
* property.
*
* When smooth scrollbar is disabled, the position and size of the scrollbar thumb
* is based solely on the number of items in the adapter and the position of the
* visible items inside the adapter. This provides a stable scrollbar as the user
* navigates through a list of items with varying heights.
*
* @param enabled Whether or not to enable smooth scrollbar.
*
* @see #setSmoothScrollbarEnabled(boolean)
* @attr ref android.R.styleable#AbsListView_smoothScrollbar
*/
public void setSmoothScrollbarEnabled(boolean enabled) {
mSmoothScrollbarEnabled = enabled;
}
/**
* Returns the current state of the fast scroll feature.
*
* @return True if smooth scrollbar is enabled is enabled, false otherwise.
*
* @see #setSmoothScrollbarEnabled(boolean)
*/
@ViewDebug.ExportedProperty
public boolean isSmoothScrollbarEnabled() {
return mSmoothScrollbarEnabled;
}
/**
* Set the listener that will receive notifications every time the list scrolls.
*
* @param l the scroll listener
*/
public void setOnScrollListener(OnScrollListener l) {
mOnScrollListener = l;
invokeOnItemScrollListener();
}
/**
* Notify our scroll listener (if there is one) of a change in scroll state
*/
void invokeOnItemScrollListener() {
if (mFastScroller != null) {
mFastScroller.onScroll(this, mFirstPosition, getChildCount(), mItemCount);
}
if (mOnScrollListener != null) {
mOnScrollListener.onScroll(this, mFirstPosition, getChildCount(), mItemCount);
}
}
/**
* Indicates whether the children's drawing cache is used during a scroll.
* By default, the drawing cache is enabled but this will consume more memory.
*
* @return true if the scrolling cache is enabled, false otherwise
*
* @see #setScrollingCacheEnabled(boolean)
* @see View#setDrawingCacheEnabled(boolean)
*/
@ViewDebug.ExportedProperty
public boolean isScrollingCacheEnabled() {
return mScrollingCacheEnabled;
}
/**
* Enables or disables the children's drawing cache during a scroll.
* By default, the drawing cache is enabled but this will use more memory.
*
* When the scrolling cache is enabled, the caches are kept after the
* first scrolling. You can manually clear the cache by calling
* {@link android.view.ViewGroup#setChildrenDrawingCacheEnabled(boolean)}.
*
* @param enabled true to enable the scroll cache, false otherwise
*
* @see #isScrollingCacheEnabled()
* @see View#setDrawingCacheEnabled(boolean)
*/
public void setScrollingCacheEnabled(boolean enabled) {
if (mScrollingCacheEnabled && !enabled) {
clearScrollingCache();
}
mScrollingCacheEnabled = enabled;
}
/**
* Enables or disables the type filter window. If enabled, typing when
* this view has focus will filter the children to match the users input.
* Note that the {@link Adapter} used by this view must implement the
* {@link Filterable} interface.
*
* @param textFilterEnabled true to enable type filtering, false otherwise
*
* @see Filterable
*/
public void setTextFilterEnabled(boolean textFilterEnabled) {
mTextFilterEnabled = textFilterEnabled;
}
/**
* Indicates whether type filtering is enabled for this view
*
* @return true if type filtering is enabled, false otherwise
*
* @see #setTextFilterEnabled(boolean)
* @see Filterable
*/
@ViewDebug.ExportedProperty
public boolean isTextFilterEnabled() {
return mTextFilterEnabled;
}
@Override
public void getFocusedRect(Rect r) {
View view = getSelectedView();
if (view != null) {
// the focused rectangle of the selected view offset into the
// coordinate space of this view.
view.getFocusedRect(r);
offsetDescendantRectToMyCoords(view, r);
} else {
// otherwise, just the norm
super.getFocusedRect(r);
}
}
private void initAbsListView() {
// Setting focusable in touch mode will set the focusable property to true
setFocusableInTouchMode(true);
setWillNotDraw(false);
setAlwaysDrawnWithCacheEnabled(false);
setScrollingCacheEnabled(true);
mTouchSlop = ViewConfiguration.get(mContext).getScaledTouchSlop();
mDensityScale = getContext().getResources().getDisplayMetrics().density;
}
private void useDefaultSelector() {
setSelector(getResources().getDrawable(
com.android.internal.R.drawable.list_selector_background));
}
/**
* Indicates whether the content of this view is pinned to, or stacked from,
* the bottom edge.
*
* @return true if the content is stacked from the bottom edge, false otherwise
*/
@ViewDebug.ExportedProperty
public boolean isStackFromBottom() {
return mStackFromBottom;
}
/**
* When stack from bottom is set to true, the list fills its content starting from
* the bottom of the view.
*
* @param stackFromBottom true to pin the view's content to the bottom edge,
* false to pin the view's content to the top edge
*/
public void setStackFromBottom(boolean stackFromBottom) {
if (mStackFromBottom != stackFromBottom) {
mStackFromBottom = stackFromBottom;
requestLayoutIfNecessary();
}
}
void requestLayoutIfNecessary() {
if (getChildCount() > 0) {
resetList();
requestLayout();
invalidate();
}
}
static class SavedState extends BaseSavedState {
long selectedId;
long firstId;
int viewTop;
int position;
int height;
String filter;
/**
* Constructor called from {@link AbsListView#onSaveInstanceState()}
*/
SavedState(Parcelable superState) {
super(superState);
}
/**
* Constructor called from {@link #CREATOR}
*/
private SavedState(Parcel in) {
super(in);
selectedId = in.readLong();
firstId = in.readLong();
viewTop = in.readInt();
position = in.readInt();
height = in.readInt();
filter = in.readString();
}
@Override
public void writeToParcel(Parcel out, int flags) {
super.writeToParcel(out, flags);
out.writeLong(selectedId);
out.writeLong(firstId);
out.writeInt(viewTop);
out.writeInt(position);
out.writeInt(height);
out.writeString(filter);
}
@Override
public String toString() {
return "AbsListView.SavedState{"
+ Integer.toHexString(System.identityHashCode(this))
+ " selectedId=" + selectedId
+ " firstId=" + firstId
+ " viewTop=" + viewTop
+ " position=" + position
+ " height=" + height
+ " filter=" + filter + "}";
}
public static final Parcelable.Creator<SavedState> CREATOR
= new Parcelable.Creator<SavedState>() {
public SavedState createFromParcel(Parcel in) {
return new SavedState(in);
}
public SavedState[] newArray(int size) {
return new SavedState[size];
}
};
}
@Override
public Parcelable onSaveInstanceState() {
/*
* This doesn't really make sense as the place to dismiss the
* popup, but there don't seem to be any other useful hooks
* that happen early enough to keep from getting complaints
* about having leaked the window.
*/
dismissPopup();
Parcelable superState = super.onSaveInstanceState();
SavedState ss = new SavedState(superState);
boolean haveChildren = getChildCount() > 0;
long selectedId = getSelectedItemId();
ss.selectedId = selectedId;
ss.height = getHeight();
if (selectedId >= 0) {
// Remember the selection
ss.viewTop = mSelectedTop;
ss.position = getSelectedItemPosition();
ss.firstId = INVALID_POSITION;
} else {
if (haveChildren) {
// Remember the position of the first child
View v = getChildAt(0);
ss.viewTop = v.getTop();
ss.position = mFirstPosition;
ss.firstId = mAdapter.getItemId(mFirstPosition);
} else {
ss.viewTop = 0;
ss.firstId = INVALID_POSITION;
ss.position = 0;
}
}
ss.filter = null;
if (mFiltered) {
final EditText textFilter = mTextFilter;
if (textFilter != null) {
Editable filterText = textFilter.getText();
if (filterText != null) {
ss.filter = filterText.toString();
}
}
}
return ss;
}
@Override
public void onRestoreInstanceState(Parcelable state) {
SavedState ss = (SavedState) state;
super.onRestoreInstanceState(ss.getSuperState());
mDataChanged = true;
mSyncHeight = ss.height;
if (ss.selectedId >= 0) {
mNeedSync = true;
mSyncRowId = ss.selectedId;
mSyncPosition = ss.position;
mSpecificTop = ss.viewTop;
mSyncMode = SYNC_SELECTED_POSITION;
} else if (ss.firstId >= 0) {
setSelectedPositionInt(INVALID_POSITION);
// Do this before setting mNeedSync since setNextSelectedPosition looks at mNeedSync
setNextSelectedPositionInt(INVALID_POSITION);
mNeedSync = true;
mSyncRowId = ss.firstId;
mSyncPosition = ss.position;
mSpecificTop = ss.viewTop;
mSyncMode = SYNC_FIRST_POSITION;
}
setFilterText(ss.filter);
requestLayout();
}
private boolean acceptFilter() {
if (!mTextFilterEnabled || !(getAdapter() instanceof Filterable) ||
((Filterable) getAdapter()).getFilter() == null) {
return false;
}
return true;
}
/**
* Sets the initial value for the text filter.
* @param filterText The text to use for the filter.
*
* @see #setTextFilterEnabled
*/
public void setFilterText(String filterText) {
// TODO: Should we check for acceptFilter()?
if (mTextFilterEnabled && !TextUtils.isEmpty(filterText)) {
createTextFilter(false);
// This is going to call our listener onTextChanged, but we might not
// be ready to bring up a window yet
mTextFilter.setText(filterText);
mTextFilter.setSelection(filterText.length());
if (mAdapter instanceof Filterable) {
// if mPopup is non-null, then onTextChanged will do the filtering
if (mPopup == null) {
Filter f = ((Filterable) mAdapter).getFilter();
f.filter(filterText);
}
// Set filtered to true so we will display the filter window when our main
// window is ready
mFiltered = true;
mDataSetObserver.clearSavedState();
}
}
}
/**
* Returns the list's text filter, if available.
* @return the list's text filter or null if filtering isn't enabled
*/
public CharSequence getTextFilter() {
if (mTextFilterEnabled && mTextFilter != null) {
return mTextFilter.getText();
}
return null;
}
@Override
protected void onFocusChanged(boolean gainFocus, int direction, Rect previouslyFocusedRect) {
super.onFocusChanged(gainFocus, direction, previouslyFocusedRect);
if (gainFocus && mSelectedPosition < 0 && !isInTouchMode()) {
resurrectSelection();
}
}
@Override
public void requestLayout() {
if (!mBlockLayoutRequests && !mInLayout) {
super.requestLayout();
}
}
/**
* The list is empty. Clear everything out.
*/
void resetList() {
removeAllViewsInLayout();
mFirstPosition = 0;
mDataChanged = false;
mNeedSync = false;
mOldSelectedPosition = INVALID_POSITION;
mOldSelectedRowId = INVALID_ROW_ID;
setSelectedPositionInt(INVALID_POSITION);
setNextSelectedPositionInt(INVALID_POSITION);
mSelectedTop = 0;
mSelectorRect.setEmpty();
invalidate();
}
@Override
protected int computeVerticalScrollExtent() {
final int count = getChildCount();
if (count > 0) {
if (mSmoothScrollbarEnabled) {
int extent = count * 100;
View view = getChildAt(0);
final int top = view.getTop();
int height = view.getHeight();
if (height > 0) {
extent += (top * 100) / height;
}
view = getChildAt(count - 1);
final int bottom = view.getBottom();
height = view.getHeight();
if (height > 0) {
extent -= ((bottom - getHeight()) * 100) / height;
}
return extent;
} else {
return 1;
}
}
return 0;
}
@Override
protected int computeVerticalScrollOffset() {
final int firstPosition = mFirstPosition;
final int childCount = getChildCount();
if (firstPosition >= 0 && childCount > 0) {
if (mSmoothScrollbarEnabled) {
final View view = getChildAt(0);
final int top = view.getTop();
int height = view.getHeight();
if (height > 0) {
return Math.max(firstPosition * 100 - (top * 100) / height, 0);
}
} else {
int index;
final int count = mItemCount;
if (firstPosition == 0) {
index = 0;
} else if (firstPosition + childCount == count) {
index = count;
} else {
index = firstPosition + childCount / 2;
}
return (int) (firstPosition + childCount * (index / (float) count));
}
}
return 0;
}
@Override
protected int computeVerticalScrollRange() {
return mSmoothScrollbarEnabled ? Math.max(mItemCount * 100, 0) : mItemCount;
}
@Override
protected float getTopFadingEdgeStrength() {
final int count = getChildCount();
final float fadeEdge = super.getTopFadingEdgeStrength();
if (count == 0) {
return fadeEdge;
} else {
if (mFirstPosition > 0) {
return 1.0f;
}
final int top = getChildAt(0).getTop();
final float fadeLength = (float) getVerticalFadingEdgeLength();
return top < mPaddingTop ? (float) -(top - mPaddingTop) / fadeLength : fadeEdge;
}
}
@Override
protected float getBottomFadingEdgeStrength() {
final int count = getChildCount();
final float fadeEdge = super.getBottomFadingEdgeStrength();
if (count == 0) {
return fadeEdge;
} else {
if (mFirstPosition + count - 1 < mItemCount - 1) {
return 1.0f;
}
final int bottom = getChildAt(count - 1).getBottom();
final int height = getHeight();
final float fadeLength = (float) getVerticalFadingEdgeLength();
return bottom > height - mPaddingBottom ?
(float) (bottom - height + mPaddingBottom) / fadeLength : fadeEdge;
}
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
if (mSelector == null) {
useDefaultSelector();
}
final Rect listPadding = mListPadding;
listPadding.left = mSelectionLeftPadding + mPaddingLeft;
listPadding.top = mSelectionTopPadding + mPaddingTop;
listPadding.right = mSelectionRightPadding + mPaddingRight;
listPadding.bottom = mSelectionBottomPadding + mPaddingBottom;
}
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
super.onLayout(changed, l, t, r, b);
mInLayout = true;
layoutChildren();
mInLayout = false;
}
/**
* @hide
*/
@Override
protected boolean setFrame(int left, int top, int right, int bottom) {
final boolean changed = super.setFrame(left, top, right, bottom);
// Reposition the popup when the frame has changed. This includes
// translating the widget, not just changing its dimension. The
// filter popup needs to follow the widget.
if (mFiltered && changed && getWindowVisibility() == View.VISIBLE && mPopup != null &&
mPopup.isShowing()) {
positionPopup();
}
return changed;
}
protected void layoutChildren() {
}
void updateScrollIndicators() {
if (mScrollUp != null) {
boolean canScrollUp;
// 0th element is not visible
canScrollUp = mFirstPosition > 0;
// ... Or top of 0th element is not visible
if (!canScrollUp) {
if (getChildCount() > 0) {
View child = getChildAt(0);
canScrollUp = child.getTop() < mListPadding.top;
}
}
mScrollUp.setVisibility(canScrollUp ? View.VISIBLE : View.INVISIBLE);
}
if (mScrollDown != null) {
boolean canScrollDown;
int count = getChildCount();
// Last item is not visible
canScrollDown = (mFirstPosition + count) < mItemCount;
// ... Or bottom of the last element is not visible
if (!canScrollDown && count > 0) {
View child = getChildAt(count - 1);
canScrollDown = child.getBottom() > mBottom - mListPadding.bottom;
}
mScrollDown.setVisibility(canScrollDown ? View.VISIBLE : View.INVISIBLE);
}
}
@Override
@ViewDebug.ExportedProperty
public View getSelectedView() {
if (mItemCount > 0 && mSelectedPosition >= 0) {
return getChildAt(mSelectedPosition - mFirstPosition);
} else {
return null;
}
}
/**
* List padding is the maximum of the normal view's padding and the padding of the selector.
*
* @see android.view.View#getPaddingTop()
* @see #getSelector()
*
* @return The top list padding.
*/
public int getListPaddingTop() {
return mListPadding.top;
}
/**
* List padding is the maximum of the normal view's padding and the padding of the selector.
*
* @see android.view.View#getPaddingBottom()
* @see #getSelector()
*
* @return The bottom list padding.
*/
public int getListPaddingBottom() {
return mListPadding.bottom;
}
/**
* List padding is the maximum of the normal view's padding and the padding of the selector.
*
* @see android.view.View#getPaddingLeft()
* @see #getSelector()
*
* @return The left list padding.
*/
public int getListPaddingLeft() {
return mListPadding.left;
}
/**
* List padding is the maximum of the normal view's padding and the padding of the selector.
*
* @see android.view.View#getPaddingRight()
* @see #getSelector()
*
* @return The right list padding.
*/
public int getListPaddingRight() {
return mListPadding.right;
}
/**
* Get a view and have it show the data associated with the specified
* position. This is called when we have already discovered that the view is
* not available for reuse in the recycle bin. The only choices left are
* converting an old view or making a new one.
*
* @param position The position to display
* @return A view displaying the data associated with the specified position
*/
View obtainView(int position) {
View scrapView;
scrapView = mRecycler.getScrapView(position);
View child;
if (scrapView != null) {
if (ViewDebug.TRACE_RECYCLER) {
ViewDebug.trace(scrapView, ViewDebug.RecyclerTraceType.RECYCLE_FROM_SCRAP_HEAP,
position, -1);
}
child = mAdapter.getView(position, scrapView, this);
if (ViewDebug.TRACE_RECYCLER) {
ViewDebug.trace(child, ViewDebug.RecyclerTraceType.BIND_VIEW,
position, getChildCount());
}
if (child != scrapView) {
mRecycler.addScrapView(scrapView);
if (mCacheColorHint != 0) {
child.setDrawingCacheBackgroundColor(mCacheColorHint);
}
if (ViewDebug.TRACE_RECYCLER) {
ViewDebug.trace(scrapView, ViewDebug.RecyclerTraceType.MOVE_TO_SCRAP_HEAP,
position, -1);
}
}
} else {
child = mAdapter.getView(position, null, this);
if (mCacheColorHint != 0) {
child.setDrawingCacheBackgroundColor(mCacheColorHint);
}
if (ViewDebug.TRACE_RECYCLER) {
ViewDebug.trace(child, ViewDebug.RecyclerTraceType.NEW_VIEW,
position, getChildCount());
}
}
return child;
}
void positionSelector(View sel) {
final Rect selectorRect = mSelectorRect;
selectorRect.set(sel.getLeft(), sel.getTop(), sel.getRight(), sel.getBottom());
positionSelector(selectorRect.left, selectorRect.top, selectorRect.right,
selectorRect.bottom);
final boolean isChildViewEnabled = mIsChildViewEnabled;
if (sel.isEnabled() != isChildViewEnabled) {
mIsChildViewEnabled = !isChildViewEnabled;
refreshDrawableState();
}
}
private void positionSelector(int l, int t, int r, int b) {
mSelectorRect.set(l - mSelectionLeftPadding, t - mSelectionTopPadding, r
+ mSelectionRightPadding, b + mSelectionBottomPadding);
}
@Override
protected void dispatchDraw(Canvas canvas) {
int saveCount = 0;
final boolean clipToPadding = (mGroupFlags & CLIP_TO_PADDING_MASK) == CLIP_TO_PADDING_MASK;
if (clipToPadding) {
saveCount = canvas.save();
final int scrollX = mScrollX;
final int scrollY = mScrollY;
canvas.clipRect(scrollX + mPaddingLeft, scrollY + mPaddingTop,
scrollX + mRight - mLeft - mPaddingRight,
scrollY + mBottom - mTop - mPaddingBottom);
mGroupFlags &= ~CLIP_TO_PADDING_MASK;
}
final boolean drawSelectorOnTop = mDrawSelectorOnTop;
if (!drawSelectorOnTop) {
drawSelector(canvas);
}
super.dispatchDraw(canvas);
if (drawSelectorOnTop) {
drawSelector(canvas);
}
if (clipToPadding) {
canvas.restoreToCount(saveCount);
mGroupFlags |= CLIP_TO_PADDING_MASK;
}
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
if (getChildCount() > 0) {
mDataChanged = true;
rememberSyncState();
}
if (mFastScroller != null) {
mFastScroller.onSizeChanged(w, h, oldw, oldh);
}
}
/**
* @return True if the current touch mode requires that we draw the selector in the pressed
* state.
*/
boolean touchModeDrawsInPressedState() {
// FIXME use isPressed for this
switch (mTouchMode) {
case TOUCH_MODE_TAP:
case TOUCH_MODE_DONE_WAITING:
return true;
default:
return false;
}
}
/**
* Indicates whether this view is in a state where the selector should be drawn. This will
* happen if we have focus but are not in touch mode, or we are in the middle of displaying
* the pressed state for an item.
*
* @return True if the selector should be shown
*/
boolean shouldShowSelector() {
return (hasFocus() && !isInTouchMode()) || touchModeDrawsInPressedState();
}
private void drawSelector(Canvas canvas) {
if (shouldShowSelector() && mSelectorRect != null && !mSelectorRect.isEmpty()) {
final Drawable selector = mSelector;
selector.setBounds(mSelectorRect);
selector.draw(canvas);
}
}
/**
* Controls whether the selection highlight drawable should be drawn on top of the item or
* behind it.
*
* @param onTop If true, the selector will be drawn on the item it is highlighting. The default
* is false.
*
* @attr ref android.R.styleable#AbsListView_drawSelectorOnTop
*/
public void setDrawSelectorOnTop(boolean onTop) {
mDrawSelectorOnTop = onTop;
}
/**
* Set a Drawable that should be used to highlight the currently selected item.
*
* @param resID A Drawable resource to use as the selection highlight.
*
* @attr ref android.R.styleable#AbsListView_listSelector
*/
public void setSelector(int resID) {
setSelector(getResources().getDrawable(resID));
}
public void setSelector(Drawable sel) {
if (mSelector != null) {
mSelector.setCallback(null);
unscheduleDrawable(mSelector);
}
mSelector = sel;
Rect padding = new Rect();
sel.getPadding(padding);
mSelectionLeftPadding = padding.left;
mSelectionTopPadding = padding.top;
mSelectionRightPadding = padding.right;
mSelectionBottomPadding = padding.bottom;
sel.setCallback(this);
sel.setState(getDrawableState());
}
/**
* Returns the selector {@link android.graphics.drawable.Drawable} that is used to draw the
* selection in the list.
*
* @return the drawable used to display the selector
*/
public Drawable getSelector() {
return mSelector;
}
/**
* Sets the selector state to "pressed" and posts a CheckForKeyLongPress to see if
* this is a long press.
*/
void keyPressed() {
Drawable selector = mSelector;
Rect selectorRect = mSelectorRect;
if (selector != null && (isFocused() || touchModeDrawsInPressedState())
&& selectorRect != null && !selectorRect.isEmpty()) {
final View v = getChildAt(mSelectedPosition - mFirstPosition);
if (v != null) {
if (v.hasFocusable()) return;
v.setPressed(true);
}
setPressed(true);
final boolean longClickable = isLongClickable();
Drawable d = selector.getCurrent();
if (d != null && d instanceof TransitionDrawable) {
if (longClickable) {
((TransitionDrawable) d).startTransition(ViewConfiguration
.getLongPressTimeout());
} else {
((TransitionDrawable) d).resetTransition();
}
}
if (longClickable && !mDataChanged) {
if (mPendingCheckForKeyLongPress == null) {
mPendingCheckForKeyLongPress = new CheckForKeyLongPress();
}
mPendingCheckForKeyLongPress.rememberWindowAttachCount();
postDelayed(mPendingCheckForKeyLongPress, ViewConfiguration.getLongPressTimeout());
}
}
}
public void setScrollIndicators(View up, View down) {
mScrollUp = up;
mScrollDown = down;
}
@Override
protected void drawableStateChanged() {
super.drawableStateChanged();
if (mSelector != null) {
mSelector.setState(getDrawableState());
}
}
@Override
protected int[] onCreateDrawableState(int extraSpace) {
// If the child view is enabled then do the default behavior.
if (mIsChildViewEnabled) {
// Common case
return super.onCreateDrawableState(extraSpace);
}
// The selector uses this View's drawable state. The selected child view
// is disabled, so we need to remove the enabled state from the drawable
// states.
final int enabledState = ENABLED_STATE_SET[0];
// If we don't have any extra space, it will return one of the static state arrays,
// and clearing the enabled state on those arrays is a bad thing! If we specify
// we need extra space, it will create+copy into a new array that safely mutable.
int[] state = super.onCreateDrawableState(extraSpace + 1);
int enabledPos = -1;
for (int i = state.length - 1; i >= 0; i--) {
if (state[i] == enabledState) {
enabledPos = i;
break;
}
}
// Remove the enabled state
if (enabledPos >= 0) {
System.arraycopy(state, enabledPos + 1, state, enabledPos,
state.length - enabledPos - 1);
}
return state;
}
@Override
public boolean verifyDrawable(Drawable dr) {
return mSelector == dr || super.verifyDrawable(dr);
}
@Override
protected void onAttachedToWindow() {
super.onAttachedToWindow();
final ViewTreeObserver treeObserver = getViewTreeObserver();
if (treeObserver != null) {
treeObserver.addOnTouchModeChangeListener(this);
}
}
@Override
protected void onDetachedFromWindow() {
super.onDetachedFromWindow();
final ViewTreeObserver treeObserver = getViewTreeObserver();
if (treeObserver != null) {
treeObserver.removeOnTouchModeChangeListener(this);
}
}
@Override
public void onWindowFocusChanged(boolean hasWindowFocus) {
super.onWindowFocusChanged(hasWindowFocus);
final int touchMode = isInTouchMode() ? TOUCH_MODE_ON : TOUCH_MODE_OFF;
if (!hasWindowFocus) {
setChildrenDrawingCacheEnabled(false);
removeCallbacks(mFlingRunnable);
// Always hide the type filter
dismissPopup();
if (touchMode == TOUCH_MODE_OFF) {
// Remember the last selected element
mResurrectToPosition = mSelectedPosition;
}
} else {
if (mFiltered) {
// Show the type filter only if a filter is in effect
showPopup();
}
// If we changed touch mode since the last time we had focus
if (touchMode != mLastTouchMode && mLastTouchMode != TOUCH_MODE_UNKNOWN) {
// If we come back in trackball mode, we bring the selection back
if (touchMode == TOUCH_MODE_OFF) {
// This will trigger a layout
resurrectSelection();
// If we come back in touch mode, then we want to hide the selector
} else {
hideSelector();
mLayoutMode = LAYOUT_NORMAL;
layoutChildren();
}
}
}
mLastTouchMode = touchMode;
}
/**
* Creates the ContextMenuInfo returned from {@link #getContextMenuInfo()}. This
* methods knows the view, position and ID of the item that received the
* long press.
*
* @param view The view that received the long press.
* @param position The position of the item that received the long press.
* @param id The ID of the item that received the long press.
* @return The extra information that should be returned by
* {@link #getContextMenuInfo()}.
*/
ContextMenuInfo createContextMenuInfo(View view, int position, long id) {
return new AdapterContextMenuInfo(view, position, id);
}
/**
* A base class for Runnables that will check that their view is still attached to
* the original window as when the Runnable was created.
*
*/
private class WindowRunnnable {
private int mOriginalAttachCount;
public void rememberWindowAttachCount() {
mOriginalAttachCount = getWindowAttachCount();
}
public boolean sameWindow() {
return hasWindowFocus() && getWindowAttachCount() == mOriginalAttachCount;
}
}
private class PerformClick extends WindowRunnnable implements Runnable {
View mChild;
int mClickMotionPosition;
public void run() {
// The data has changed since we posted this action in the event queue,
// bail out before bad things happen
if (mDataChanged) return;
if (mAdapter != null && mItemCount > 0 &&
mClickMotionPosition < mAdapter.getCount() && sameWindow()) {
performItemClick(mChild, mClickMotionPosition, getAdapter().getItemId(
mClickMotionPosition));
}
}
}
private class CheckForLongPress extends WindowRunnnable implements Runnable {
public void run() {
final int motionPosition = mMotionPosition;
final View child = getChildAt(motionPosition - mFirstPosition);
if (child != null) {
final int longPressPosition = mMotionPosition;
final long longPressId = mAdapter.getItemId(mMotionPosition);
boolean handled = false;
if (sameWindow() && !mDataChanged) {
handled = performLongPress(child, longPressPosition, longPressId);
}
if (handled) {
mTouchMode = TOUCH_MODE_REST;
setPressed(false);
child.setPressed(false);
} else {
mTouchMode = TOUCH_MODE_DONE_WAITING;
}
}
}
}
private class CheckForKeyLongPress extends WindowRunnnable implements Runnable {
public void run() {
if (isPressed() && mSelectedPosition >= 0) {
int index = mSelectedPosition - mFirstPosition;
View v = getChildAt(index);
if (!mDataChanged) {
boolean handled = false;
if (sameWindow()) {
handled = performLongPress(v, mSelectedPosition, mSelectedRowId);
}
if (handled) {
setPressed(false);
v.setPressed(false);
}
} else {
setPressed(false);
if (v != null) v.setPressed(false);
}
}
}
}
private boolean performLongPress(final View child,
final int longPressPosition, final long longPressId) {
boolean handled = false;
if (mOnItemLongClickListener != null) {
handled = mOnItemLongClickListener.onItemLongClick(AbsListView.this, child,
longPressPosition, longPressId);
}
if (!handled) {
mContextMenuInfo = createContextMenuInfo(child, longPressPosition, longPressId);
handled = super.showContextMenuForChild(AbsListView.this);
}
if (handled) {
performHapticFeedback(HapticFeedbackConstants.LONG_PRESS);
}
return handled;
}
@Override
protected ContextMenuInfo getContextMenuInfo() {
return mContextMenuInfo;
}
@Override
public boolean showContextMenuForChild(View originalView) {
final int longPressPosition = getPositionForView(originalView);
if (longPressPosition >= 0) {
final long longPressId = mAdapter.getItemId(longPressPosition);
boolean handled = false;
if (mOnItemLongClickListener != null) {
handled = mOnItemLongClickListener.onItemLongClick(AbsListView.this, originalView,
longPressPosition, longPressId);
}
if (!handled) {
mContextMenuInfo = createContextMenuInfo(
getChildAt(longPressPosition - mFirstPosition),
longPressPosition, longPressId);
handled = super.showContextMenuForChild(originalView);
}
return handled;
}
return false;
}
@Override
public boolean onKeyUp(int keyCode, KeyEvent event) {
switch (keyCode) {
case KeyEvent.KEYCODE_DPAD_CENTER:
case KeyEvent.KEYCODE_ENTER:
if (isPressed() && mSelectedPosition >= 0 && mAdapter != null &&
mSelectedPosition < mAdapter.getCount()) {
final View view = getChildAt(mSelectedPosition - mFirstPosition);
performItemClick(view, mSelectedPosition, mSelectedRowId);
setPressed(false);
if (view != null) view.setPressed(false);
return true;
}
}
return super.onKeyUp(keyCode, event);
}
@Override
protected void dispatchSetPressed(boolean pressed) {
// Don't dispatch setPressed to our children. We call setPressed on ourselves to
// get the selector in the right state, but we don't want to press each child.
}
/**
* Maps a point to a position in the list.
*
* @param x X in local coordinate
* @param y Y in local coordinate
* @return The position of the item which contains the specified point, or
* {@link #INVALID_POSITION} if the point does not intersect an item.
*/
public int pointToPosition(int x, int y) {
Rect frame = mTouchFrame;
if (frame == null) {
mTouchFrame = new Rect();
frame = mTouchFrame;
}
final int count = getChildCount();
for (int i = count - 1; i >= 0; i--) {
final View child = getChildAt(i);
if (child.getVisibility() == View.VISIBLE) {
child.getHitRect(frame);
if (frame.contains(x, y)) {
return mFirstPosition + i;
}
}
}
return INVALID_POSITION;
}
/**
* Maps a point to a the rowId of the item which intersects that point.
*
* @param x X in local coordinate
* @param y Y in local coordinate
* @return The rowId of the item which contains the specified point, or {@link #INVALID_ROW_ID}
* if the point does not intersect an item.
*/
public long pointToRowId(int x, int y) {
int position = pointToPosition(x, y);
if (position >= 0) {
return mAdapter.getItemId(position);
}
return INVALID_ROW_ID;
}
final class CheckForTap implements Runnable {
public void run() {
if (mTouchMode == TOUCH_MODE_DOWN) {
mTouchMode = TOUCH_MODE_TAP;
final View child = getChildAt(mMotionPosition - mFirstPosition);
if (child != null && !child.hasFocusable()) {
mLayoutMode = LAYOUT_NORMAL;
if (!mDataChanged) {
layoutChildren();
child.setPressed(true);
positionSelector(child);
setPressed(true);
final int longPressTimeout = ViewConfiguration.getLongPressTimeout();
final boolean longClickable = isLongClickable();
if (mSelector != null) {
Drawable d = mSelector.getCurrent();
if (d != null && d instanceof TransitionDrawable) {
if (longClickable) {
((TransitionDrawable) d).startTransition(longPressTimeout);
} else {
((TransitionDrawable) d).resetTransition();
}
}
}
if (longClickable) {
if (mPendingCheckForLongPress == null) {
mPendingCheckForLongPress = new CheckForLongPress();
}
mPendingCheckForLongPress.rememberWindowAttachCount();
postDelayed(mPendingCheckForLongPress, longPressTimeout);
} else {
mTouchMode = TOUCH_MODE_DONE_WAITING;
}
} else {
mTouchMode = TOUCH_MODE_DONE_WAITING;
}
}
}
}
}
private boolean startScrollIfNeeded(int deltaY) {
// Check if we have moved far enough that it looks more like a
// scroll than a tap
final int distance = Math.abs(deltaY);
if (distance > mTouchSlop) {
createScrollingCache();
mTouchMode = TOUCH_MODE_SCROLL;
mMotionCorrection = deltaY;
final Handler handler = getHandler();
// Handler should not be null unless the AbsListView is not attached to a
// window, which would make it very hard to scroll it... but the monkeys
// say it's possible.
if (handler != null) {
handler.removeCallbacks(mPendingCheckForLongPress);
}
setPressed(false);
View motionView = getChildAt(mMotionPosition - mFirstPosition);
if (motionView != null) {
motionView.setPressed(false);
}
reportScrollStateChange(OnScrollListener.SCROLL_STATE_TOUCH_SCROLL);
// Time to start stealing events! Once we've stolen them, don't let anyone
// steal from us
requestDisallowInterceptTouchEvent(true);
return true;
}
return false;
}
public void onTouchModeChanged(boolean isInTouchMode) {
if (isInTouchMode) {
// Get rid of the selection when we enter touch mode
hideSelector();
// Layout, but only if we already have done so previously.
// (Otherwise may clobber a LAYOUT_SYNC layout that was requested to restore
// state.)
if (getHeight() > 0 && getChildCount() > 0) {
// We do not lose focus initiating a touch (since AbsListView is focusable in
// touch mode). Force an initial layout to get rid of the selection.
mLayoutMode = LAYOUT_NORMAL;
layoutChildren();
}
}
}
@Override
public boolean onTouchEvent(MotionEvent ev) {
if (mFastScroller != null) {
boolean intercepted = mFastScroller.onTouchEvent(ev);
if (intercepted) {
return true;
}
}
final int action = ev.getAction();
final int x = (int) ev.getX();
final int y = (int) ev.getY();
View v;
int deltaY;
if (mVelocityTracker == null) {
mVelocityTracker = VelocityTracker.obtain();
}
mVelocityTracker.addMovement(ev);
switch (action) {
case MotionEvent.ACTION_DOWN: {
int motionPosition = pointToPosition(x, y);
if (!mDataChanged) {
if ((mTouchMode != TOUCH_MODE_FLING) && (motionPosition >= 0)
&& (getAdapter().isEnabled(motionPosition))) {
// User clicked on an actual view (and was not stopping a fling). It might be a
// click or a scroll. Assume it is a click until proven otherwise
mTouchMode = TOUCH_MODE_DOWN;
// FIXME Debounce
if (mPendingCheckForTap == null) {
mPendingCheckForTap = new CheckForTap();
}
postDelayed(mPendingCheckForTap, ViewConfiguration.getTapTimeout());
} else {
if (ev.getEdgeFlags() != 0 && motionPosition < 0) {
// If we couldn't find a view to click on, but the down event was touching
// the edge, we will bail out and try again. This allows the edge correcting
// code in ViewRoot to try to find a nearby view to select
return false;
}
// User clicked on whitespace, or stopped a fling. It is a scroll.
createScrollingCache();
mTouchMode = TOUCH_MODE_SCROLL;
+ mMotionCorrection = 0;
motionPosition = findMotionRow(y);
reportScrollStateChange(OnScrollListener.SCROLL_STATE_TOUCH_SCROLL);
}
}
if (motionPosition >= 0) {
// Remember where the motion event started
v = getChildAt(motionPosition - mFirstPosition);
mMotionViewOriginalTop = v.getTop();
mMotionX = x;
mMotionY = y;
mMotionPosition = motionPosition;
}
mLastY = Integer.MIN_VALUE;
break;
}
case MotionEvent.ACTION_MOVE: {
deltaY = y - mMotionY;
switch (mTouchMode) {
case TOUCH_MODE_DOWN:
case TOUCH_MODE_TAP:
case TOUCH_MODE_DONE_WAITING:
// Check if we have moved far enough that it looks more like a
// scroll than a tap
startScrollIfNeeded(deltaY);
break;
case TOUCH_MODE_SCROLL:
if (PROFILE_SCROLLING) {
if (!mScrollProfilingStarted) {
Debug.startMethodTracing("AbsListViewScroll");
mScrollProfilingStarted = true;
}
}
if (y != mLastY) {
deltaY -= mMotionCorrection;
int incrementalDeltaY = mLastY != Integer.MIN_VALUE ? y - mLastY : deltaY;
trackMotionScroll(deltaY, incrementalDeltaY);
// Check to see if we have bumped into the scroll limit
View motionView = this.getChildAt(mMotionPosition - mFirstPosition);
if (motionView != null) {
// Check if the top of the motion view is where it is
// supposed to be
if (motionView.getTop() != mMotionViewNewTop) {
// We did not scroll the full amount. Treat this essentially like the
// start of a new touch scroll
final int motionPosition = findMotionRow(y);
mMotionCorrection = 0;
motionView = getChildAt(motionPosition - mFirstPosition);
mMotionViewOriginalTop = motionView.getTop();
mMotionY = y;
mMotionPosition = motionPosition;
}
}
mLastY = y;
}
break;
}
break;
}
case MotionEvent.ACTION_UP: {
switch (mTouchMode) {
case TOUCH_MODE_DOWN:
case TOUCH_MODE_TAP:
case TOUCH_MODE_DONE_WAITING:
final int motionPosition = mMotionPosition;
final View child = getChildAt(motionPosition - mFirstPosition);
if (child != null && !child.hasFocusable()) {
if (mTouchMode != TOUCH_MODE_DOWN) {
child.setPressed(false);
}
if (mPerformClick == null) {
mPerformClick = new PerformClick();
}
final AbsListView.PerformClick performClick = mPerformClick;
performClick.mChild = child;
performClick.mClickMotionPosition = motionPosition;
performClick.rememberWindowAttachCount();
mResurrectToPosition = motionPosition;
if (mTouchMode == TOUCH_MODE_DOWN || mTouchMode == TOUCH_MODE_TAP) {
final Handler handler = getHandler();
if (handler != null) {
handler.removeCallbacks(mTouchMode == TOUCH_MODE_DOWN ?
mPendingCheckForTap : mPendingCheckForLongPress);
}
mLayoutMode = LAYOUT_NORMAL;
mTouchMode = TOUCH_MODE_TAP;
if (!mDataChanged) {
setSelectedPositionInt(mMotionPosition);
layoutChildren();
child.setPressed(true);
positionSelector(child);
setPressed(true);
if (mSelector != null) {
Drawable d = mSelector.getCurrent();
if (d != null && d instanceof TransitionDrawable) {
((TransitionDrawable)d).resetTransition();
}
}
postDelayed(new Runnable() {
public void run() {
child.setPressed(false);
setPressed(false);
if (!mDataChanged) {
post(performClick);
}
mTouchMode = TOUCH_MODE_REST;
}
}, ViewConfiguration.getPressedStateDuration());
}
return true;
} else {
if (!mDataChanged) {
post(performClick);
}
}
}
mTouchMode = TOUCH_MODE_REST;
break;
case TOUCH_MODE_SCROLL:
final VelocityTracker velocityTracker = mVelocityTracker;
velocityTracker.computeCurrentVelocity(1000);
int initialVelocity = (int)velocityTracker.getYVelocity();
if ((Math.abs(initialVelocity) >
ViewConfiguration.get(mContext).getScaledMinimumFlingVelocity()) &&
(getChildCount() > 0)) {
if (mFlingRunnable == null) {
mFlingRunnable = new FlingRunnable();
}
reportScrollStateChange(OnScrollListener.SCROLL_STATE_FLING);
mFlingRunnable.start(-initialVelocity);
} else {
mTouchMode = TOUCH_MODE_REST;
reportScrollStateChange(OnScrollListener.SCROLL_STATE_IDLE);
}
}
setPressed(false);
// Need to redraw since we probably aren't drawing the selector anymore
invalidate();
final Handler handler = getHandler();
if (handler != null) {
handler.removeCallbacks(mPendingCheckForLongPress);
}
if (mVelocityTracker != null) {
mVelocityTracker.recycle();
mVelocityTracker = null;
}
if (PROFILE_SCROLLING) {
if (mScrollProfilingStarted) {
Debug.stopMethodTracing();
mScrollProfilingStarted = false;
}
}
break;
}
case MotionEvent.ACTION_CANCEL: {
mTouchMode = TOUCH_MODE_REST;
setPressed(false);
View motionView = this.getChildAt(mMotionPosition - mFirstPosition);
if (motionView != null) {
motionView.setPressed(false);
}
clearScrollingCache();
final Handler handler = getHandler();
if (handler != null) {
handler.removeCallbacks(mPendingCheckForLongPress);
}
if (mVelocityTracker != null) {
mVelocityTracker.recycle();
mVelocityTracker = null;
}
}
}
return true;
}
@Override
public void draw(Canvas canvas) {
super.draw(canvas);
if (mFastScroller != null) {
mFastScroller.draw(canvas);
}
}
@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
int action = ev.getAction();
int x = (int) ev.getX();
int y = (int) ev.getY();
View v;
if (mFastScroller != null) {
boolean intercepted = mFastScroller.onInterceptTouchEvent(ev);
if (intercepted) {
return true;
}
}
switch (action) {
case MotionEvent.ACTION_DOWN: {
int motionPosition = findMotionRow(y);
if (mTouchMode != TOUCH_MODE_FLING && motionPosition >= 0) {
// User clicked on an actual view (and was not stopping a fling).
// Remember where the motion event started
v = getChildAt(motionPosition - mFirstPosition);
mMotionViewOriginalTop = v.getTop();
mMotionX = x;
mMotionY = y;
mMotionPosition = motionPosition;
mTouchMode = TOUCH_MODE_DOWN;
clearScrollingCache();
}
mLastY = Integer.MIN_VALUE;
break;
}
case MotionEvent.ACTION_MOVE: {
switch (mTouchMode) {
case TOUCH_MODE_DOWN:
if (startScrollIfNeeded(y - mMotionY)) {
return true;
}
break;
}
break;
}
case MotionEvent.ACTION_UP: {
mTouchMode = TOUCH_MODE_REST;
reportScrollStateChange(OnScrollListener.SCROLL_STATE_IDLE);
break;
}
}
return false;
}
/**
* {@inheritDoc}
*/
@Override
public void addTouchables(ArrayList<View> views) {
final int count = getChildCount();
final int firstPosition = mFirstPosition;
final ListAdapter adapter = mAdapter;
if (adapter == null) {
return;
}
for (int i = 0; i < count; i++) {
final View child = getChildAt(i);
if (adapter.isEnabled(firstPosition + i)) {
views.add(child);
}
child.addTouchables(views);
}
}
/**
* Fires an "on scroll state changed" event to the registered
* {@link android.widget.AbsListView.OnScrollListener}, if any. The state change
* is fired only if the specified state is different from the previously known state.
*
* @param newState The new scroll state.
*/
void reportScrollStateChange(int newState) {
if (newState != mLastScrollState) {
if (mOnScrollListener != null) {
mOnScrollListener.onScrollStateChanged(this, newState);
mLastScrollState = newState;
}
}
}
/**
* Responsible for fling behavior. Use {@link #start(int)} to
* initiate a fling. Each frame of the fling is handled in {@link #run()}.
* A FlingRunnable will keep re-posting itself until the fling is done.
*
*/
private class FlingRunnable implements Runnable {
/**
* Tracks the decay of a fling scroll
*/
private Scroller mScroller;
/**
* Y value reported by mScroller on the previous fling
*/
private int mLastFlingY;
public FlingRunnable() {
mScroller = new Scroller(getContext());
}
public void start(int initialVelocity) {
int initialY = initialVelocity < 0 ? Integer.MAX_VALUE : 0;
mLastFlingY = initialY;
mScroller.fling(0, initialY, 0, initialVelocity,
0, Integer.MAX_VALUE, 0, Integer.MAX_VALUE);
mTouchMode = TOUCH_MODE_FLING;
post(this);
if (PROFILE_FLINGING) {
if (!mFlingProfilingStarted) {
Debug.startMethodTracing("AbsListViewFling");
mFlingProfilingStarted = true;
}
}
}
private void endFling() {
mTouchMode = TOUCH_MODE_REST;
reportScrollStateChange(OnScrollListener.SCROLL_STATE_IDLE);
clearScrollingCache();
}
public void run() {
if (mTouchMode != TOUCH_MODE_FLING) {
return;
}
if (mItemCount == 0 || getChildCount() == 0) {
endFling();
return;
}
final Scroller scroller = mScroller;
boolean more = scroller.computeScrollOffset();
final int y = scroller.getCurrY();
// Flip sign to convert finger direction to list items direction
// (e.g. finger moving down means list is moving towards the top)
int delta = mLastFlingY - y;
// Pretend that each frame of a fling scroll is a touch scroll
if (delta > 0) {
// List is moving towards the top. Use first view as mMotionPosition
mMotionPosition = mFirstPosition;
final View firstView = getChildAt(0);
mMotionViewOriginalTop = firstView.getTop();
// Don't fling more than 1 screen
delta = Math.min(getHeight() - mPaddingBottom - mPaddingTop - 1, delta);
} else {
// List is moving towards the bottom. Use last view as mMotionPosition
int offsetToLast = getChildCount() - 1;
mMotionPosition = mFirstPosition + offsetToLast;
final View lastView = getChildAt(offsetToLast);
mMotionViewOriginalTop = lastView.getTop();
// Don't fling more than 1 screen
delta = Math.max(-(getHeight() - mPaddingBottom - mPaddingTop - 1), delta);
}
trackMotionScroll(delta, delta);
// Check to see if we have bumped into the scroll limit
View motionView = getChildAt(mMotionPosition - mFirstPosition);
if (motionView != null) {
// Check if the top of the motion view is where it is
// supposed to be
if (motionView.getTop() != mMotionViewNewTop) {
more = false;
}
}
if (more) {
mLastFlingY = y;
post(this);
} else {
endFling();
if (PROFILE_FLINGING) {
if (mFlingProfilingStarted) {
Debug.stopMethodTracing();
mFlingProfilingStarted = false;
}
}
}
}
}
private void createScrollingCache() {
if (mScrollingCacheEnabled && !mCachingStarted) {
setChildrenDrawnWithCacheEnabled(true);
setChildrenDrawingCacheEnabled(true);
mCachingStarted = true;
}
}
private void clearScrollingCache() {
if (mCachingStarted) {
setChildrenDrawnWithCacheEnabled(false);
if ((mPersistentDrawingCache & PERSISTENT_SCROLLING_CACHE) == 0) {
setChildrenDrawingCacheEnabled(false);
}
if (!isAlwaysDrawnWithCacheEnabled()) {
invalidate();
}
mCachingStarted = false;
}
}
/**
* Track a motion scroll
*
* @param deltaY Amount to offset mMotionView. This is the accumulated delta since the motion
* began. Positive numbers mean the user's finger is moving down the screen.
* @param incrementalDeltaY Change in deltaY from the previous event.
*/
void trackMotionScroll(int deltaY, int incrementalDeltaY) {
final int childCount = getChildCount();
if (childCount == 0) {
return;
}
final int firstTop = getChildAt(0).getTop();
final int lastBottom = getChildAt(childCount - 1).getBottom();
final Rect listPadding = mListPadding;
// FIXME account for grid vertical spacing too?
final int spaceAbove = listPadding.top - firstTop;
final int end = getHeight() - listPadding.bottom;
final int spaceBelow = lastBottom - end;
final int height = getHeight() - mPaddingBottom - mPaddingTop;
if (deltaY < 0) {
deltaY = Math.max(-(height - 1), deltaY);
} else {
deltaY = Math.min(height - 1, deltaY);
}
if (incrementalDeltaY < 0) {
incrementalDeltaY = Math.max(-(height - 1), incrementalDeltaY);
} else {
incrementalDeltaY = Math.min(height - 1, incrementalDeltaY);
}
final int absIncrementalDeltaY = Math.abs(incrementalDeltaY);
if (spaceAbove >= absIncrementalDeltaY && spaceBelow >= absIncrementalDeltaY) {
hideSelector();
offsetChildrenTopAndBottom(incrementalDeltaY);
invalidate();
mMotionViewNewTop = mMotionViewOriginalTop + deltaY;
} else {
final int firstPosition = mFirstPosition;
if (firstPosition == 0 && firstTop >= listPadding.top && deltaY > 0) {
// Don't need to move views down if the top of the first position is already visible
return;
}
if (firstPosition + childCount == mItemCount && lastBottom <= end && deltaY < 0) {
// Don't need to move views up if the bottom of the last position is already visible
return;
}
final boolean down = incrementalDeltaY < 0;
hideSelector();
final int headerViewsCount = getHeaderViewsCount();
final int footerViewsStart = mItemCount - getFooterViewsCount();
int start = 0;
int count = 0;
if (down) {
final int top = listPadding.top - incrementalDeltaY;
for (int i = 0; i < childCount; i++) {
final View child = getChildAt(i);
if (child.getBottom() >= top) {
break;
} else {
count++;
int position = firstPosition + i;
if (position >= headerViewsCount && position < footerViewsStart) {
mRecycler.addScrapView(child);
if (ViewDebug.TRACE_RECYCLER) {
ViewDebug.trace(child,
ViewDebug.RecyclerTraceType.MOVE_TO_SCRAP_HEAP,
firstPosition + i, -1);
}
}
}
}
} else {
final int bottom = getHeight() - listPadding.bottom - incrementalDeltaY;
for (int i = childCount - 1; i >= 0; i--) {
final View child = getChildAt(i);
if (child.getTop() <= bottom) {
break;
} else {
start = i;
count++;
int position = firstPosition + i;
if (position >= headerViewsCount && position < footerViewsStart) {
mRecycler.addScrapView(child);
if (ViewDebug.TRACE_RECYCLER) {
ViewDebug.trace(child,
ViewDebug.RecyclerTraceType.MOVE_TO_SCRAP_HEAP,
firstPosition + i, -1);
}
}
}
}
}
mMotionViewNewTop = mMotionViewOriginalTop + deltaY;
mBlockLayoutRequests = true;
detachViewsFromParent(start, count);
offsetChildrenTopAndBottom(incrementalDeltaY);
if (down) {
mFirstPosition += count;
}
invalidate();
fillGap(down);
mBlockLayoutRequests = false;
invokeOnItemScrollListener();
}
}
/**
* Returns the number of header views in the list. Header views are special views
* at the top of the list that should not be recycled during a layout.
*
* @return The number of header views, 0 in the default implementation.
*/
int getHeaderViewsCount() {
return 0;
}
/**
* Returns the number of footer views in the list. Footer views are special views
* at the bottom of the list that should not be recycled during a layout.
*
* @return The number of footer views, 0 in the default implementation.
*/
int getFooterViewsCount() {
return 0;
}
/**
* Fills the gap left open by a touch-scroll. During a touch scroll, children that
* remain on screen are shifted and the other ones are discarded. The role of this
* method is to fill the gap thus created by performing a partial layout in the
* empty space.
*
* @param down true if the scroll is going down, false if it is going up
*/
abstract void fillGap(boolean down);
void hideSelector() {
if (mSelectedPosition != INVALID_POSITION) {
mResurrectToPosition = mSelectedPosition;
if (mNextSelectedPosition >= 0 && mNextSelectedPosition != mSelectedPosition) {
mResurrectToPosition = mNextSelectedPosition;
}
setSelectedPositionInt(INVALID_POSITION);
setNextSelectedPositionInt(INVALID_POSITION);
mSelectedTop = 0;
mSelectorRect.setEmpty();
}
}
/**
* @return A position to select. First we try mSelectedPosition. If that has been clobbered by
* entering touch mode, we then try mResurrectToPosition. Values are pinned to the range
* of items available in the adapter
*/
int reconcileSelectedPosition() {
int position = mSelectedPosition;
if (position < 0) {
position = mResurrectToPosition;
}
position = Math.max(0, position);
position = Math.min(position, mItemCount - 1);
return position;
}
/**
* Find the row closest to y. This row will be used as the motion row when scrolling
*
* @param y Where the user touched
* @return The position of the first (or only) item in the row closest to y
*/
abstract int findMotionRow(int y);
/**
* Causes all the views to be rebuilt and redrawn.
*/
public void invalidateViews() {
mDataChanged = true;
rememberSyncState();
requestLayout();
invalidate();
}
/**
* Makes the item at the supplied position selected.
*
* @param position the position of the new selection
*/
abstract void setSelectionInt(int position);
/**
* Attempt to bring the selection back if the user is switching from touch
* to trackball mode
* @return Whether selection was set to something.
*/
boolean resurrectSelection() {
final int childCount = getChildCount();
if (childCount <= 0) {
return false;
}
int selectedTop = 0;
int selectedPos;
int childrenTop = mListPadding.top;
int childrenBottom = mBottom - mTop - mListPadding.bottom;
final int firstPosition = mFirstPosition;
final int toPosition = mResurrectToPosition;
boolean down = true;
if (toPosition >= firstPosition && toPosition < firstPosition + childCount) {
selectedPos = toPosition;
final View selected = getChildAt(selectedPos - mFirstPosition);
selectedTop = selected.getTop();
int selectedBottom = selected.getBottom();
// We are scrolled, don't get in the fade
if (selectedTop < childrenTop) {
selectedTop = childrenTop + getVerticalFadingEdgeLength();
} else if (selectedBottom > childrenBottom) {
selectedTop = childrenBottom - selected.getMeasuredHeight()
- getVerticalFadingEdgeLength();
}
} else {
if (toPosition < firstPosition) {
// Default to selecting whatever is first
selectedPos = firstPosition;
for (int i = 0; i < childCount; i++) {
final View v = getChildAt(i);
final int top = v.getTop();
if (i == 0) {
// Remember the position of the first item
selectedTop = top;
// See if we are scrolled at all
if (firstPosition > 0 || top < childrenTop) {
// If we are scrolled, don't select anything that is
// in the fade region
childrenTop += getVerticalFadingEdgeLength();
}
}
if (top >= childrenTop) {
// Found a view whose top is fully visisble
selectedPos = firstPosition + i;
selectedTop = top;
break;
}
}
} else {
final int itemCount = mItemCount;
down = false;
selectedPos = firstPosition + childCount - 1;
for (int i = childCount - 1; i >= 0; i--) {
final View v = getChildAt(i);
final int top = v.getTop();
final int bottom = v.getBottom();
if (i == childCount - 1) {
selectedTop = top;
if (firstPosition + childCount < itemCount || bottom > childrenBottom) {
childrenBottom -= getVerticalFadingEdgeLength();
}
}
if (bottom <= childrenBottom) {
selectedPos = firstPosition + i;
selectedTop = top;
break;
}
}
}
}
mResurrectToPosition = INVALID_POSITION;
removeCallbacks(mFlingRunnable);
mTouchMode = TOUCH_MODE_REST;
clearScrollingCache();
mSpecificTop = selectedTop;
selectedPos = lookForSelectablePosition(selectedPos, down);
if (selectedPos >= firstPosition && selectedPos <= getLastVisiblePosition()) {
mLayoutMode = LAYOUT_SPECIFIC;
setSelectionInt(selectedPos);
invokeOnItemScrollListener();
} else {
selectedPos = INVALID_POSITION;
}
reportScrollStateChange(OnScrollListener.SCROLL_STATE_IDLE);
return selectedPos >= 0;
}
@Override
protected void handleDataChanged() {
int count = mItemCount;
if (count > 0) {
int newPos;
int selectablePos;
// Find the row we are supposed to sync to
if (mNeedSync) {
// Update this first, since setNextSelectedPositionInt inspects it
mNeedSync = false;
if (mTranscriptMode == TRANSCRIPT_MODE_ALWAYS_SCROLL ||
(mTranscriptMode == TRANSCRIPT_MODE_NORMAL &&
mFirstPosition + getChildCount() >= mOldItemCount)) {
mLayoutMode = LAYOUT_FORCE_BOTTOM;
return;
}
switch (mSyncMode) {
case SYNC_SELECTED_POSITION:
if (isInTouchMode()) {
// We saved our state when not in touch mode. (We know this because
// mSyncMode is SYNC_SELECTED_POSITION.) Now we are trying to
// restore in touch mode. Just leave mSyncPosition as it is (possibly
// adjusting if the available range changed) and return.
mLayoutMode = LAYOUT_SYNC;
mSyncPosition = Math.min(Math.max(0, mSyncPosition), count - 1);
return;
} else {
// See if we can find a position in the new data with the same
// id as the old selection. This will change mSyncPosition.
newPos = findSyncPosition();
if (newPos >= 0) {
// Found it. Now verify that new selection is still selectable
selectablePos = lookForSelectablePosition(newPos, true);
if (selectablePos == newPos) {
// Same row id is selected
mSyncPosition = newPos;
if (mSyncHeight == getHeight()) {
// If we are at the same height as when we saved state, try
// to restore the scroll position too.
mLayoutMode = LAYOUT_SYNC;
} else {
// We are not the same height as when the selection was saved, so
// don't try to restore the exact position
mLayoutMode = LAYOUT_SET_SELECTION;
}
// Restore selection
setNextSelectedPositionInt(newPos);
return;
}
}
}
break;
case SYNC_FIRST_POSITION:
// Leave mSyncPosition as it is -- just pin to available range
mLayoutMode = LAYOUT_SYNC;
mSyncPosition = Math.min(Math.max(0, mSyncPosition), count - 1);
return;
}
}
if (!isInTouchMode()) {
// We couldn't find matching data -- try to use the same position
newPos = getSelectedItemPosition();
// Pin position to the available range
if (newPos >= count) {
newPos = count - 1;
}
if (newPos < 0) {
newPos = 0;
}
// Make sure we select something selectable -- first look down
selectablePos = lookForSelectablePosition(newPos, true);
if (selectablePos >= 0) {
setNextSelectedPositionInt(selectablePos);
return;
} else {
// Looking down didn't work -- try looking up
selectablePos = lookForSelectablePosition(newPos, false);
if (selectablePos >= 0) {
setNextSelectedPositionInt(selectablePos);
return;
}
}
} else {
// We already know where we want to resurrect the selection
if (mResurrectToPosition >= 0) {
return;
}
}
}
// Nothing is selected. Give up and reset everything.
mLayoutMode = mStackFromBottom ? LAYOUT_FORCE_BOTTOM : LAYOUT_FORCE_TOP;
mSelectedPosition = INVALID_POSITION;
mSelectedRowId = INVALID_ROW_ID;
mNextSelectedPosition = INVALID_POSITION;
mNextSelectedRowId = INVALID_ROW_ID;
mNeedSync = false;
checkSelectionChanged();
}
/**
* Removes the filter window
*/
void dismissPopup() {
if (mPopup != null) {
mPopup.dismiss();
}
}
/**
* Shows the filter window
*/
private void showPopup() {
// Make sure we have a window before showing the popup
if (getWindowVisibility() == View.VISIBLE) {
createTextFilter(true);
positionPopup();
// Make sure we get focus if we are showing the popup
checkFocus();
}
}
private void positionPopup() {
int screenHeight = getResources().getDisplayMetrics().heightPixels;
final int[] xy = new int[2];
getLocationOnScreen(xy);
// TODO: The 20 below should come from the theme and be expressed in dip
// TODO: And the gravity should be defined in the theme as well
final int bottomGap = screenHeight - xy[1] - getHeight() + (int) (mDensityScale * 20);
if (!mPopup.isShowing()) {
mPopup.showAtLocation(this, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL,
xy[0], bottomGap);
} else {
mPopup.update(xy[0], bottomGap, -1, -1);
}
}
/**
* What is the distance between the source and destination rectangles given the direction of
* focus navigation between them? The direction basically helps figure out more quickly what is
* self evident by the relationship between the rects...
*
* @param source the source rectangle
* @param dest the destination rectangle
* @param direction the direction
* @return the distance between the rectangles
*/
static int getDistance(Rect source, Rect dest, int direction) {
int sX, sY; // source x, y
int dX, dY; // dest x, y
switch (direction) {
case View.FOCUS_RIGHT:
sX = source.right;
sY = source.top + source.height() / 2;
dX = dest.left;
dY = dest.top + dest.height() / 2;
break;
case View.FOCUS_DOWN:
sX = source.left + source.width() / 2;
sY = source.bottom;
dX = dest.left + dest.width() / 2;
dY = dest.top;
break;
case View.FOCUS_LEFT:
sX = source.left;
sY = source.top + source.height() / 2;
dX = dest.right;
dY = dest.top + dest.height() / 2;
break;
case View.FOCUS_UP:
sX = source.left + source.width() / 2;
sY = source.top;
dX = dest.left + dest.width() / 2;
dY = dest.bottom;
break;
default:
throw new IllegalArgumentException("direction must be one of "
+ "{FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, FOCUS_RIGHT}.");
}
int deltaX = dX - sX;
int deltaY = dY - sY;
return deltaY * deltaY + deltaX * deltaX;
}
@Override
protected boolean isInFilterMode() {
return mFiltered;
}
/**
* Sends a key to the text filter window
*
* @param keyCode The keycode for the event
* @param event The actual key event
*
* @return True if the text filter handled the event, false otherwise.
*/
boolean sendToTextFilter(int keyCode, int count, KeyEvent event) {
if (!acceptFilter()) {
return false;
}
boolean handled = false;
boolean okToSend = true;
switch (keyCode) {
case KeyEvent.KEYCODE_DPAD_UP:
case KeyEvent.KEYCODE_DPAD_DOWN:
case KeyEvent.KEYCODE_DPAD_LEFT:
case KeyEvent.KEYCODE_DPAD_RIGHT:
case KeyEvent.KEYCODE_DPAD_CENTER:
case KeyEvent.KEYCODE_ENTER:
okToSend = false;
break;
case KeyEvent.KEYCODE_BACK:
if (mFiltered && mPopup != null && mPopup.isShowing() &&
event.getAction() == KeyEvent.ACTION_DOWN) {
handled = true;
mTextFilter.setText("");
}
okToSend = false;
break;
case KeyEvent.KEYCODE_SPACE:
// Only send spaces once we are filtered
okToSend = mFiltered = true;
break;
}
if (okToSend) {
createTextFilter(true);
KeyEvent forwardEvent = event;
if (forwardEvent.getRepeatCount() > 0) {
forwardEvent = KeyEvent.changeTimeRepeat(event, event.getEventTime(), 0);
}
int action = event.getAction();
switch (action) {
case KeyEvent.ACTION_DOWN:
handled = mTextFilter.onKeyDown(keyCode, forwardEvent);
break;
case KeyEvent.ACTION_UP:
handled = mTextFilter.onKeyUp(keyCode, forwardEvent);
break;
case KeyEvent.ACTION_MULTIPLE:
handled = mTextFilter.onKeyMultiple(keyCode, count, event);
break;
}
}
return handled;
}
/**
* Return an InputConnection for editing of the filter text.
*/
@Override
public InputConnection onCreateInputConnection(EditorInfo outAttrs) {
if (isTextFilterEnabled()) {
// XXX we need to have the text filter created, so we can get an
// InputConnection to proxy to. Unfortunately this means we pretty
// much need to make it as soon as a list view gets focus.
createTextFilter(false);
if (mPublicInputConnection == null) {
mDefInputConnection = new BaseInputConnection(this, false);
mPublicInputConnection = new InputConnectionWrapper(
mTextFilter.onCreateInputConnection(outAttrs), true) {
@Override
public boolean reportFullscreenMode(boolean enabled) {
// Use our own input connection, since it is
// the "real" one the IME is talking with.
return mDefInputConnection.reportFullscreenMode(enabled);
}
@Override
public boolean performEditorAction(int editorAction) {
// The editor is off in its own window; we need to be
// the one that does this.
if (editorAction == EditorInfo.IME_ACTION_DONE) {
InputMethodManager imm = (InputMethodManager)
getContext().getSystemService(
Context.INPUT_METHOD_SERVICE);
if (imm != null) {
imm.hideSoftInputFromWindow(getWindowToken(), 0);
}
return true;
}
return false;
}
@Override
public boolean sendKeyEvent(KeyEvent event) {
// Use our own input connection, since the filter
// text view may not be shown in a window so has
// no ViewRoot to dispatch events with.
return mDefInputConnection.sendKeyEvent(event);
}
};
}
outAttrs.inputType = EditorInfo.TYPE_CLASS_TEXT
| EditorInfo.TYPE_TEXT_VARIATION_FILTER;
outAttrs.imeOptions = EditorInfo.IME_ACTION_DONE;
return mPublicInputConnection;
}
return null;
}
/**
* For filtering we proxy an input connection to an internal text editor,
* and this allows the proxying to happen.
*/
@Override
public boolean checkInputConnectionProxy(View view) {
return view == mTextFilter;
}
/**
* Creates the window for the text filter and populates it with an EditText field;
*
* @param animateEntrance true if the window should appear with an animation
*/
private void createTextFilter(boolean animateEntrance) {
if (mPopup == null) {
Context c = getContext();
PopupWindow p = new PopupWindow(c);
LayoutInflater layoutInflater = (LayoutInflater)
c.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
mTextFilter = (EditText) layoutInflater.inflate(
com.android.internal.R.layout.typing_filter, null);
// For some reason setting this as the "real" input type changes
// the text view in some way that it doesn't work, and I don't
// want to figure out why this is.
mTextFilter.setRawInputType(EditorInfo.TYPE_CLASS_TEXT
| EditorInfo.TYPE_TEXT_VARIATION_FILTER);
mTextFilter.setImeOptions(EditorInfo.IME_FLAG_NO_EXTRACT_UI);
mTextFilter.addTextChangedListener(this);
p.setFocusable(false);
p.setTouchable(false);
p.setInputMethodMode(PopupWindow.INPUT_METHOD_NOT_NEEDED);
p.setContentView(mTextFilter);
p.setWidth(LayoutParams.WRAP_CONTENT);
p.setHeight(LayoutParams.WRAP_CONTENT);
p.setBackgroundDrawable(null);
mPopup = p;
getViewTreeObserver().addOnGlobalLayoutListener(this);
}
if (animateEntrance) {
mPopup.setAnimationStyle(com.android.internal.R.style.Animation_TypingFilter);
} else {
mPopup.setAnimationStyle(com.android.internal.R.style.Animation_TypingFilterRestore);
}
}
/**
* Clear the text filter.
*/
public void clearTextFilter() {
if (mFiltered) {
mTextFilter.setText("");
mFiltered = false;
if (mPopup != null && mPopup.isShowing()) {
dismissPopup();
}
}
}
/**
* Returns if the ListView currently has a text filter.
*/
public boolean hasTextFilter() {
return mFiltered;
}
public void onGlobalLayout() {
if (isShown()) {
// Show the popup if we are filtered
if (mFiltered && mPopup != null && !mPopup.isShowing()) {
showPopup();
}
} else {
// Hide the popup when we are no longer visible
if (mPopup.isShowing()) {
dismissPopup();
}
}
}
/**
* For our text watcher that is associated with the text filter. Does
* nothing.
*/
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
/**
* For our text watcher that is associated with the text filter. Performs
* the actual filtering as the text changes, and takes care of hiding and
* showing the popup displaying the currently entered filter text.
*/
public void onTextChanged(CharSequence s, int start, int before, int count) {
if (mPopup != null && isTextFilterEnabled()) {
int length = s.length();
boolean showing = mPopup.isShowing();
if (!showing && length > 0) {
// Show the filter popup if necessary
showPopup();
mFiltered = true;
} else if (showing && length == 0) {
// Remove the filter popup if the user has cleared all text
dismissPopup();
mFiltered = false;
}
if (mAdapter instanceof Filterable) {
Filter f = ((Filterable) mAdapter).getFilter();
// Filter should not be null when we reach this part
if (f != null) {
f.filter(s, this);
} else {
throw new IllegalStateException("You cannot call onTextChanged with a non "
+ "filterable adapter");
}
}
}
}
/**
* For our text watcher that is associated with the text filter. Does
* nothing.
*/
public void afterTextChanged(Editable s) {
}
public void onFilterComplete(int count) {
if (mSelectedPosition < 0 && count > 0) {
mResurrectToPosition = INVALID_POSITION;
resurrectSelection();
}
}
@Override
protected ViewGroup.LayoutParams generateLayoutParams(ViewGroup.LayoutParams p) {
return new LayoutParams(p);
}
@Override
public LayoutParams generateLayoutParams(AttributeSet attrs) {
return new AbsListView.LayoutParams(getContext(), attrs);
}
@Override
protected boolean checkLayoutParams(ViewGroup.LayoutParams p) {
return p instanceof AbsListView.LayoutParams;
}
/**
* Puts the list or grid into transcript mode. In this mode the list or grid will always scroll
* to the bottom to show new items.
*
* @param mode the transcript mode to set
*
* @see #TRANSCRIPT_MODE_DISABLED
* @see #TRANSCRIPT_MODE_NORMAL
* @see #TRANSCRIPT_MODE_ALWAYS_SCROLL
*/
public void setTranscriptMode(int mode) {
mTranscriptMode = mode;
}
/**
* Returns the current transcript mode.
*
* @return {@link #TRANSCRIPT_MODE_DISABLED}, {@link #TRANSCRIPT_MODE_NORMAL} or
* {@link #TRANSCRIPT_MODE_ALWAYS_SCROLL}
*/
public int getTranscriptMode() {
return mTranscriptMode;
}
@Override
public int getSolidColor() {
return mCacheColorHint;
}
/**
* When set to a non-zero value, the cache color hint indicates that this list is always drawn
* on top of a solid, single-color, opaque background
*
* @param color The background color
*/
public void setCacheColorHint(int color) {
mCacheColorHint = color;
}
/**
* When set to a non-zero value, the cache color hint indicates that this list is always drawn
* on top of a solid, single-color, opaque background
*
* @return The cache color hint
*/
public int getCacheColorHint() {
return mCacheColorHint;
}
/**
* Move all views (excluding headers and footers) held by this AbsListView into the supplied
* List. This includes views displayed on the screen as well as views stored in AbsListView's
* internal view recycler.
*
* @param views A list into which to put the reclaimed views
*/
public void reclaimViews(List<View> views) {
int childCount = getChildCount();
RecyclerListener listener = mRecycler.mRecyclerListener;
// Reclaim views on screen
for (int i = 0; i < childCount; i++) {
View child = getChildAt(i);
AbsListView.LayoutParams lp = (AbsListView.LayoutParams)child.getLayoutParams();
// Don't reclaim header or footer views, or views that should be ignored
if (lp != null && mRecycler.shouldRecycleViewType(lp.viewType)) {
views.add(child);
if (listener != null) {
// Pretend they went through the scrap heap
listener.onMovedToScrapHeap(child);
}
}
}
mRecycler.reclaimScrapViews(views);
removeAllViewsInLayout();
}
/**
* Sets the recycler listener to be notified whenever a View is set aside in
* the recycler for later reuse. This listener can be used to free resources
* associated to the View.
*
* @param listener The recycler listener to be notified of views set aside
* in the recycler.
*
* @see android.widget.AbsListView.RecycleBin
* @see android.widget.AbsListView.RecyclerListener
*/
public void setRecyclerListener(RecyclerListener listener) {
mRecycler.mRecyclerListener = listener;
}
/**
* AbsListView extends LayoutParams to provide a place to hold the view type.
*/
public static class LayoutParams extends ViewGroup.LayoutParams {
/**
* View type for this view, as returned by
* {@link android.widget.Adapter#getItemViewType(int) }
*/
int viewType;
/**
* When this boolean is set, the view has been added to the AbsListView
* at least once. It is used to know whether headers/footers have already
* been added to the list view and whether they should be treated as
* recycled views or not.
*/
boolean recycledHeaderFooter;
public LayoutParams(Context c, AttributeSet attrs) {
super(c, attrs);
}
public LayoutParams(int w, int h) {
super(w, h);
}
public LayoutParams(int w, int h, int viewType) {
super(w, h);
this.viewType = viewType;
}
public LayoutParams(ViewGroup.LayoutParams source) {
super(source);
}
}
/**
* A RecyclerListener is used to receive a notification whenever a View is placed
* inside the RecycleBin's scrap heap. This listener is used to free resources
* associated to Views placed in the RecycleBin.
*
* @see android.widget.AbsListView.RecycleBin
* @see android.widget.AbsListView#setRecyclerListener(android.widget.AbsListView.RecyclerListener)
*/
public static interface RecyclerListener {
/**
* Indicates that the specified View was moved into the recycler's scrap heap.
* The view is not displayed on screen any more and any expensive resource
* associated with the view should be discarded.
*
* @param view
*/
void onMovedToScrapHeap(View view);
}
/**
* The RecycleBin facilitates reuse of views across layouts. The RecycleBin has two levels of
* storage: ActiveViews and ScrapViews. ActiveViews are those views which were onscreen at the
* start of a layout. By construction, they are displaying current information. At the end of
* layout, all views in ActiveViews are demoted to ScrapViews. ScrapViews are old views that
* could potentially be used by the adapter to avoid allocating views unnecessarily.
*
* @see android.widget.AbsListView#setRecyclerListener(android.widget.AbsListView.RecyclerListener)
* @see android.widget.AbsListView.RecyclerListener
*/
class RecycleBin {
private RecyclerListener mRecyclerListener;
/**
* The position of the first view stored in mActiveViews.
*/
private int mFirstActivePosition;
/**
* Views that were on screen at the start of layout. This array is populated at the start of
* layout, and at the end of layout all view in mActiveViews are moved to mScrapViews.
* Views in mActiveViews represent a contiguous range of Views, with position of the first
* view store in mFirstActivePosition.
*/
private View[] mActiveViews = new View[0];
/**
* Unsorted views that can be used by the adapter as a convert view.
*/
private ArrayList<View>[] mScrapViews;
private int mViewTypeCount;
private ArrayList<View> mCurrentScrap;
public void setViewTypeCount(int viewTypeCount) {
if (viewTypeCount < 1) {
throw new IllegalArgumentException("Can't have a viewTypeCount < 1");
}
//noinspection unchecked
ArrayList<View>[] scrapViews = new ArrayList[viewTypeCount];
for (int i = 0; i < viewTypeCount; i++) {
scrapViews[i] = new ArrayList<View>();
}
mViewTypeCount = viewTypeCount;
mCurrentScrap = scrapViews[0];
mScrapViews = scrapViews;
}
public boolean shouldRecycleViewType(int viewType) {
return viewType >= 0;
}
/**
* Clears the scrap heap.
*/
void clear() {
if (mViewTypeCount == 1) {
final ArrayList<View> scrap = mCurrentScrap;
final int scrapCount = scrap.size();
for (int i = 0; i < scrapCount; i++) {
removeDetachedView(scrap.remove(scrapCount - 1 - i), false);
}
} else {
final int typeCount = mViewTypeCount;
for (int i = 0; i < typeCount; i++) {
final ArrayList<View> scrap = mScrapViews[i];
final int scrapCount = scrap.size();
for (int j = 0; j < scrapCount; j++) {
removeDetachedView(scrap.remove(scrapCount - 1 - j), false);
}
}
}
}
/**
* Fill ActiveViews with all of the children of the AbsListView.
*
* @param childCount The minimum number of views mActiveViews should hold
* @param firstActivePosition The position of the first view that will be stored in
* mActiveViews
*/
void fillActiveViews(int childCount, int firstActivePosition) {
if (mActiveViews.length < childCount) {
mActiveViews = new View[childCount];
}
mFirstActivePosition = firstActivePosition;
final View[] activeViews = mActiveViews;
for (int i = 0; i < childCount; i++) {
View child = getChildAt(i);
AbsListView.LayoutParams lp = (AbsListView.LayoutParams)child.getLayoutParams();
// Don't put header or footer views into the scrap heap
if (lp != null && lp.viewType != AdapterView.ITEM_VIEW_TYPE_HEADER_OR_FOOTER) {
// Note: We do place AdapterView.ITEM_VIEW_TYPE_IGNORE in active views.
// However, we will NOT place them into scrap views.
activeViews[i] = child;
}
}
}
/**
* Get the view corresponding to the specified position. The view will be removed from
* mActiveViews if it is found.
*
* @param position The position to look up in mActiveViews
* @return The view if it is found, null otherwise
*/
View getActiveView(int position) {
int index = position - mFirstActivePosition;
final View[] activeViews = mActiveViews;
if (index >=0 && index < activeViews.length) {
final View match = activeViews[index];
activeViews[index] = null;
return match;
}
return null;
}
/**
* @return A view from the ScrapViews collection. These are unordered.
*/
View getScrapView(int position) {
ArrayList<View> scrapViews;
if (mViewTypeCount == 1) {
scrapViews = mCurrentScrap;
int size = scrapViews.size();
if (size > 0) {
return scrapViews.remove(size - 1);
} else {
return null;
}
} else {
int whichScrap = mAdapter.getItemViewType(position);
if (whichScrap >= 0 && whichScrap < mScrapViews.length) {
scrapViews = mScrapViews[whichScrap];
int size = scrapViews.size();
if (size > 0) {
return scrapViews.remove(size - 1);
}
}
}
return null;
}
/**
* Put a view into the ScapViews list. These views are unordered.
*
* @param scrap The view to add
*/
void addScrapView(View scrap) {
AbsListView.LayoutParams lp = (AbsListView.LayoutParams) scrap.getLayoutParams();
if (lp == null) {
return;
}
// Don't put header or footer views or views that should be ignored
// into the scrap heap
int viewType = lp.viewType;
if (!shouldRecycleViewType(viewType)) {
return;
}
if (mViewTypeCount == 1) {
mCurrentScrap.add(scrap);
} else {
mScrapViews[viewType].add(scrap);
}
if (mRecyclerListener != null) {
mRecyclerListener.onMovedToScrapHeap(scrap);
}
}
/**
* Move all views remaining in mActiveViews to mScrapViews.
*/
void scrapActiveViews() {
final View[] activeViews = mActiveViews;
final boolean hasListener = mRecyclerListener != null;
final boolean multipleScraps = mViewTypeCount > 1;
ArrayList<View> scrapViews = mCurrentScrap;
final int count = activeViews.length;
for (int i = 0; i < count; ++i) {
final View victim = activeViews[i];
if (victim != null) {
int whichScrap = ((AbsListView.LayoutParams)
victim.getLayoutParams()).viewType;
activeViews[i] = null;
if (whichScrap == AdapterView.ITEM_VIEW_TYPE_IGNORE) {
// Do not move views that should be ignored
continue;
}
if (multipleScraps) {
scrapViews = mScrapViews[whichScrap];
}
scrapViews.add(victim);
if (hasListener) {
mRecyclerListener.onMovedToScrapHeap(victim);
}
if (ViewDebug.TRACE_RECYCLER) {
ViewDebug.trace(victim,
ViewDebug.RecyclerTraceType.MOVE_FROM_ACTIVE_TO_SCRAP_HEAP,
mFirstActivePosition + i, -1);
}
}
}
pruneScrapViews();
}
/**
* Makes sure that the size of mScrapViews does not exceed the size of mActiveViews.
* (This can happen if an adapter does not recycle its views).
*/
private void pruneScrapViews() {
final int maxViews = mActiveViews.length;
final int viewTypeCount = mViewTypeCount;
final ArrayList<View>[] scrapViews = mScrapViews;
for (int i = 0; i < viewTypeCount; ++i) {
final ArrayList<View> scrapPile = scrapViews[i];
int size = scrapPile.size();
final int extras = size - maxViews;
size--;
for (int j = 0; j < extras; j++) {
removeDetachedView(scrapPile.remove(size--), false);
}
}
}
/**
* Puts all views in the scrap heap into the supplied list.
*/
void reclaimScrapViews(List<View> views) {
if (mViewTypeCount == 1) {
views.addAll(mCurrentScrap);
} else {
final int viewTypeCount = mViewTypeCount;
final ArrayList<View>[] scrapViews = mScrapViews;
for (int i = 0; i < viewTypeCount; ++i) {
final ArrayList<View> scrapPile = scrapViews[i];
views.addAll(scrapPile);
}
}
}
}
}
| true | true | public boolean onTouchEvent(MotionEvent ev) {
if (mFastScroller != null) {
boolean intercepted = mFastScroller.onTouchEvent(ev);
if (intercepted) {
return true;
}
}
final int action = ev.getAction();
final int x = (int) ev.getX();
final int y = (int) ev.getY();
View v;
int deltaY;
if (mVelocityTracker == null) {
mVelocityTracker = VelocityTracker.obtain();
}
mVelocityTracker.addMovement(ev);
switch (action) {
case MotionEvent.ACTION_DOWN: {
int motionPosition = pointToPosition(x, y);
if (!mDataChanged) {
if ((mTouchMode != TOUCH_MODE_FLING) && (motionPosition >= 0)
&& (getAdapter().isEnabled(motionPosition))) {
// User clicked on an actual view (and was not stopping a fling). It might be a
// click or a scroll. Assume it is a click until proven otherwise
mTouchMode = TOUCH_MODE_DOWN;
// FIXME Debounce
if (mPendingCheckForTap == null) {
mPendingCheckForTap = new CheckForTap();
}
postDelayed(mPendingCheckForTap, ViewConfiguration.getTapTimeout());
} else {
if (ev.getEdgeFlags() != 0 && motionPosition < 0) {
// If we couldn't find a view to click on, but the down event was touching
// the edge, we will bail out and try again. This allows the edge correcting
// code in ViewRoot to try to find a nearby view to select
return false;
}
// User clicked on whitespace, or stopped a fling. It is a scroll.
createScrollingCache();
mTouchMode = TOUCH_MODE_SCROLL;
motionPosition = findMotionRow(y);
reportScrollStateChange(OnScrollListener.SCROLL_STATE_TOUCH_SCROLL);
}
}
if (motionPosition >= 0) {
// Remember where the motion event started
v = getChildAt(motionPosition - mFirstPosition);
mMotionViewOriginalTop = v.getTop();
mMotionX = x;
mMotionY = y;
mMotionPosition = motionPosition;
}
mLastY = Integer.MIN_VALUE;
break;
}
case MotionEvent.ACTION_MOVE: {
deltaY = y - mMotionY;
switch (mTouchMode) {
case TOUCH_MODE_DOWN:
case TOUCH_MODE_TAP:
case TOUCH_MODE_DONE_WAITING:
// Check if we have moved far enough that it looks more like a
// scroll than a tap
startScrollIfNeeded(deltaY);
break;
case TOUCH_MODE_SCROLL:
if (PROFILE_SCROLLING) {
if (!mScrollProfilingStarted) {
Debug.startMethodTracing("AbsListViewScroll");
mScrollProfilingStarted = true;
}
}
if (y != mLastY) {
deltaY -= mMotionCorrection;
int incrementalDeltaY = mLastY != Integer.MIN_VALUE ? y - mLastY : deltaY;
trackMotionScroll(deltaY, incrementalDeltaY);
// Check to see if we have bumped into the scroll limit
View motionView = this.getChildAt(mMotionPosition - mFirstPosition);
if (motionView != null) {
// Check if the top of the motion view is where it is
// supposed to be
if (motionView.getTop() != mMotionViewNewTop) {
// We did not scroll the full amount. Treat this essentially like the
// start of a new touch scroll
final int motionPosition = findMotionRow(y);
mMotionCorrection = 0;
motionView = getChildAt(motionPosition - mFirstPosition);
mMotionViewOriginalTop = motionView.getTop();
mMotionY = y;
mMotionPosition = motionPosition;
}
}
mLastY = y;
}
break;
}
break;
}
case MotionEvent.ACTION_UP: {
switch (mTouchMode) {
case TOUCH_MODE_DOWN:
case TOUCH_MODE_TAP:
case TOUCH_MODE_DONE_WAITING:
final int motionPosition = mMotionPosition;
final View child = getChildAt(motionPosition - mFirstPosition);
if (child != null && !child.hasFocusable()) {
if (mTouchMode != TOUCH_MODE_DOWN) {
child.setPressed(false);
}
if (mPerformClick == null) {
mPerformClick = new PerformClick();
}
final AbsListView.PerformClick performClick = mPerformClick;
performClick.mChild = child;
performClick.mClickMotionPosition = motionPosition;
performClick.rememberWindowAttachCount();
mResurrectToPosition = motionPosition;
if (mTouchMode == TOUCH_MODE_DOWN || mTouchMode == TOUCH_MODE_TAP) {
final Handler handler = getHandler();
if (handler != null) {
handler.removeCallbacks(mTouchMode == TOUCH_MODE_DOWN ?
mPendingCheckForTap : mPendingCheckForLongPress);
}
mLayoutMode = LAYOUT_NORMAL;
mTouchMode = TOUCH_MODE_TAP;
if (!mDataChanged) {
setSelectedPositionInt(mMotionPosition);
layoutChildren();
child.setPressed(true);
positionSelector(child);
setPressed(true);
if (mSelector != null) {
Drawable d = mSelector.getCurrent();
if (d != null && d instanceof TransitionDrawable) {
((TransitionDrawable)d).resetTransition();
}
}
postDelayed(new Runnable() {
public void run() {
child.setPressed(false);
setPressed(false);
if (!mDataChanged) {
post(performClick);
}
mTouchMode = TOUCH_MODE_REST;
}
}, ViewConfiguration.getPressedStateDuration());
}
return true;
} else {
if (!mDataChanged) {
post(performClick);
}
}
}
mTouchMode = TOUCH_MODE_REST;
break;
case TOUCH_MODE_SCROLL:
final VelocityTracker velocityTracker = mVelocityTracker;
velocityTracker.computeCurrentVelocity(1000);
int initialVelocity = (int)velocityTracker.getYVelocity();
if ((Math.abs(initialVelocity) >
ViewConfiguration.get(mContext).getScaledMinimumFlingVelocity()) &&
(getChildCount() > 0)) {
if (mFlingRunnable == null) {
mFlingRunnable = new FlingRunnable();
}
reportScrollStateChange(OnScrollListener.SCROLL_STATE_FLING);
mFlingRunnable.start(-initialVelocity);
} else {
mTouchMode = TOUCH_MODE_REST;
reportScrollStateChange(OnScrollListener.SCROLL_STATE_IDLE);
}
}
setPressed(false);
// Need to redraw since we probably aren't drawing the selector anymore
invalidate();
final Handler handler = getHandler();
if (handler != null) {
handler.removeCallbacks(mPendingCheckForLongPress);
}
if (mVelocityTracker != null) {
mVelocityTracker.recycle();
mVelocityTracker = null;
}
if (PROFILE_SCROLLING) {
if (mScrollProfilingStarted) {
Debug.stopMethodTracing();
mScrollProfilingStarted = false;
}
}
break;
}
case MotionEvent.ACTION_CANCEL: {
mTouchMode = TOUCH_MODE_REST;
setPressed(false);
View motionView = this.getChildAt(mMotionPosition - mFirstPosition);
if (motionView != null) {
motionView.setPressed(false);
}
clearScrollingCache();
final Handler handler = getHandler();
if (handler != null) {
handler.removeCallbacks(mPendingCheckForLongPress);
}
if (mVelocityTracker != null) {
mVelocityTracker.recycle();
mVelocityTracker = null;
}
}
}
return true;
}
| public boolean onTouchEvent(MotionEvent ev) {
if (mFastScroller != null) {
boolean intercepted = mFastScroller.onTouchEvent(ev);
if (intercepted) {
return true;
}
}
final int action = ev.getAction();
final int x = (int) ev.getX();
final int y = (int) ev.getY();
View v;
int deltaY;
if (mVelocityTracker == null) {
mVelocityTracker = VelocityTracker.obtain();
}
mVelocityTracker.addMovement(ev);
switch (action) {
case MotionEvent.ACTION_DOWN: {
int motionPosition = pointToPosition(x, y);
if (!mDataChanged) {
if ((mTouchMode != TOUCH_MODE_FLING) && (motionPosition >= 0)
&& (getAdapter().isEnabled(motionPosition))) {
// User clicked on an actual view (and was not stopping a fling). It might be a
// click or a scroll. Assume it is a click until proven otherwise
mTouchMode = TOUCH_MODE_DOWN;
// FIXME Debounce
if (mPendingCheckForTap == null) {
mPendingCheckForTap = new CheckForTap();
}
postDelayed(mPendingCheckForTap, ViewConfiguration.getTapTimeout());
} else {
if (ev.getEdgeFlags() != 0 && motionPosition < 0) {
// If we couldn't find a view to click on, but the down event was touching
// the edge, we will bail out and try again. This allows the edge correcting
// code in ViewRoot to try to find a nearby view to select
return false;
}
// User clicked on whitespace, or stopped a fling. It is a scroll.
createScrollingCache();
mTouchMode = TOUCH_MODE_SCROLL;
mMotionCorrection = 0;
motionPosition = findMotionRow(y);
reportScrollStateChange(OnScrollListener.SCROLL_STATE_TOUCH_SCROLL);
}
}
if (motionPosition >= 0) {
// Remember where the motion event started
v = getChildAt(motionPosition - mFirstPosition);
mMotionViewOriginalTop = v.getTop();
mMotionX = x;
mMotionY = y;
mMotionPosition = motionPosition;
}
mLastY = Integer.MIN_VALUE;
break;
}
case MotionEvent.ACTION_MOVE: {
deltaY = y - mMotionY;
switch (mTouchMode) {
case TOUCH_MODE_DOWN:
case TOUCH_MODE_TAP:
case TOUCH_MODE_DONE_WAITING:
// Check if we have moved far enough that it looks more like a
// scroll than a tap
startScrollIfNeeded(deltaY);
break;
case TOUCH_MODE_SCROLL:
if (PROFILE_SCROLLING) {
if (!mScrollProfilingStarted) {
Debug.startMethodTracing("AbsListViewScroll");
mScrollProfilingStarted = true;
}
}
if (y != mLastY) {
deltaY -= mMotionCorrection;
int incrementalDeltaY = mLastY != Integer.MIN_VALUE ? y - mLastY : deltaY;
trackMotionScroll(deltaY, incrementalDeltaY);
// Check to see if we have bumped into the scroll limit
View motionView = this.getChildAt(mMotionPosition - mFirstPosition);
if (motionView != null) {
// Check if the top of the motion view is where it is
// supposed to be
if (motionView.getTop() != mMotionViewNewTop) {
// We did not scroll the full amount. Treat this essentially like the
// start of a new touch scroll
final int motionPosition = findMotionRow(y);
mMotionCorrection = 0;
motionView = getChildAt(motionPosition - mFirstPosition);
mMotionViewOriginalTop = motionView.getTop();
mMotionY = y;
mMotionPosition = motionPosition;
}
}
mLastY = y;
}
break;
}
break;
}
case MotionEvent.ACTION_UP: {
switch (mTouchMode) {
case TOUCH_MODE_DOWN:
case TOUCH_MODE_TAP:
case TOUCH_MODE_DONE_WAITING:
final int motionPosition = mMotionPosition;
final View child = getChildAt(motionPosition - mFirstPosition);
if (child != null && !child.hasFocusable()) {
if (mTouchMode != TOUCH_MODE_DOWN) {
child.setPressed(false);
}
if (mPerformClick == null) {
mPerformClick = new PerformClick();
}
final AbsListView.PerformClick performClick = mPerformClick;
performClick.mChild = child;
performClick.mClickMotionPosition = motionPosition;
performClick.rememberWindowAttachCount();
mResurrectToPosition = motionPosition;
if (mTouchMode == TOUCH_MODE_DOWN || mTouchMode == TOUCH_MODE_TAP) {
final Handler handler = getHandler();
if (handler != null) {
handler.removeCallbacks(mTouchMode == TOUCH_MODE_DOWN ?
mPendingCheckForTap : mPendingCheckForLongPress);
}
mLayoutMode = LAYOUT_NORMAL;
mTouchMode = TOUCH_MODE_TAP;
if (!mDataChanged) {
setSelectedPositionInt(mMotionPosition);
layoutChildren();
child.setPressed(true);
positionSelector(child);
setPressed(true);
if (mSelector != null) {
Drawable d = mSelector.getCurrent();
if (d != null && d instanceof TransitionDrawable) {
((TransitionDrawable)d).resetTransition();
}
}
postDelayed(new Runnable() {
public void run() {
child.setPressed(false);
setPressed(false);
if (!mDataChanged) {
post(performClick);
}
mTouchMode = TOUCH_MODE_REST;
}
}, ViewConfiguration.getPressedStateDuration());
}
return true;
} else {
if (!mDataChanged) {
post(performClick);
}
}
}
mTouchMode = TOUCH_MODE_REST;
break;
case TOUCH_MODE_SCROLL:
final VelocityTracker velocityTracker = mVelocityTracker;
velocityTracker.computeCurrentVelocity(1000);
int initialVelocity = (int)velocityTracker.getYVelocity();
if ((Math.abs(initialVelocity) >
ViewConfiguration.get(mContext).getScaledMinimumFlingVelocity()) &&
(getChildCount() > 0)) {
if (mFlingRunnable == null) {
mFlingRunnable = new FlingRunnable();
}
reportScrollStateChange(OnScrollListener.SCROLL_STATE_FLING);
mFlingRunnable.start(-initialVelocity);
} else {
mTouchMode = TOUCH_MODE_REST;
reportScrollStateChange(OnScrollListener.SCROLL_STATE_IDLE);
}
}
setPressed(false);
// Need to redraw since we probably aren't drawing the selector anymore
invalidate();
final Handler handler = getHandler();
if (handler != null) {
handler.removeCallbacks(mPendingCheckForLongPress);
}
if (mVelocityTracker != null) {
mVelocityTracker.recycle();
mVelocityTracker = null;
}
if (PROFILE_SCROLLING) {
if (mScrollProfilingStarted) {
Debug.stopMethodTracing();
mScrollProfilingStarted = false;
}
}
break;
}
case MotionEvent.ACTION_CANCEL: {
mTouchMode = TOUCH_MODE_REST;
setPressed(false);
View motionView = this.getChildAt(mMotionPosition - mFirstPosition);
if (motionView != null) {
motionView.setPressed(false);
}
clearScrollingCache();
final Handler handler = getHandler();
if (handler != null) {
handler.removeCallbacks(mPendingCheckForLongPress);
}
if (mVelocityTracker != null) {
mVelocityTracker.recycle();
mVelocityTracker = null;
}
}
}
return true;
}
|
diff --git a/org.orbisgis.geoview/src/main/java/org/orbisgis/geoview/MapControl.java b/org.orbisgis.geoview/src/main/java/org/orbisgis/geoview/MapControl.java
index 3d916a565..818065ec4 100644
--- a/org.orbisgis.geoview/src/main/java/org/orbisgis/geoview/MapControl.java
+++ b/org.orbisgis.geoview/src/main/java/org/orbisgis/geoview/MapControl.java
@@ -1,239 +1,241 @@
/*
* OrbisGIS is a GIS application dedicated to scientific spatial simulation.
* This cross-platform GIS is developed at french IRSTV institute and is able
* to manipulate and create vectorial and raster spatial information. OrbisGIS
* is distributed under GPL 3 license. It is produced by the geomatic team of
* the IRSTV Institute <http://www.irstv.cnrs.fr/>, CNRS FR 2488:
* Erwan BOCHER, scientific researcher,
* Thomas LEDUC, scientific researcher,
* Fernando GONZALEZ CORTES, computer engineer.
*
* Copyright (C) 2007 Erwan BOCHER, Fernando GONZALEZ CORTES, Thomas LEDUC
*
* This file is part of OrbisGIS.
*
* OrbisGIS 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.
*
* OrbisGIS 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 OrbisGIS. If not, see <http://www.gnu.org/licenses/>.
*
* For more information, please consult:
* <http://orbisgis.cerma.archi.fr/>
* <http://sourcesup.cru.fr/projects/orbisgis/>
* <http://listes.cru.fr/sympa/info/orbisgis-developers/>
* <http://listes.cru.fr/sympa/info/orbisgis-users/>
*
* or contact directly:
* erwan.bocher _at_ ec-nantes.fr
* fergonco _at_ gmail.com
* thomas.leduc _at_ cerma.archi.fr
*/
package org.orbisgis.geoview;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.ComponentEvent;
import java.awt.event.ComponentListener;
import java.awt.geom.AffineTransform;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import javax.swing.JComponent;
import org.orbisgis.tools.Automaton;
import org.orbisgis.tools.ToolManager;
import org.orbisgis.tools.TransitionException;
import org.orbisgis.tools.ViewContext;
import com.vividsolutions.jts.geom.Envelope;
/**
* MapControl.
*
* @author Fernando Gonzlez Corts
*/
public class MapControl extends JComponent implements ComponentListener {
/** Cuando la vista est actualizada. */
public static final int UPDATED = 0;
/** Cuando la vista est desactualizada. */
public static final int DIRTY = 1;
private MapControlModel mapControlModel = null;
private int status = DIRTY;
private ToolManager toolManager;
private Color backColor;
private BufferedImage inProcessImage;
private MapTransform mapTransform = new MapTransform();
/**
* Crea un nuevo NewMapControl.
*
* @param ec
*/
public MapControl() {
setDoubleBuffered(false);
setOpaque(true);
status = DIRTY;
// eventos
this.addComponentListener(this);
}
public void setMapControlModel(MapControlModel ms) {
this.mapControlModel = ms;
this.setExtent(ms.getMapArea());
this.drawMap();
}
public void drawFinished() {
mapTransform.setImage(inProcessImage);
this.repaint();
}
/**
* @see javax.swing.JComponent#paintComponent(java.awt.Graphics)
*/
protected void paintComponent(Graphics g) {
if (null != mapControlModel) {
if (status == UPDATED) {
// If not waiting for an image
if ((mapTransform.getImage() == inProcessImage)
|| (inProcessImage == null)) {
g.drawImage(mapTransform.getImage(), 0, 0, null);
toolManager.paintEdition(g);
}
} else if (status == DIRTY) {
inProcessImage = new BufferedImage(this.getWidth(), this
.getHeight(), BufferedImage.TYPE_INT_ARGB);
Graphics gImg = inProcessImage.createGraphics();
gImg.setColor(backColor);
gImg.fillRect(0, 0, getWidth(), getHeight());
status = UPDATED;
if (mapTransform.getAdjustedExtent() != null) {
mapControlModel.draw(inProcessImage);
}
+ // to avoid strange effects
+ g.drawImage(inProcessImage, 0, 0, null);
}
}
}
/**
* Returns the drawn image
*
* @return imagen.
*/
public BufferedImage getImage() {
return mapTransform.getImage();
}
/**
* Redraws the map accessing the model
*
* @param doClear
*/
public void drawMap() {
status = DIRTY;
repaint();
}
/**
* @see java.awt.event.ComponentListener#componentHidden(java.awt.event.ComponentEvent)
*/
public void componentHidden(ComponentEvent e) {
}
/**
* @see java.awt.event.ComponentListener#componentMoved(java.awt.event.ComponentEvent)
*/
public void componentMoved(ComponentEvent e) {
}
/**
* @see java.awt.event.ComponentListener#componentResized(java.awt.event.ComponentEvent)
*/
public void componentResized(ComponentEvent e) {
mapTransform.resizeImage(getWidth(), getHeight());
drawMap();
}
/**
* @see java.awt.event.ComponentListener#componentShown(java.awt.event.ComponentEvent)
*/
public void componentShown(ComponentEvent e) {
System.out.println("shown");
repaint();
}
public Color getBackColor() {
return backColor;
}
public void setBackColor(Color backColor) {
this.backColor = backColor;
}
public void setExtent(Rectangle2D newExtent) {
mapTransform.setExtent(newExtent);
drawMap();
}
public void setExtent(Envelope newExtent) {
if (newExtent != null) {
Rectangle2D.Double extent = new Rectangle2D.Double(newExtent
.getMinX(), newExtent.getMinY(), newExtent.getWidth(),
newExtent.getHeight());
mapTransform.setExtent(extent);
drawMap();
}
}
public Rectangle2D getAdjustedExtent() {
return mapTransform.getAdjustedExtent();
}
public AffineTransform getTrans() {
return mapTransform.getAffineTransform();
}
public void setTool(Automaton tool) throws TransitionException {
toolManager.setTool(tool);
}
public Envelope toPixel(final Envelope geographicEnvelope) {
return mapTransform.toPixel(geographicEnvelope);
}
public void setEditionContext(ViewContext ec) {
if (toolManager != null) {
this.removeMouseListener(toolManager);
this.removeMouseMotionListener(toolManager);
}
Automaton defaultTool = ec.getView().getDefaultTool();
toolManager = new ToolManager(defaultTool, ec);
try {
toolManager.setTool(defaultTool);
} catch (TransitionException e) {
throw new RuntimeException();
}
this.addMouseListener(toolManager);
this.addMouseMotionListener(toolManager);
}
public Rectangle2D getExtent() {
return mapTransform.getExtent();
}
}
| true | true | protected void paintComponent(Graphics g) {
if (null != mapControlModel) {
if (status == UPDATED) {
// If not waiting for an image
if ((mapTransform.getImage() == inProcessImage)
|| (inProcessImage == null)) {
g.drawImage(mapTransform.getImage(), 0, 0, null);
toolManager.paintEdition(g);
}
} else if (status == DIRTY) {
inProcessImage = new BufferedImage(this.getWidth(), this
.getHeight(), BufferedImage.TYPE_INT_ARGB);
Graphics gImg = inProcessImage.createGraphics();
gImg.setColor(backColor);
gImg.fillRect(0, 0, getWidth(), getHeight());
status = UPDATED;
if (mapTransform.getAdjustedExtent() != null) {
mapControlModel.draw(inProcessImage);
}
}
}
}
| protected void paintComponent(Graphics g) {
if (null != mapControlModel) {
if (status == UPDATED) {
// If not waiting for an image
if ((mapTransform.getImage() == inProcessImage)
|| (inProcessImage == null)) {
g.drawImage(mapTransform.getImage(), 0, 0, null);
toolManager.paintEdition(g);
}
} else if (status == DIRTY) {
inProcessImage = new BufferedImage(this.getWidth(), this
.getHeight(), BufferedImage.TYPE_INT_ARGB);
Graphics gImg = inProcessImage.createGraphics();
gImg.setColor(backColor);
gImg.fillRect(0, 0, getWidth(), getHeight());
status = UPDATED;
if (mapTransform.getAdjustedExtent() != null) {
mapControlModel.draw(inProcessImage);
}
// to avoid strange effects
g.drawImage(inProcessImage, 0, 0, null);
}
}
}
|
diff --git a/src/org/gridlab/gridsphere/portlet/PortletAdapter.java b/src/org/gridlab/gridsphere/portlet/PortletAdapter.java
index 9a2beeb65..456c8fdd7 100644
--- a/src/org/gridlab/gridsphere/portlet/PortletAdapter.java
+++ b/src/org/gridlab/gridsphere/portlet/PortletAdapter.java
@@ -1,368 +1,368 @@
/*
* @author <a href="mailto:[email protected]">Jason Novotny</a>
* @version $Id$
*/
package org.gridlab.gridsphere.portlet;
import org.gridlab.gridsphere.core.persistence.PersistenceManagerException;
import org.gridlab.gridsphere.portlet.impl.SportletProperties;
import org.gridlab.gridsphere.portletcontainer.PortletDataManager;
import org.gridlab.gridsphere.portletcontainer.impl.SportletDataManager;
import javax.servlet.UnavailableException;
import java.io.IOException;
import java.util.Hashtable;
import java.util.Map;
/**
* The <code>PortletAdapter</code> provides a default implementation for the
* <code>Portlet</code> interfaces as well as providing a default handler
* for the <code>PortletSessionListener</code> to allow <it>user portlet
* instances</it> to be created and removed via the {@link #login} and
* {@link #logout} methods.
*/
public abstract class PortletAdapter extends Portlet {
protected Hashtable storeVars = new Hashtable();
/* keep track of all PortletSettings per concrete portlet (concreteID, PortletSettings) */
private Map allPortletSettings = new Hashtable();
/* the datamanger injects PortletData into the request */
private transient PortletDataManager dataManager = null;
public PortletAdapter() {
}
/**
* Called by the portlet container to indicate to this portlet that it is put into service.
* <p/>
* The portlet container calls the init() method for the whole life-cycle of the portlet.
* The init() method must complete successfully before concrete portlets are created through
* the initConcrete() method.
* <p/>
* The portlet container cannot place the portlet into service if the init() method
* <p/>
* 1. throws UnavailableException
* 2. does not return within a time period defined by the portlet container.
*
* @param config the portlet configuration
* @throws UnavailableException if an exception has occurrred that interferes with the portlet's
* normal initialization
*/
public void init(PortletConfig config) throws UnavailableException {
this.portletConfig = config;
dataManager = SportletDataManager.getInstance();
}
/**
* Called by the portlet container to indicate to this portlet that it is taken out of service.
* This method is only called once all threads within the portlet's service() method have exited
* or after a timeout period has passed. After the portlet container calls this method,
* it will not call the service() method again on this portlet.
* <p/>
* This method gives the portlet an opportunity to clean up any resources that are
* being held (for example, memory, file handles, threads).
*
* @param config the portlet configuration
*/
public void destroy(PortletConfig config) {
this.portletConfig = null;
}
/**
* Called by the portlet container to indicate that the concrete portlet is put into service.
* The portlet container calls the initConcrete() method for the whole life-cycle of the portlet.
* The initConcrete() method must complete successfully before concrete portlet instances can be
* created through the login() method.
* <p/>
* The portlet container cannot place the portlet into service if the initConcrete() method
* <p/>
* 1. throws UnavailableException
* 2. does not return within a time period defined by the portlet container.
*
* @param settings the portlet settings
*/
public void initConcrete(PortletSettings settings) throws UnavailableException {
allPortletSettings.put(settings.getConcretePortletID(), settings);
}
/**
* Called by the portlet container to indicate that the concrete portlet is taken out of service.
* This method is only called once all threads within the portlet's service() method have exited
* or after a timeout period has passed. After the portlet container calls this method,
* it will not call the service() method again on this portlet.
* <p/>
* This method gives the portlet an opportunity to clean up any resources that are being
* held (for example, memory, file handles, threads).
*
* @param settings the portlet settings
*/
public void destroyConcrete(PortletSettings settings) {
allPortletSettings.remove(settings.getConcretePortletID());
}
/**
* Called by the portlet container to ask this portlet to generate its markup using the given
* request/response pair. Depending on the mode of the portlet and the requesting client device,
* the markup will be different. Also, the portlet can take language preferences and/or
* personalized settings into account.
*
* @param request the portlet request
* @param response the portlet response
* @throws PortletException if the portlet has trouble fulfilling the rendering request
* @throws IOException if the streaming causes an I/O problem
*/
public void service(PortletRequest request, PortletResponse response) throws PortletException, IOException {
// There must be a portlet ID to know which portlet to service
String portletID = (String) request.getAttribute(SportletProperties.PORTLETID);
if (portletID == null) {
// it may be in the request parameter
portletID = request.getParameter(SportletProperties.PORTLETID);
if (portletID == null) {
log.error("in PortletAdapter: No PortletID found in request attribute");
return;
}
}
PortletData data = null;
User user = request.getUser();
if (!(user instanceof GuestUser)) {
try {
data = dataManager.getPortletData(user, portletID);
request.setAttribute(SportletProperties.PORTLET_DATA, data);
} catch (PersistenceManagerException e) {
- log.error("in PortletAdapter: Unable to obtain PortletData for user");
+ log.error("in PortletAdapter: Unable to obtain PortletData for user", e);
}
}
portletSettings = (PortletSettings) allPortletSettings.get(portletID);
if (portletSettings != null) {
request.setAttribute(SportletProperties.PORTLET_SETTINGS, portletSettings);
}
user = request.getUser();
String method = (String) request.getAttribute(SportletProperties.PORTLET_ACTION_METHOD);
if (method != null) return;
Portlet.Mode mode = request.getMode();
if (mode == null) {
mode = Portlet.Mode.VIEW;
request.setMode(mode);
}
log.debug("in PortletAdapter: Displaying mode: " + mode + " for portlet: " + portletID);
try {
switch (mode.getMode()) {
case Portlet.Mode.VIEW_MODE:
doView(request, response);
break;
case Portlet.Mode.EDIT_MODE:
doEdit(request, response);
break;
case Portlet.Mode.CONFIGURE_MODE:
doConfigure(request, response);
break;
case Portlet.Mode.HELP_MODE:
doHelp(request, response);
break;
default:
log.error("Received invalid PortletMode command : " + mode);
throw new IllegalArgumentException("Received invalid PortletMode command: " + mode);
}
} catch (Exception e) {
log.error("in PortletAdapter: service()", e);
request.setAttribute(SportletProperties.PORTLETERROR + getPortletSettings().getConcretePortletID(), e);
throw new PortletException(e);
}
}
/**
* Called by the portlet container to ask the portlet to initialize a personalized user experience.
* In addition to initializing the session this method allows the portlet to initialize the
* concrete portlet instance, for example, to store attributes in the session.
*
* @param request the portlet request
*/
public void login(PortletRequest request) {
}
/**
* Called by the portlet container to indicate that a concrete portlet instance is being removed.
* This method gives the concrete portlet instance an opportunity to clean up any resources
* (for example, memory, file handles, threads), before it is removed.
* This happens if the user logs out, or decides to remove this portlet from a page.
*
* @param session the portlet session
*/
public void logout(PortletSession session) {
}
/**
* Returns the time the response of the PortletInfo object was last modified, in milliseconds since midnight
* January 1, 1970 GMT. If the time is unknown, this method returns a negative number (the default).
* <p/>
* Portlets that can quickly determine their last modification time should override this method.
* This makes browser and proxy caches work more effectively, reducing the load on server and network resources.
*
* @param request the portlet request
* @return long a long integer specifying the time the response of the PortletInfo
* object was last modified, in milliseconds since midnight, January 1, 1970 GMT, or -1 if the time is not known
*/
public long getLastModified(PortletRequest request) {
// XXX: FILL ME IN
return 0;
}
/**
* Returns the PortletConfig object of the portlet
*
* @return the PortletConfig object
*/
public PortletConfig getPortletConfig() {
return portletConfig;
}
/**
* Returns the portlet log
*
* @return the portlet log
*/
public PortletLog getPortletLog() {
return log;
}
/**
* Helper method to serve up the CONFIGURE mode.
*
* @param request the portlet request
* @param response the portlet response
* @throws PortletException if an error occurs during processing
* @throws IOException if an I/O error occurs
*/
public void doConfigure(PortletRequest request, PortletResponse response)
throws PortletException, IOException {
// default is doView
doView(request, response);
}
/**
* Helper method to serve up the EDIT mode.
*
* @param request the portlet request
* @param response the portlet response
* @throws PortletException if an error occurs during processing
* @throws IOException if an I/O error occurs
*/
public void doEdit(PortletRequest request, PortletResponse response)
throws PortletException, IOException {
// default is doView
doView(request, response);
}
/**
* Helper method to serve up the HELP mode.
*
* @param request the portlet request
* @param response the portlet response
* @throws PortletException if an error occurs during processing
* @throws IOException if an I/O error occurs
*/
public void doHelp(PortletRequest request, PortletResponse response)
throws PortletException, IOException {
// default doView
doView(request, response);
}
/**
* Helper method to serve up the VIEW mode.
*
* @param request the portlet request
* @param response the portlet response
* @throws PortletException if an error occurs during processing
* @throws IOException if an I/O error occurs
*/
public void doView(PortletRequest request, PortletResponse response)
throws PortletException, IOException {
throw new PortletException("doView method not implemented!");
}
/**
* Returns a transient variable of the concrete portlet.
*
* @param name the variable name
* @return the variable or null if it doesn't exist
* @throws AccessDeniedException if the method is called outside of a concrete portlet
*/
public Object getVariable(String name) throws AccessDeniedException {
return storeVars.get(name);
}
/**
* Removes a transient variable of the concrete portlet.
*
* @param name the variable name
*/
public void removeVariable(String name) {
if (storeVars.containsKey(name)) {
storeVars.remove(name);
}
}
/**
* Sets a transient variable of the concrete portlet.
*
* @param name the variable name
* @param value the variable value
*/
public void setVariable(String name, Object value) {
if ((name != null) && (value != null))
storeVars.put(name, value);
}
}
| true | true | public void service(PortletRequest request, PortletResponse response) throws PortletException, IOException {
// There must be a portlet ID to know which portlet to service
String portletID = (String) request.getAttribute(SportletProperties.PORTLETID);
if (portletID == null) {
// it may be in the request parameter
portletID = request.getParameter(SportletProperties.PORTLETID);
if (portletID == null) {
log.error("in PortletAdapter: No PortletID found in request attribute");
return;
}
}
PortletData data = null;
User user = request.getUser();
if (!(user instanceof GuestUser)) {
try {
data = dataManager.getPortletData(user, portletID);
request.setAttribute(SportletProperties.PORTLET_DATA, data);
} catch (PersistenceManagerException e) {
log.error("in PortletAdapter: Unable to obtain PortletData for user");
}
}
portletSettings = (PortletSettings) allPortletSettings.get(portletID);
if (portletSettings != null) {
request.setAttribute(SportletProperties.PORTLET_SETTINGS, portletSettings);
}
user = request.getUser();
String method = (String) request.getAttribute(SportletProperties.PORTLET_ACTION_METHOD);
if (method != null) return;
Portlet.Mode mode = request.getMode();
if (mode == null) {
mode = Portlet.Mode.VIEW;
request.setMode(mode);
}
log.debug("in PortletAdapter: Displaying mode: " + mode + " for portlet: " + portletID);
try {
switch (mode.getMode()) {
case Portlet.Mode.VIEW_MODE:
doView(request, response);
break;
case Portlet.Mode.EDIT_MODE:
doEdit(request, response);
break;
case Portlet.Mode.CONFIGURE_MODE:
doConfigure(request, response);
break;
case Portlet.Mode.HELP_MODE:
doHelp(request, response);
break;
default:
log.error("Received invalid PortletMode command : " + mode);
throw new IllegalArgumentException("Received invalid PortletMode command: " + mode);
}
} catch (Exception e) {
log.error("in PortletAdapter: service()", e);
request.setAttribute(SportletProperties.PORTLETERROR + getPortletSettings().getConcretePortletID(), e);
throw new PortletException(e);
}
}
| public void service(PortletRequest request, PortletResponse response) throws PortletException, IOException {
// There must be a portlet ID to know which portlet to service
String portletID = (String) request.getAttribute(SportletProperties.PORTLETID);
if (portletID == null) {
// it may be in the request parameter
portletID = request.getParameter(SportletProperties.PORTLETID);
if (portletID == null) {
log.error("in PortletAdapter: No PortletID found in request attribute");
return;
}
}
PortletData data = null;
User user = request.getUser();
if (!(user instanceof GuestUser)) {
try {
data = dataManager.getPortletData(user, portletID);
request.setAttribute(SportletProperties.PORTLET_DATA, data);
} catch (PersistenceManagerException e) {
log.error("in PortletAdapter: Unable to obtain PortletData for user", e);
}
}
portletSettings = (PortletSettings) allPortletSettings.get(portletID);
if (portletSettings != null) {
request.setAttribute(SportletProperties.PORTLET_SETTINGS, portletSettings);
}
user = request.getUser();
String method = (String) request.getAttribute(SportletProperties.PORTLET_ACTION_METHOD);
if (method != null) return;
Portlet.Mode mode = request.getMode();
if (mode == null) {
mode = Portlet.Mode.VIEW;
request.setMode(mode);
}
log.debug("in PortletAdapter: Displaying mode: " + mode + " for portlet: " + portletID);
try {
switch (mode.getMode()) {
case Portlet.Mode.VIEW_MODE:
doView(request, response);
break;
case Portlet.Mode.EDIT_MODE:
doEdit(request, response);
break;
case Portlet.Mode.CONFIGURE_MODE:
doConfigure(request, response);
break;
case Portlet.Mode.HELP_MODE:
doHelp(request, response);
break;
default:
log.error("Received invalid PortletMode command : " + mode);
throw new IllegalArgumentException("Received invalid PortletMode command: " + mode);
}
} catch (Exception e) {
log.error("in PortletAdapter: service()", e);
request.setAttribute(SportletProperties.PORTLETERROR + getPortletSettings().getConcretePortletID(), e);
throw new PortletException(e);
}
}
|
diff --git a/core-task-impl/src/main/java/org/cytoscape/task/internal/proxysettings/ProxySettingsTask2.java b/core-task-impl/src/main/java/org/cytoscape/task/internal/proxysettings/ProxySettingsTask2.java
index 1ac4439a8..c8ed9dcea 100644
--- a/core-task-impl/src/main/java/org/cytoscape/task/internal/proxysettings/ProxySettingsTask2.java
+++ b/core-task-impl/src/main/java/org/cytoscape/task/internal/proxysettings/ProxySettingsTask2.java
@@ -1,152 +1,153 @@
package org.cytoscape.task.internal.proxysettings;
import java.net.URL;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import org.cytoscape.io.util.StreamUtil;
import org.cytoscape.work.AbstractTask;
import org.cytoscape.work.TaskMonitor;
import org.cytoscape.work.Tunable;
import org.cytoscape.work.TunableValidator;
import org.cytoscape.work.util.ListSingleSelection;
/**
* Dialog for assigning proxy settings.
*/
public class ProxySettingsTask2 extends AbstractTask implements TunableValidator {
private static final List<String> KEYS = Arrays.asList("http.proxyHost", "http.proxyPort", "socks.proxyHost", "socks.proxyPort");
@Tunable(description="Type")
public ListSingleSelection<String> type = new ListSingleSelection<String>("direct", "http", "socks");
@Tunable(description="Proxy Server",groups={"param"},dependsOn="type!=direct",params="alignments=horizontal;displayState=hidden")
public String hostname="";
@Tunable(description="Port",groups={"param"},dependsOn="type!=direct",params="alignments=horizontal;displayState=hidden")
public int port=0;
private final StreamUtil streamUtil;
private final Map<String,String> oldSettings;
private final Properties properties;
public ProxySettingsTask2(final StreamUtil streamUtil) {
this.streamUtil = streamUtil;
oldSettings = new HashMap<String,String>();
properties = System.getProperties();
}
public ValidationState getValidationState(final Appendable errMsg) {
storeProxySettings();
- FutureTask<Exception> executor = new FutureTask<Exception>(new TestProxySettings(streamUtil));
+ FutureTask<Exception> task = new FutureTask<Exception>(new TestProxySettings(streamUtil));
Exception result = null;
try {
- result = executor.get(10, TimeUnit.SECONDS);
+ new Thread(task).start();
+ result = task.get(10, TimeUnit.SECONDS);
} catch (final InterruptedException e) {
result = e;
} catch (final ExecutionException e) {
result = e;
} catch (final TimeoutException e) {
result = e;
}
revertProxySettings();
if (result == null)
return ValidationState.OK;
try {
errMsg.append("Cytoscape was unable to connect to the internet because:\n\n" + result.getMessage());
} catch (final Exception e) {
/* Intentionally ignored! */
}
return ValidationState.INVALID;
}
public void run(TaskMonitor taskMonitor) {
taskMonitor.setProgress(0.0);
storeProxySettings();
oldSettings.clear();
taskMonitor.setProgress(1.0);
}
void storeProxySettings() {
oldSettings.clear();
for (String key : KEYS) {
if (properties.getProperty(key) != null)
oldSettings.put(key, properties.getProperty(key));
}
if (type.getSelectedValue().equals("direct")) {
for (String key : KEYS) {
if (properties.getProperty(key) != null)
properties.remove(key);
}
} else if (type.getSelectedValue().equals("http")) {
properties.remove("socks.proxyHost");
properties.remove("socks.proxyPort");
properties.setProperty("http.proxyHost", hostname);
properties.setProperty("http.proxyPort", Integer.toString(port));
} else if (type.getSelectedValue().equals("socks")) {
properties.remove("http.proxyHost");
properties.remove("http.proxyPort");
properties.setProperty("socks.proxyHost", hostname);
properties.setProperty("socks.proxyPort", Integer.toString(port));
}
}
void revertProxySettings() {
for (String key : KEYS) {
if (properties.getProperty(key) != null)
properties.remove(key);
if (oldSettings.containsKey(key))
properties.setProperty(key, oldSettings.get(key));
}
oldSettings.clear();
}
void dumpSettings(String title) {
System.out.println(title);
for (String key : KEYS)
System.out.println(String.format("%s: %s", key, properties.getProperty(key)));
}
}
final class TestProxySettings implements Callable<Exception> {
static final String TEST_URL = "http://www.google.com";
final StreamUtil streamUtil;
public TestProxySettings(final StreamUtil streamUtil) {
this.streamUtil = streamUtil;
}
public Exception call() {
try {
final URL url = new URL(TEST_URL);
streamUtil.getInputStream(url).close();
} catch (final Exception ex) {
return ex;
}
return null;
}
}
| false | true | public ValidationState getValidationState(final Appendable errMsg) {
storeProxySettings();
FutureTask<Exception> executor = new FutureTask<Exception>(new TestProxySettings(streamUtil));
Exception result = null;
try {
result = executor.get(10, TimeUnit.SECONDS);
} catch (final InterruptedException e) {
result = e;
} catch (final ExecutionException e) {
result = e;
} catch (final TimeoutException e) {
result = e;
}
revertProxySettings();
if (result == null)
return ValidationState.OK;
try {
errMsg.append("Cytoscape was unable to connect to the internet because:\n\n" + result.getMessage());
} catch (final Exception e) {
/* Intentionally ignored! */
}
return ValidationState.INVALID;
}
| public ValidationState getValidationState(final Appendable errMsg) {
storeProxySettings();
FutureTask<Exception> task = new FutureTask<Exception>(new TestProxySettings(streamUtil));
Exception result = null;
try {
new Thread(task).start();
result = task.get(10, TimeUnit.SECONDS);
} catch (final InterruptedException e) {
result = e;
} catch (final ExecutionException e) {
result = e;
} catch (final TimeoutException e) {
result = e;
}
revertProxySettings();
if (result == null)
return ValidationState.OK;
try {
errMsg.append("Cytoscape was unable to connect to the internet because:\n\n" + result.getMessage());
} catch (final Exception e) {
/* Intentionally ignored! */
}
return ValidationState.INVALID;
}
|
diff --git a/attributelib/src/main/java/com/github/thebiologist13/attributelib/Attribute.java b/attributelib/src/main/java/com/github/thebiologist13/attributelib/Attribute.java
index 543923f..66f9215 100644
--- a/attributelib/src/main/java/com/github/thebiologist13/attributelib/Attribute.java
+++ b/attributelib/src/main/java/com/github/thebiologist13/attributelib/Attribute.java
@@ -1,58 +1,58 @@
package com.github.thebiologist13.attributelib;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
public class Attribute implements Serializable {
private static final long serialVersionUID = 7131150007489438852L;
private VanillaAttribute attribute;
private double base;
private List<Modifier> modifiers = new ArrayList<Modifier>();
public Attribute(VanillaAttribute attribute) {
this.attribute = attribute;
this.base = attribute.getDefaultBase();
}
public void addModifier(Modifier modifier) {
modifiers.add(modifier);
}
public VanillaAttribute getAttribute() {
return attribute;
}
public double getBase() {
return base;
}
public List<Modifier> getModifiers() {
return modifiers;
}
public void removeModifier(Modifier modifier) {
modifiers.remove(modifier);
}
public void setAttribute(VanillaAttribute attribute) {
this.attribute = attribute;
}
public void setBase(double base) {
double min = attribute.getMinimum();
double max = attribute.getMaximum();
if(base < min)
base = min;
- else if(base > max)
+ else if(base > max && max != -1)
base = max;
this.base = base;
}
public void setModifiers(List<Modifier> modifiers) {
this.modifiers = modifiers;
}
}
| true | true | public void setBase(double base) {
double min = attribute.getMinimum();
double max = attribute.getMaximum();
if(base < min)
base = min;
else if(base > max)
base = max;
this.base = base;
}
| public void setBase(double base) {
double min = attribute.getMinimum();
double max = attribute.getMaximum();
if(base < min)
base = min;
else if(base > max && max != -1)
base = max;
this.base = base;
}
|
diff --git a/src/org/objectweb/proactive/core/body/BodyImpl.java b/src/org/objectweb/proactive/core/body/BodyImpl.java
index 6cda3ea75..abebcb85c 100644
--- a/src/org/objectweb/proactive/core/body/BodyImpl.java
+++ b/src/org/objectweb/proactive/core/body/BodyImpl.java
@@ -1,363 +1,364 @@
/*
* ################################################################
*
* ProActive: The Java(TM) library for Parallel, Distributed,
* Concurrent computing with Security and Mobility
*
* Copyright (C) 1997-2002 INRIA/University of Nice-Sophia Antipolis
* Contact: [email protected]
*
* 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 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
*
* Initial developer(s): The ProActive Team
* http://www.inria.fr/oasis/ProActive/contacts.html
* Contributor(s):
*
* ################################################################
*/
package org.objectweb.proactive.core.body;
import org.objectweb.proactive.core.ProActiveRuntimeException;
import org.objectweb.proactive.core.UniqueID;
import org.objectweb.proactive.core.body.future.Future;
import org.objectweb.proactive.core.body.future.FuturePool;
import org.objectweb.proactive.core.body.message.MessageEventProducerImpl;
import org.objectweb.proactive.core.body.reply.Reply;
import org.objectweb.proactive.core.body.reply.ReplyReceiver;
import org.objectweb.proactive.core.body.request.BlockingRequestQueue;
import org.objectweb.proactive.core.body.request.Request;
import org.objectweb.proactive.core.body.request.RequestFactory;
import org.objectweb.proactive.core.body.request.RequestQueue;
import org.objectweb.proactive.core.body.request.RequestReceiver;
import org.objectweb.proactive.core.body.request.ServeException;
import org.objectweb.proactive.core.event.MessageEvent;
import org.objectweb.proactive.core.event.MessageEventListener;
import org.objectweb.proactive.core.mop.MethodCall;
/**
* @author fhuet
*
*
*
*/
/**
* <i><font size="-1" color="#FF0000">**For internal use only** </font></i><br>
* <p>
* This class gives a common implementation of the Body interface. It provides all
* the non specific behavior allowing sub-class to write the detail implementation.
* </p><p>
* Each body is identify by an unique identifier.
* </p><p>
* All active bodies that get created in one JVM register themselves into a table that allows
* to tack them done. The registering and deregistering is done by the AbstractBody and
* the table is managed here as well using some static methods.
* </p><p>
* In order to let somebody customize the body of an active object without subclassing it,
* AbstractBody delegates lot of tasks to satellite objects that implements a given
* interface. Abstract protected methods instantiate those objects allowing subclasses
* to create them as they want (using customizable factories or instance).
* </p>
*
* @author ProActive Team
* @version 1.0, 2001/10/23
* @since ProActive 0.9
* @see org.objectweb.proactive.Body
* @see UniqueID
*
*/
public abstract class BodyImpl extends AbstractBody
implements java.io.Serializable {
//
// -- STATIC MEMBERS -----------------------------------------------
//
private static final String INACTIVE_BODY_EXCEPTION_MESSAGE =
"Cannot perform this call because this body is inactive";
//
// -- PROTECTED MEMBERS -----------------------------------------------
//
/** The component in charge of receiving reply */
protected ReplyReceiver replyReceiver;
/** The component in charge of receiving request */
protected RequestReceiver requestReceiver;
protected MessageEventProducerImpl messageEventProducer;
//
// -- CONSTRUCTORS -----------------------------------------------
//
/**
* Creates a new AbstractBody.
* Used for serialization.
*/
public BodyImpl() {
}
/**
* Creates a new AbstractBody for an active object attached to a given node.
* @param reifiedObject the active object that body is for
* @param nodeURL the URL of the node that body is attached to
* @param factory the factory able to construct new factories for each type of meta objects
* needed by this body
*/
public BodyImpl(Object reifiedObject, String nodeURL, MetaObjectFactory factory) {
super(reifiedObject, nodeURL, factory);
this.requestReceiver = factory.newRequestReceiverFactory().newRequestReceiver();
this.replyReceiver = factory.newReplyReceiverFactory().newReplyReceiver();
this.messageEventProducer = new MessageEventProducerImpl();
setLocalBodyImpl(
new ActiveLocalBodyStrategy(
reifiedObject,
factory.newRequestQueueFactory().newRequestQueue(bodyID),
factory.newRequestFactory()));
this.localBodyStrategy.getFuturePool().setOwnerBody(this.getID());
}
//
// -- PUBLIC METHODS -----------------------------------------------
//
//
// -- implements MessageEventProducer -----------------------------------------------
//
public void addMessageEventListener(MessageEventListener listener) {
if (messageEventProducer != null)
messageEventProducer.addMessageEventListener(listener);
}
public void removeMessageEventListener(MessageEventListener listener) {
if (messageEventProducer != null)
messageEventProducer.removeMessageEventListener(listener);
}
//
// -- PROTECTED METHODS -----------------------------------------------
//
/**
* Receives a request for later processing. The call to this method is non blocking
* unless the body cannot temporary receive the request.
* @param request the request to process
* @exception java.io.IOException if the request cannot be accepted
*/
protected void internalReceiveRequest(Request request) throws java.io.IOException {
if (messageEventProducer != null)
messageEventProducer.notifyListeners(request, MessageEvent.REQUEST_RECEIVED, bodyID,
getRequestQueue().size() + 1);
// request queue length = number of requests in queue
// + the one to add now
requestReceiver.receiveRequest(request, this);
}
/**
* Receives a reply in response to a former request.
* @param reply the reply received
* @exception java.io.IOException if the reply cannot be accepted
*/
protected void internalReceiveReply(Reply reply) throws java.io.IOException {
if (messageEventProducer != null)
messageEventProducer.notifyListeners(reply, MessageEvent.REPLY_RECEIVED, bodyID);
replyReceiver.receiveReply(reply, this, getFuturePool());
}
/**
* Signals that the activity of this body, managed by the active thread has just stopped.
*/
protected void activityStopped() {
super.activityStopped();
messageEventProducer = null;
setLocalBodyImpl(new InactiveLocalBodyStrategy());
}
public void setImmediateService(String methodName) throws java.io.IOException {
this.requestReceiver.setImmediateService(methodName);
}
//
// -- PRIVATE METHODS -----------------------------------------------
//
//
// -- inner classes -----------------------------------------------
//
private class ActiveLocalBodyStrategy implements LocalBodyStrategy, java.io.Serializable {
/** A pool future that contains the pending future objects */
protected FuturePool futures;
/** The reified object target of the request processed by this body */
protected Object reifiedObject;
protected BlockingRequestQueue requestQueue;
protected RequestFactory internalRequestFactory;
private long absoluteSequenceID;
//
// -- CONSTRUCTORS -----------------------------------------------
//
public ActiveLocalBodyStrategy(Object reifiedObject, BlockingRequestQueue requestQueue, RequestFactory requestFactory) {
this.reifiedObject = reifiedObject;
this.futures = new FuturePool();
this.requestQueue = requestQueue;
this.internalRequestFactory = requestFactory;
}
//
// -- PUBLIC METHODS -----------------------------------------------
//
//
// -- implements LocalBody -----------------------------------------------
//
public FuturePool getFuturePool() {
return futures;
}
public BlockingRequestQueue getRequestQueue() {
return requestQueue;
}
public Object getReifiedObject() {
return reifiedObject;
}
public String getName() {
return reifiedObject.getClass().getName();
}
/** Serves the request. The request should be removed from the request queue
* before serving, which is correctly done by all methods of the Service class.
* However, this condition is not ensured for custom calls on serve. */
public void serve(Request request) {
if (request == null)
return;
try {
messageEventProducer.notifyListeners(request, MessageEvent.SERVING_STARTED,
bodyID, getRequestQueue().size());
Reply reply = request.serve(BodyImpl.this);
if (reply == null) {
+ if(!isActive()) return;//test if active in case of terminate() method otherwise eventProducer would be null
messageEventProducer.notifyListeners(request, MessageEvent.VOID_REQUEST_SERVED,
bodyID, getRequestQueue().size());
return;
}
UniqueID destinationBodyId = request.getSourceBodyID();
if (destinationBodyId != null)
messageEventProducer.notifyListeners(reply, MessageEvent.REPLY_SENT, destinationBodyId,
getRequestQueue().size());
this.getFuturePool().registerDestination(request.getSender());
reply.send(request.getSender());
this.getFuturePool().removeDestination();
} catch (ServeException e) {
// handle error here
throw new ProActiveRuntimeException("Exception in serve (Still not handled) : throws killer RuntimeException", e);
} catch (java.io.IOException e) {
// handle error here
throw new ProActiveRuntimeException("Exception in sending reply (Still not handled) : throws killer RuntimeException", e);
}
}
public void sendRequest(MethodCall methodCall, Future future, UniversalBody destinationBody) throws java.io.IOException {
long sequenceID = getNextSequenceID();
Request request = internalRequestFactory.newRequest(methodCall, BodyImpl.this, future == null, sequenceID);
if (future != null) {
future.setID(sequenceID);
futures.receiveFuture(future);
}
messageEventProducer.notifyListeners(request, MessageEvent.REQUEST_SENT, destinationBody.getID());
request.send(destinationBody);
}
//
// -- PROTECTED METHODS -----------------------------------------------
//
/**
* Returns a unique identifier that can be used to tag a future, a request
* @return a unique identifier that can be used to tag a future, a request.
*/
private synchronized long getNextSequenceID() {
return ++absoluteSequenceID;
}
} // end inner class LocalBodyImpl
private class InactiveLocalBodyStrategy implements LocalBodyStrategy, java.io.Serializable {
//
// -- CONSTRUCTORS -----------------------------------------------
//
public InactiveLocalBodyStrategy() {
}
//
// -- PUBLIC METHODS -----------------------------------------------
//
//
// -- implements LocalBody -----------------------------------------------
//
public FuturePool getFuturePool() {
//throw new ProActiveRuntimeException(INACTIVE_BODY_EXCEPTION_MESSAGE);
return null;
}
public BlockingRequestQueue getRequestQueue() {
throw new ProActiveRuntimeException(INACTIVE_BODY_EXCEPTION_MESSAGE);
}
public RequestQueue getHighPriorityRequestQueue() {
throw new ProActiveRuntimeException(INACTIVE_BODY_EXCEPTION_MESSAGE);
}
public Object getReifiedObject() {
throw new ProActiveRuntimeException(INACTIVE_BODY_EXCEPTION_MESSAGE);
}
public String getName() {
return "inactive body";
}
public void serve(Request request) {
throw new ProActiveRuntimeException(INACTIVE_BODY_EXCEPTION_MESSAGE);
}
public void sendRequest(MethodCall methodCall, Future future, UniversalBody destinationBody) throws java.io.IOException {
throw new ProActiveRuntimeException(INACTIVE_BODY_EXCEPTION_MESSAGE);
}
} // end inner class LocalInactiveBody
}
| true | true | public void serve(Request request) {
if (request == null)
return;
try {
messageEventProducer.notifyListeners(request, MessageEvent.SERVING_STARTED,
bodyID, getRequestQueue().size());
Reply reply = request.serve(BodyImpl.this);
if (reply == null) {
messageEventProducer.notifyListeners(request, MessageEvent.VOID_REQUEST_SERVED,
bodyID, getRequestQueue().size());
return;
}
UniqueID destinationBodyId = request.getSourceBodyID();
if (destinationBodyId != null)
messageEventProducer.notifyListeners(reply, MessageEvent.REPLY_SENT, destinationBodyId,
getRequestQueue().size());
this.getFuturePool().registerDestination(request.getSender());
reply.send(request.getSender());
this.getFuturePool().removeDestination();
} catch (ServeException e) {
// handle error here
throw new ProActiveRuntimeException("Exception in serve (Still not handled) : throws killer RuntimeException", e);
} catch (java.io.IOException e) {
// handle error here
throw new ProActiveRuntimeException("Exception in sending reply (Still not handled) : throws killer RuntimeException", e);
}
}
| public void serve(Request request) {
if (request == null)
return;
try {
messageEventProducer.notifyListeners(request, MessageEvent.SERVING_STARTED,
bodyID, getRequestQueue().size());
Reply reply = request.serve(BodyImpl.this);
if (reply == null) {
if(!isActive()) return;//test if active in case of terminate() method otherwise eventProducer would be null
messageEventProducer.notifyListeners(request, MessageEvent.VOID_REQUEST_SERVED,
bodyID, getRequestQueue().size());
return;
}
UniqueID destinationBodyId = request.getSourceBodyID();
if (destinationBodyId != null)
messageEventProducer.notifyListeners(reply, MessageEvent.REPLY_SENT, destinationBodyId,
getRequestQueue().size());
this.getFuturePool().registerDestination(request.getSender());
reply.send(request.getSender());
this.getFuturePool().removeDestination();
} catch (ServeException e) {
// handle error here
throw new ProActiveRuntimeException("Exception in serve (Still not handled) : throws killer RuntimeException", e);
} catch (java.io.IOException e) {
// handle error here
throw new ProActiveRuntimeException("Exception in sending reply (Still not handled) : throws killer RuntimeException", e);
}
}
|
diff --git a/src/net/sf/freecol/client/control/PreGameController.java b/src/net/sf/freecol/client/control/PreGameController.java
index 694cf200e..db668f343 100644
--- a/src/net/sf/freecol/client/control/PreGameController.java
+++ b/src/net/sf/freecol/client/control/PreGameController.java
@@ -1,221 +1,223 @@
package net.sf.freecol.client.control;
import java.awt.Color;
import java.util.logging.Logger;
import net.sf.freecol.client.FreeColClient;
import net.sf.freecol.client.gui.Canvas;
import net.sf.freecol.client.gui.CanvasKeyListener;
import net.sf.freecol.client.gui.CanvasMouseListener;
import net.sf.freecol.client.gui.CanvasMouseMotionListener;
import net.sf.freecol.client.gui.GUI;
import net.sf.freecol.client.gui.InGameMenuBar;
import net.sf.freecol.client.gui.i18n.Messages;
import net.sf.freecol.common.model.GameOptions;
import net.sf.freecol.common.model.ModelMessage;
import net.sf.freecol.common.model.Player;
import net.sf.freecol.common.model.Tile;
import net.sf.freecol.common.model.Unit;
import net.sf.freecol.common.networking.Message;
import net.sf.freecol.server.generator.MapGeneratorOptions;
import org.w3c.dom.Element;
/**
* The controller that will be used before the game starts.
*/
public final class PreGameController {
@SuppressWarnings("unused")
private static final Logger logger = Logger.getLogger(PreGameController.class.getName());
public static final String COPYRIGHT = "Copyright (C) 2003-2005 The FreeCol Team";
public static final String LICENSE = "http://www.gnu.org/licenses/gpl.html";
public static final String REVISION = "$Revision$";
private FreeColClient freeColClient;
private MapGeneratorOptions mapGeneratorOptions = null;
/**
* The constructor to use.
* @param freeColClient The main controller.
*/
public PreGameController(FreeColClient freeColClient) {
this.freeColClient = freeColClient;
}
/**
* Sets the <code>MapGeneratorOptions</code> used when creating
* a map.
*
* @param mapGeneratorOptions The <code>MapGeneratorOptions</code>.
*/
void setMapGeneratorOptions(MapGeneratorOptions mapGeneratorOptions) {
this.mapGeneratorOptions = mapGeneratorOptions;
}
/**
* Gets the <code>MapGeneratorOptions</code> used when creating
* a map.
*
* @return The <code>MapGeneratorOptions</code>.
*/
public MapGeneratorOptions getMapGeneratorOptions() {
return mapGeneratorOptions;
}
/**
* Sets this client to be (or not be) ready to start the game.
* @param ready Indicates wether or not this client is ready
* to start the game.
*/
public void setReady(boolean ready) {
// Make the change:
freeColClient.getMyPlayer().setReady(ready);
// Inform the server:
Element readyElement = Message.createNewRootElement("ready");
readyElement.setAttribute("value", Boolean.toString(ready));
freeColClient.getClient().send(readyElement);
}
/**
* Sets this client's player's nation.
* @param nation Which nation this player wishes to set.
*/
public void setNation(int nation) {
// Make the change:
freeColClient.getMyPlayer().setNation(nation);
// Inform the server:
Element nationElement = Message.createNewRootElement("setNation");
nationElement.setAttribute("value", Integer.toString(nation));
freeColClient.getClient().sendAndWait(nationElement);
}
/**
* Sets this client's player's color.
* @param color Which color this player wishes to set.
*/
public void setColor(Color color) {
// Make the change:
freeColClient.getMyPlayer().setColor(color);
// Inform the server:
Element colorElement = Message.createNewRootElement("setColor");
colorElement.setAttribute("value", Player.convertColorToString(color));
freeColClient.getClient().sendAndWait(colorElement);
}
/**
* Requests the game to be started. This will only be successful
* if all players are ready to start the game.
*/
public void requestLaunch() {
Canvas canvas = freeColClient.getCanvas();
if (!freeColClient.getGame().isAllPlayersReadyToLaunch()) {
canvas.errorMessage("server.notAllReady");
return;
}
Element requestLaunchElement = Message.createNewRootElement("requestLaunch");
freeColClient.getClient().send(requestLaunchElement);
canvas.showStatusPanel( Messages.message("status.startingGame") );
}
/**
* Sends a chat message.
* @param message The message as plain text.
*/
public void chat(String message) {
Element chatElement = Message.createNewRootElement("chat");
chatElement.setAttribute("senderName", freeColClient.getMyPlayer().getName());
chatElement.setAttribute("message", message);
chatElement.setAttribute("privateChat", "false");
freeColClient.getClient().send(chatElement);
}
/**
* Sends the {@link GameOptions} to the server.
* This method should be called after updating that object.
*/
public void sendGameOptions() {
Element updateGameOptionsElement = Message.createNewRootElement("updateGameOptions");
updateGameOptionsElement.appendChild(freeColClient.getGame().getGameOptions().toXMLElement(updateGameOptionsElement.getOwnerDocument()));
freeColClient.getClient().send(updateGameOptionsElement);
}
/**
* Sends the {@link MapGeneratorOptions} to the server.
* This method should be called after updating that object.
*/
public void sendMapGeneratorOptions() {
if (mapGeneratorOptions != null) {
Element updateMapGeneratorOptionsElement = Message.createNewRootElement("updateMapGeneratorOptions");
updateMapGeneratorOptionsElement.appendChild(mapGeneratorOptions.toXMLElement(updateMapGeneratorOptionsElement.getOwnerDocument()));
freeColClient.getClient().send(updateMapGeneratorOptionsElement);
}
}
/**
* Starts the game.
*/
public void startGame() {
Canvas canvas = freeColClient.getCanvas();
GUI gui = freeColClient.getGUI();
canvas.closeMainPanel();
canvas.closeMenus();
InGameController inGameController = freeColClient.getInGameController();
InGameInputHandler inGameInputHandler = freeColClient.getInGameInputHandler();
freeColClient.getClient().setMessageHandler(inGameInputHandler);
gui.setInGame(true);
freeColClient.getCanvas().setJMenuBar(new InGameMenuBar(freeColClient));
- Player player = freeColClient.getMyPlayer();
- player.addModelMessage(new ModelMessage(player, "tutorial.startGame", null, ModelMessage.TUTORIAL, player));
+ if (freeColClient.getGame().getTurn().getNumber() == 1) {
+ Player player = freeColClient.getMyPlayer();
+ player.addModelMessage(new ModelMessage(player, "tutorial.startGame", null, ModelMessage.TUTORIAL, player));
+ }
Unit activeUnit = freeColClient.getMyPlayer().getNextActiveUnit();
//freeColClient.getMyPlayer().updateCrossesRequired();
gui.setActiveUnit(activeUnit);
if (activeUnit != null) {
gui.setFocus(activeUnit.getTile().getPosition());
} else {
gui.setFocus(((Tile) freeColClient.getMyPlayer().getEntryLocation()).getPosition());
}
canvas.addKeyListener(new CanvasKeyListener(canvas, inGameController));
canvas.addMouseListener(new CanvasMouseListener(canvas, gui));
canvas.addMouseMotionListener(new CanvasMouseMotionListener(canvas, gui, freeColClient.getGame().getMap()));
if (freeColClient.getMyPlayer().equals(freeColClient.getGame().getCurrentPlayer())) {
canvas.requestFocus();
freeColClient.getInGameController().nextModelMessage();
} else {
//canvas.setEnabled(false);
}
}
}
| true | true | public void startGame() {
Canvas canvas = freeColClient.getCanvas();
GUI gui = freeColClient.getGUI();
canvas.closeMainPanel();
canvas.closeMenus();
InGameController inGameController = freeColClient.getInGameController();
InGameInputHandler inGameInputHandler = freeColClient.getInGameInputHandler();
freeColClient.getClient().setMessageHandler(inGameInputHandler);
gui.setInGame(true);
freeColClient.getCanvas().setJMenuBar(new InGameMenuBar(freeColClient));
Player player = freeColClient.getMyPlayer();
player.addModelMessage(new ModelMessage(player, "tutorial.startGame", null, ModelMessage.TUTORIAL, player));
Unit activeUnit = freeColClient.getMyPlayer().getNextActiveUnit();
//freeColClient.getMyPlayer().updateCrossesRequired();
gui.setActiveUnit(activeUnit);
if (activeUnit != null) {
gui.setFocus(activeUnit.getTile().getPosition());
} else {
gui.setFocus(((Tile) freeColClient.getMyPlayer().getEntryLocation()).getPosition());
}
canvas.addKeyListener(new CanvasKeyListener(canvas, inGameController));
canvas.addMouseListener(new CanvasMouseListener(canvas, gui));
canvas.addMouseMotionListener(new CanvasMouseMotionListener(canvas, gui, freeColClient.getGame().getMap()));
if (freeColClient.getMyPlayer().equals(freeColClient.getGame().getCurrentPlayer())) {
canvas.requestFocus();
freeColClient.getInGameController().nextModelMessage();
} else {
//canvas.setEnabled(false);
}
}
| public void startGame() {
Canvas canvas = freeColClient.getCanvas();
GUI gui = freeColClient.getGUI();
canvas.closeMainPanel();
canvas.closeMenus();
InGameController inGameController = freeColClient.getInGameController();
InGameInputHandler inGameInputHandler = freeColClient.getInGameInputHandler();
freeColClient.getClient().setMessageHandler(inGameInputHandler);
gui.setInGame(true);
freeColClient.getCanvas().setJMenuBar(new InGameMenuBar(freeColClient));
if (freeColClient.getGame().getTurn().getNumber() == 1) {
Player player = freeColClient.getMyPlayer();
player.addModelMessage(new ModelMessage(player, "tutorial.startGame", null, ModelMessage.TUTORIAL, player));
}
Unit activeUnit = freeColClient.getMyPlayer().getNextActiveUnit();
//freeColClient.getMyPlayer().updateCrossesRequired();
gui.setActiveUnit(activeUnit);
if (activeUnit != null) {
gui.setFocus(activeUnit.getTile().getPosition());
} else {
gui.setFocus(((Tile) freeColClient.getMyPlayer().getEntryLocation()).getPosition());
}
canvas.addKeyListener(new CanvasKeyListener(canvas, inGameController));
canvas.addMouseListener(new CanvasMouseListener(canvas, gui));
canvas.addMouseMotionListener(new CanvasMouseMotionListener(canvas, gui, freeColClient.getGame().getMap()));
if (freeColClient.getMyPlayer().equals(freeColClient.getGame().getCurrentPlayer())) {
canvas.requestFocus();
freeColClient.getInGameController().nextModelMessage();
} else {
//canvas.setEnabled(false);
}
}
|
diff --git a/src/ribbonserver/AccessHandler.java b/src/ribbonserver/AccessHandler.java
index 93b6d90..7357f98 100644
--- a/src/ribbonserver/AccessHandler.java
+++ b/src/ribbonserver/AccessHandler.java
@@ -1,285 +1,285 @@
/**
* This file is part of RibbonServer application (check README).
* Copyright (C) 2012-2013 Stanislav Nepochatov
*
* 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 Street, Fifth Floor, Boston, MA 02110-1301, USA.
**/
package ribbonserver;
import java.util.Arrays;
/**
* Access control class and handler
* @author Stanislav Nepochatov
* @since RibbonServer a2
*/
public final class AccessHandler {
private static String LOG_ID = "ДОСТУП";
/**
* User storage list.
* @since RibbonServer a2
*/
private static java.util.ArrayList<UserClasses.UserEntry> userStore;
/**
* Group storage list.
* @since RibbonServer a2
*/
private static java.util.ArrayList<UserClasses.GroupEntry> groupStore;
/**
* Init this component;
* @since RibbonServer a2
*/
public static void init() {
AccessHandler.groupStore = IndexReader.readGroups();
AccessHandler.groupStore.add(new UserClasses.GroupEntry("{ADM},{Службова група адміністраторів системи \"Стрічка\"}"));
RibbonServer.logAppend(LOG_ID, 3, "індекс груп опрацьвано (" + groupStore.size() + ")");
AccessHandler.userStore = IndexReader.readUsers();
RibbonServer.logAppend(LOG_ID, 3, "індекс користувачів опрацьвано (" + userStore.size() + ")");
}
/**
* Check access to directory with specified mode;<br>
* <br>
* <b>Modes:</b><br>
* 0 - attempt to read directory;<br>
* 1 - attempt to release messege in directory;<br>
* 2 - attempt to admin directory;
* @param givenName user name which attempt to perform some action
* @param givenDir directory path
* @param givenMode mode of action (read, write or admin)
* @return result of access checking
* @since RibbonServer a2
*/
public static Boolean checkAccess(String givenName, String givenDir, Integer givenMode) {
java.util.ListIterator<UserClasses.UserEntry> userIter = AccessHandler.userStore.listIterator();
UserClasses.UserEntry findedUser = null;
while (userIter.hasNext()) {
UserClasses.UserEntry currUser = userIter.next();
if (currUser.USER_NAME.equals(givenName)) {
findedUser = currUser;
break;
}
}
String[] keyArray = Arrays.copyOf(findedUser.GROUPS, findedUser.GROUPS.length + 1);
keyArray[keyArray.length - 1] = findedUser.USER_NAME;
Boolean findedAnswer = false;
DirClasses.DirPermissionEntry fallbackPermission = null;
DirClasses.DirPermissionEntry[] dirAccessArray = Directories.getDirAccess(givenDir);
- if (dirAccessArray == null) {
+ if (dirAccessArray != null) {
for (Integer keyIndex = 0; keyIndex < keyArray.length; keyIndex++) {
for (Integer dirIndex = 0; dirIndex < dirAccessArray.length; dirIndex++) {
if (keyArray[keyIndex].equals("ADM") && !keyIndex.equals(keyArray.length - 1)) {
return true; //ADM is root-like group, all permission will be ignored
}
if (dirAccessArray[dirIndex].KEY.equals("ALL")) {
fallbackPermission = dirAccessArray[dirIndex];
continue;
}
if (dirAccessArray[dirIndex].KEY.equals(keyArray[keyIndex])) {
findedAnswer = dirAccessArray[dirIndex].checkByMode(givenMode);
if (findedAnswer == true) {
return findedAnswer;
}
}
}
}
} else {
for (Integer keyIndex = 0; keyIndex < keyArray.length; keyIndex++) {
if (keyArray[keyIndex].equals("ADM") && !keyIndex.equals(keyArray.length - 1)) {
if (keyArray[keyIndex].equals("ADM")) {
return true; //ADM is root-like group, all permission will be ignored
}
}
}
}
if (fallbackPermission == null) {
- fallbackPermission = new DirClasses.DirPermissionEntry("ALL:" + RibbonServer.ACCESS_ALL_MASK);
+ fallbackPermission = new DirClasses.DirPermissionEntry("GALL:" + RibbonServer.ACCESS_ALL_MASK);
}
if (findedAnswer == false) {
findedAnswer = fallbackPermission.checkByMode(givenMode);
}
return findedAnswer;
}
/**
* Check access to directories with specified mode;<br>
* <br>
* <b>Modes:</b><br>
* 0 - attempt to read directory;<br>
* 1 - attempt to release messege in directory;<br>
* 2 - attempt to admin directory;
* @param givenName user name which attempt to perform some action
* @param givenDirs array with directories which should be checked
* @return null if success or array index which checking failed
* @since RibbonServer a2
*/
public static Integer checkAccessForAll(String givenName, String[] givenDirs, Integer givenMode) {
for (Integer dirIndex = 0; dirIndex < givenDirs.length; dirIndex++) {
if (AccessHandler.checkAccess(givenName, givenDirs[dirIndex], givenMode) == false) {
return dirIndex;
}
}
return null;
}
/**
* Find out is user is member of specified group.
* @param givenName name to search
* @param givenGroup name of group
* @return result of checking
* @since RibbonServer a2
*/
public static Boolean isUserIsMemberOf(String givenName, String givenGroup) {
java.util.ListIterator<UserClasses.UserEntry> userIter = AccessHandler.userStore.listIterator();
UserClasses.UserEntry findedUser = null;
while (userIter.hasNext()) {
UserClasses.UserEntry currUser = userIter.next();
if (currUser.USER_NAME.equals(givenName)) {
findedUser = currUser;
break;
}
}
if (findedUser == null) {
return false;
}
for (String groupItem : findedUser.GROUPS) {
if (groupItem.equals("ADM")) {
return true;
}
}
return false;
}
/**
* Login user or return error.
* @param givenName name of user which is trying to login
* @param givenHash md5 hash of user's password
* @return null or error message
* @since RibbonServer a2
*/
public static String PROC_LOGIN_USER(String givenName, String givenHash) {
UserClasses.UserEntry findedUser = null;
java.util.ListIterator<UserClasses.UserEntry> usersIter = userStore.listIterator();
while (usersIter.hasNext()) {
UserClasses.UserEntry currUser = usersIter.next();
if (currUser.USER_NAME.equals(givenName)) {
findedUser = currUser;
break;
}
}
if (findedUser != null) {
if (findedUser.H_PASSWORD.equals(givenHash)) {
if (!findedUser.IS_ENABLED) {
return "Користувач " + givenName + " заблоковано!";
} else {
return null;
}
} else {
return "Невірний пароль!";
}
} else {
return "Користувача " + givenName + " не знайдено!";
}
}
/**
* Resume user or return error.
* @param givenEntry session entry of user which trying to resume;
* @return null or error message;
* @since RibbonServer a2
*/
public static String PROC_RESUME_USER(SessionManager.SessionEntry givenEntry) {
UserClasses.UserEntry findedUser = null;
java.util.ListIterator<UserClasses.UserEntry> usersIter = userStore.listIterator();
while (usersIter.hasNext()) {
UserClasses.UserEntry currUser = usersIter.next();
if (currUser.USER_NAME.equals(givenEntry.SESSION_USER_NAME)) {
findedUser = currUser;
break;
}
}
if (findedUser != null) {
if (!findedUser.IS_ENABLED) {
return "Користувач " + givenEntry.SESSION_USER_NAME + " заблоковано!";
} else {
givenEntry.useEntry();
return null;
}
} else {
return "Користувача " + givenEntry.SESSION_USER_NAME + " не знайдено!";
}
}
/**
* Return all users in short csv form to client or control application.
* @param includAdm include ADM members in final result;
* @return list with all users;
* @since RibbonServer a2
*/
public static String PROC_GET_USERS_UNI(Boolean includAdm) {
StringBuffer userBuf = new StringBuffer();
java.util.ListIterator<UserClasses.UserEntry> userIter = userStore.listIterator();
while (userIter.hasNext()) {
UserClasses.UserEntry currEntry = userIter.next();
userBuf.append("{");
userBuf.append(currEntry.USER_NAME);
userBuf.append("},{");
userBuf.append(currEntry.COMM);
userBuf.append("}\n");
}
userBuf.append("END:");
return userBuf.toString();
}
/**
* Find out if there is group with given name
* @param givenGroupName given name to search
* @return true if group existed/false if not
* @since RibbonServer a2
*/
public static Boolean isGroupExisted(String givenGroupName) {
java.util.ListIterator<UserClasses.GroupEntry> groupIter = groupStore.listIterator();
while (groupIter.hasNext()) {
if (groupIter.next().GROUP_NAME.equals(givenGroupName)) {
return true;
}
}
return false;
}
/**
* Find user entry by user name.
* @param givenName name to search;
* @return finded entry or null;
*/
public static UserClasses.UserEntry getEntryByName(String givenName) {
UserClasses.UserEntry result = null;
java.util.ListIterator<UserClasses.UserEntry> userIter = AccessHandler.userStore.listIterator();
while (userIter.hasNext()) {
UserClasses.UserEntry curr = userIter.next();
if (curr.USER_NAME.equals(givenName)) {
result = curr;
break;
}
}
return result;
}
}
| false | true | public static Boolean checkAccess(String givenName, String givenDir, Integer givenMode) {
java.util.ListIterator<UserClasses.UserEntry> userIter = AccessHandler.userStore.listIterator();
UserClasses.UserEntry findedUser = null;
while (userIter.hasNext()) {
UserClasses.UserEntry currUser = userIter.next();
if (currUser.USER_NAME.equals(givenName)) {
findedUser = currUser;
break;
}
}
String[] keyArray = Arrays.copyOf(findedUser.GROUPS, findedUser.GROUPS.length + 1);
keyArray[keyArray.length - 1] = findedUser.USER_NAME;
Boolean findedAnswer = false;
DirClasses.DirPermissionEntry fallbackPermission = null;
DirClasses.DirPermissionEntry[] dirAccessArray = Directories.getDirAccess(givenDir);
if (dirAccessArray == null) {
for (Integer keyIndex = 0; keyIndex < keyArray.length; keyIndex++) {
for (Integer dirIndex = 0; dirIndex < dirAccessArray.length; dirIndex++) {
if (keyArray[keyIndex].equals("ADM") && !keyIndex.equals(keyArray.length - 1)) {
return true; //ADM is root-like group, all permission will be ignored
}
if (dirAccessArray[dirIndex].KEY.equals("ALL")) {
fallbackPermission = dirAccessArray[dirIndex];
continue;
}
if (dirAccessArray[dirIndex].KEY.equals(keyArray[keyIndex])) {
findedAnswer = dirAccessArray[dirIndex].checkByMode(givenMode);
if (findedAnswer == true) {
return findedAnswer;
}
}
}
}
} else {
for (Integer keyIndex = 0; keyIndex < keyArray.length; keyIndex++) {
if (keyArray[keyIndex].equals("ADM") && !keyIndex.equals(keyArray.length - 1)) {
if (keyArray[keyIndex].equals("ADM")) {
return true; //ADM is root-like group, all permission will be ignored
}
}
}
}
if (fallbackPermission == null) {
fallbackPermission = new DirClasses.DirPermissionEntry("ALL:" + RibbonServer.ACCESS_ALL_MASK);
}
if (findedAnswer == false) {
findedAnswer = fallbackPermission.checkByMode(givenMode);
}
return findedAnswer;
}
| public static Boolean checkAccess(String givenName, String givenDir, Integer givenMode) {
java.util.ListIterator<UserClasses.UserEntry> userIter = AccessHandler.userStore.listIterator();
UserClasses.UserEntry findedUser = null;
while (userIter.hasNext()) {
UserClasses.UserEntry currUser = userIter.next();
if (currUser.USER_NAME.equals(givenName)) {
findedUser = currUser;
break;
}
}
String[] keyArray = Arrays.copyOf(findedUser.GROUPS, findedUser.GROUPS.length + 1);
keyArray[keyArray.length - 1] = findedUser.USER_NAME;
Boolean findedAnswer = false;
DirClasses.DirPermissionEntry fallbackPermission = null;
DirClasses.DirPermissionEntry[] dirAccessArray = Directories.getDirAccess(givenDir);
if (dirAccessArray != null) {
for (Integer keyIndex = 0; keyIndex < keyArray.length; keyIndex++) {
for (Integer dirIndex = 0; dirIndex < dirAccessArray.length; dirIndex++) {
if (keyArray[keyIndex].equals("ADM") && !keyIndex.equals(keyArray.length - 1)) {
return true; //ADM is root-like group, all permission will be ignored
}
if (dirAccessArray[dirIndex].KEY.equals("ALL")) {
fallbackPermission = dirAccessArray[dirIndex];
continue;
}
if (dirAccessArray[dirIndex].KEY.equals(keyArray[keyIndex])) {
findedAnswer = dirAccessArray[dirIndex].checkByMode(givenMode);
if (findedAnswer == true) {
return findedAnswer;
}
}
}
}
} else {
for (Integer keyIndex = 0; keyIndex < keyArray.length; keyIndex++) {
if (keyArray[keyIndex].equals("ADM") && !keyIndex.equals(keyArray.length - 1)) {
if (keyArray[keyIndex].equals("ADM")) {
return true; //ADM is root-like group, all permission will be ignored
}
}
}
}
if (fallbackPermission == null) {
fallbackPermission = new DirClasses.DirPermissionEntry("GALL:" + RibbonServer.ACCESS_ALL_MASK);
}
if (findedAnswer == false) {
findedAnswer = fallbackPermission.checkByMode(givenMode);
}
return findedAnswer;
}
|
diff --git a/maven-artifact/src/main/java/org/apache/maven/artifact/resolver/filter/ScopeArtifactFilter.java b/maven-artifact/src/main/java/org/apache/maven/artifact/resolver/filter/ScopeArtifactFilter.java
index eb9a7b47d..3214f0ef5 100644
--- a/maven-artifact/src/main/java/org/apache/maven/artifact/resolver/filter/ScopeArtifactFilter.java
+++ b/maven-artifact/src/main/java/org/apache/maven/artifact/resolver/filter/ScopeArtifactFilter.java
@@ -1,95 +1,95 @@
package org.apache.maven.artifact.resolver.filter;
import org.apache.maven.artifact.Artifact;
import org.apache.maven.artifact.DefaultArtifact;
/*
* Copyright 2001-2005 The Apache Software Foundation.
*
* 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.
*/
/**
* Filter to only retain objects in the given scope or better.
*
* @author <a href="mailto:[email protected]">Brett Porter</a>
* @version $Id$
*/
public class ScopeArtifactFilter
implements ArtifactFilter
{
private final boolean compileScope;
private final boolean runtimeScope;
private final boolean testScope;
private final boolean providedScope;
public ScopeArtifactFilter( String scope )
{
if ( DefaultArtifact.SCOPE_COMPILE.equals( scope ) )
{
providedScope = true;
compileScope = true;
runtimeScope = false;
testScope = false;
}
else if ( DefaultArtifact.SCOPE_RUNTIME.equals( scope ) )
{
providedScope = false;
compileScope = true;
runtimeScope = true;
testScope = false;
}
else if ( DefaultArtifact.SCOPE_TEST.equals( scope ) )
{
- providedScope = false;
+ providedScope = true;
compileScope = true;
runtimeScope = true;
testScope = true;
}
else
{
providedScope = false;
compileScope = false;
runtimeScope = false;
testScope = false;
}
}
public boolean include( Artifact artifact )
{
if ( DefaultArtifact.SCOPE_COMPILE.equals( artifact.getScope() ) )
{
return compileScope;
}
else if ( DefaultArtifact.SCOPE_RUNTIME.equals( artifact.getScope() ) )
{
return runtimeScope;
}
else if ( DefaultArtifact.SCOPE_TEST.equals( artifact.getScope() ) )
{
return testScope;
}
else if ( DefaultArtifact.SCOPE_PROVIDED.equals( artifact.getScope() ) )
{
return providedScope;
}
else
{
// TODO: should this be true? Does it even happen?
return false;
}
}
}
| true | true | public ScopeArtifactFilter( String scope )
{
if ( DefaultArtifact.SCOPE_COMPILE.equals( scope ) )
{
providedScope = true;
compileScope = true;
runtimeScope = false;
testScope = false;
}
else if ( DefaultArtifact.SCOPE_RUNTIME.equals( scope ) )
{
providedScope = false;
compileScope = true;
runtimeScope = true;
testScope = false;
}
else if ( DefaultArtifact.SCOPE_TEST.equals( scope ) )
{
providedScope = false;
compileScope = true;
runtimeScope = true;
testScope = true;
}
else
{
providedScope = false;
compileScope = false;
runtimeScope = false;
testScope = false;
}
}
| public ScopeArtifactFilter( String scope )
{
if ( DefaultArtifact.SCOPE_COMPILE.equals( scope ) )
{
providedScope = true;
compileScope = true;
runtimeScope = false;
testScope = false;
}
else if ( DefaultArtifact.SCOPE_RUNTIME.equals( scope ) )
{
providedScope = false;
compileScope = true;
runtimeScope = true;
testScope = false;
}
else if ( DefaultArtifact.SCOPE_TEST.equals( scope ) )
{
providedScope = true;
compileScope = true;
runtimeScope = true;
testScope = true;
}
else
{
providedScope = false;
compileScope = false;
runtimeScope = false;
testScope = false;
}
}
|
diff --git a/seam/plugins/org.jboss.tools.seam.core/src/org/jboss/tools/seam/internal/core/refactoring/ELProjectSet.java b/seam/plugins/org.jboss.tools.seam.core/src/org/jboss/tools/seam/internal/core/refactoring/ELProjectSet.java
index 2034385ad..b88689fcf 100644
--- a/seam/plugins/org.jboss.tools.seam.core/src/org/jboss/tools/seam/internal/core/refactoring/ELProjectSet.java
+++ b/seam/plugins/org.jboss.tools.seam.core/src/org/jboss/tools/seam/internal/core/refactoring/ELProjectSet.java
@@ -1,51 +1,51 @@
/*******************************************************************************
* Copyright (c) 2009 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.seam.internal.core.refactoring;
import org.eclipse.core.resources.IContainer;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.runtime.IPath;
import org.jboss.tools.common.model.project.ProjectHome;
import org.jboss.tools.jst.web.kb.refactoring.IProjectsSet;
import org.jboss.tools.seam.core.SeamProjectsSet;
public class ELProjectSet implements IProjectsSet {
SeamProjectsSet projectsSet;
IProject project;
public void init(IProject project){
projectsSet = new SeamProjectsSet(project);
this.project = project;
}
public IProject[] getLinkedProjects() {
IProject[] projects = projectsSet.getAllProjects();
if(projects.length == 0 || projects[0] == null){
return new IProject[]{project};
}
return projects;
}
public IContainer getViewFolder(IProject project){
if(project.equals(projectsSet.getWarProject()))
return projectsSet.getDefaultViewsFolder();
else if(project.equals(projectsSet.getEarProject()))
return projectsSet.getDefaultEarViewsFolder();
IPath path = ProjectHome.getFirstWebContentPath(project);
if(path != null)
- return project.getFolder(path.removeFirstSegments(1));
+ return path.segmentCount() > 1 ? project.getFolder(path.removeFirstSegments(1)) : project;
return null;
}
}
| true | true | public IContainer getViewFolder(IProject project){
if(project.equals(projectsSet.getWarProject()))
return projectsSet.getDefaultViewsFolder();
else if(project.equals(projectsSet.getEarProject()))
return projectsSet.getDefaultEarViewsFolder();
IPath path = ProjectHome.getFirstWebContentPath(project);
if(path != null)
return project.getFolder(path.removeFirstSegments(1));
return null;
}
| public IContainer getViewFolder(IProject project){
if(project.equals(projectsSet.getWarProject()))
return projectsSet.getDefaultViewsFolder();
else if(project.equals(projectsSet.getEarProject()))
return projectsSet.getDefaultEarViewsFolder();
IPath path = ProjectHome.getFirstWebContentPath(project);
if(path != null)
return path.segmentCount() > 1 ? project.getFolder(path.removeFirstSegments(1)) : project;
return null;
}
|
diff --git a/tests/org.jboss.tools.ui.bot.ext/src/org/jboss/tools/ui/bot/ext/helper/ContentAssistHelper.java b/tests/org.jboss.tools.ui.bot.ext/src/org/jboss/tools/ui/bot/ext/helper/ContentAssistHelper.java
index 40e82e327..c7de6f9aa 100644
--- a/tests/org.jboss.tools.ui.bot.ext/src/org/jboss/tools/ui/bot/ext/helper/ContentAssistHelper.java
+++ b/tests/org.jboss.tools.ui.bot.ext/src/org/jboss/tools/ui/bot/ext/helper/ContentAssistHelper.java
@@ -1,170 +1,171 @@
/*******************************************************************************
* Copyright (c) 2007-2012 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
*
* Contributor:
* Red Hat, Inc. - initial API and implementation
******************************************************************************/
package org.jboss.tools.ui.bot.ext.helper;
import static org.junit.Assert.assertTrue;
import java.util.List;
import org.apache.log4j.Logger;
import org.eclipse.swtbot.eclipse.finder.widgets.SWTBotEditor;
import org.jboss.tools.ui.bot.ext.FormatUtils;
import org.jboss.tools.ui.bot.ext.SWTBotExt;
import org.jboss.tools.ui.bot.ext.SWTJBTExt;
import org.jboss.tools.ui.bot.ext.SWTTestExt;
import org.jboss.tools.ui.bot.ext.Timing;
import org.jboss.tools.ui.bot.ext.parts.ContentAssistBot;
import org.jboss.tools.ui.bot.ext.parts.SWTBotEditorExt;
/**
* Helper for Content Assist functionality testing
* @author Vladimir Pakan
*
*/
public class ContentAssistHelper {
protected static final Logger log = Logger.getLogger(ContentAssistHelper.class);
/**
* Checks Content Assist content on specified position within editor with editorTitle
* and checks if expectedProposalList is equal to current Proposal List
* @param editorTitle
* @param textToSelect
* @param selectionOffset
* @param selectionLength
* @param textToSelectIndex
* @param expectedProposalList
*/
public static SWTBotEditor checkContentAssistContent(SWTBotExt bot,
String editorTitle, String textToSelect, int selectionOffset,
int selectionLength, int textToSelectIndex, List<String> expectedProposalList) {
return checkContentAssistContent(bot, editorTitle, textToSelect, selectionOffset,
selectionLength, textToSelectIndex, expectedProposalList, true);
}
/**
* Checks Content Assist content on specified position within editor with editorTitle
* and checks if expectedProposalList is equal to current Proposal List
* @param editorTitle
* @param textToSelect
* @param selectionOffset
* @param selectionLength
* @param textToSelectIndex
* @param expectedProposalList
* @param mustEquals
*/
public static SWTBotEditor checkContentAssistContent(SWTBotExt bot,
String editorTitle, String textToSelect, int selectionOffset,
int selectionLength, int textToSelectIndex, List<String> expectedProposalList,
boolean mustEquals) {
SWTJBTExt.selectTextInSourcePane(bot,
editorTitle, textToSelect, selectionOffset, selectionLength,
textToSelectIndex);
bot.sleep(Timing.time1S());
SWTBotEditorExt editor = SWTTestExt.bot.swtBotEditorExtByTitle(editorTitle);
ContentAssistBot contentAssist = editor.contentAssist();
List<String> currentProposalList = contentAssist.getProposalList();
assertTrue("Code Assist menu has incorrect menu items.\n" +
"Expected Proposal Menu Labels vs. Current Proposal Menu Labels :\n" +
FormatUtils.getListsDiffFormatted(expectedProposalList,currentProposalList),
mustEquals?expectedProposalList.equals(currentProposalList):
currentProposalList.containsAll(expectedProposalList));
return editor;
}
/**
* Checks Content Assist content on specified position within editor with editorTitle
* and checks if expectedProposalList is equal to current Proposal List
* @param editorTitle
* @param textToSelect
* @param selectionOffset
* @param selectionLength
* @param textToSelectIndex
* @param expectedProposalList
*/
public static SWTBotEditor checkContentAssistContent(SWTBotExt bot,
String editorTitle, String textToSelect, int selectionOffset,
int selectionLength, List<String> expectedProposalList) {
return checkContentAssistContent(bot, editorTitle, textToSelect,
selectionOffset, selectionLength, expectedProposalList, true);
}
/**
* Checks Content Assist content on specified position within editor with editorTitle
* and checks if expectedProposalList is equal to current Proposal List
* @param editorTitle
* @param textToSelect
* @param selectionOffset
* @param selectionLength
* @param textToSelectIndex
* @param expectedProposalList
* @param mustEquals
*/
public static SWTBotEditor checkContentAssistContent(SWTBotExt bot,
String editorTitle, String textToSelect, int selectionOffset,
int selectionLength, List<String> expectedProposalList, boolean mustEquals) {
return ContentAssistHelper.checkContentAssistContent(bot,
editorTitle,
textToSelect,
selectionOffset,
selectionLength,
0,
expectedProposalList,
mustEquals);
}
/**
* Checks Content Assist auto proposal. It's case when there is only one
* content assist item and that item is automatically inserted into editor
* and checks if expectedProposalList is equal to current Proposal List
* @param editorTitle
* @param textToSelect
* @param selectionOffset
* @param selectionLength
* @param textToSelectIndex
* @param expectedInsertedText
*/
public static SWTBotEditor checkContentAssistAutoProposal(SWTBotExt bot,
String editorTitle, String textToSelect, int selectionOffset,
int selectionLength, int textToSelectIndex, String expectedInsertedText) {
SWTJBTExt.selectTextInSourcePane(bot,
editorTitle, textToSelect, selectionOffset, selectionLength,
textToSelectIndex);
bot.sleep(Timing.time1S());
SWTBotEditorExt editor = SWTTestExt.bot.swtBotEditorExtByTitle(editorTitle);
String editorLineBeforeInsert = editor.getTextOnCurrentLine();
int xPos = editor.cursorPosition().column;
String expectedEditorLineAfterInsert = editorLineBeforeInsert.substring(0,xPos) +
expectedInsertedText +
editorLineBeforeInsert.substring(xPos);
ContentAssistBot contentAssist = editor.contentAssist();
contentAssist.invokeContentAssist();
String editorLineAfterInsert = editor.getTextOnCurrentLine();
- assertTrue("Text on current line should be:\n" +
- "but is :\n" + editorLineAfterInsert
+ assertTrue("Text on current line should be:\n" +
+ expectedEditorLineAfterInsert +
+ "\nbut is:\n" + editorLineAfterInsert
, editorLineAfterInsert.equals(expectedEditorLineAfterInsert));
return editor;
}
}
| true | true | public static SWTBotEditor checkContentAssistAutoProposal(SWTBotExt bot,
String editorTitle, String textToSelect, int selectionOffset,
int selectionLength, int textToSelectIndex, String expectedInsertedText) {
SWTJBTExt.selectTextInSourcePane(bot,
editorTitle, textToSelect, selectionOffset, selectionLength,
textToSelectIndex);
bot.sleep(Timing.time1S());
SWTBotEditorExt editor = SWTTestExt.bot.swtBotEditorExtByTitle(editorTitle);
String editorLineBeforeInsert = editor.getTextOnCurrentLine();
int xPos = editor.cursorPosition().column;
String expectedEditorLineAfterInsert = editorLineBeforeInsert.substring(0,xPos) +
expectedInsertedText +
editorLineBeforeInsert.substring(xPos);
ContentAssistBot contentAssist = editor.contentAssist();
contentAssist.invokeContentAssist();
String editorLineAfterInsert = editor.getTextOnCurrentLine();
assertTrue("Text on current line should be:\n" +
"but is :\n" + editorLineAfterInsert
, editorLineAfterInsert.equals(expectedEditorLineAfterInsert));
return editor;
}
| public static SWTBotEditor checkContentAssistAutoProposal(SWTBotExt bot,
String editorTitle, String textToSelect, int selectionOffset,
int selectionLength, int textToSelectIndex, String expectedInsertedText) {
SWTJBTExt.selectTextInSourcePane(bot,
editorTitle, textToSelect, selectionOffset, selectionLength,
textToSelectIndex);
bot.sleep(Timing.time1S());
SWTBotEditorExt editor = SWTTestExt.bot.swtBotEditorExtByTitle(editorTitle);
String editorLineBeforeInsert = editor.getTextOnCurrentLine();
int xPos = editor.cursorPosition().column;
String expectedEditorLineAfterInsert = editorLineBeforeInsert.substring(0,xPos) +
expectedInsertedText +
editorLineBeforeInsert.substring(xPos);
ContentAssistBot contentAssist = editor.contentAssist();
contentAssist.invokeContentAssist();
String editorLineAfterInsert = editor.getTextOnCurrentLine();
assertTrue("Text on current line should be:\n" +
expectedEditorLineAfterInsert +
"\nbut is:\n" + editorLineAfterInsert
, editorLineAfterInsert.equals(expectedEditorLineAfterInsert));
return editor;
}
|
diff --git a/enunciate/modules/spring-app/src/java/org/codehaus/enunciate/modules/spring_app/SpringAppDeploymentModule.java b/enunciate/modules/spring-app/src/java/org/codehaus/enunciate/modules/spring_app/SpringAppDeploymentModule.java
index f3a1479a..2b355c31 100644
--- a/enunciate/modules/spring-app/src/java/org/codehaus/enunciate/modules/spring_app/SpringAppDeploymentModule.java
+++ b/enunciate/modules/spring-app/src/java/org/codehaus/enunciate/modules/spring_app/SpringAppDeploymentModule.java
@@ -1,1018 +1,1017 @@
/*
* Copyright 2006 Web Cohesion
*
* 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.enunciate.modules.spring_app;
import com.sun.org.apache.xalan.internal.xsltc.trax.TransformerFactoryImpl;
import freemarker.template.TemplateException;
import org.apache.commons.digester.RuleSet;
import org.codehaus.enunciate.EnunciateException;
import org.codehaus.enunciate.apt.EnunciateFreemarkerModel;
import org.codehaus.enunciate.contract.validation.Validator;
import org.codehaus.enunciate.main.Artifact;
import org.codehaus.enunciate.main.Enunciate;
import org.codehaus.enunciate.main.FileArtifact;
import org.codehaus.enunciate.modules.DeploymentModule;
import org.codehaus.enunciate.modules.FreemarkerDeploymentModule;
import org.codehaus.enunciate.modules.spring_app.config.*;
import org.springframework.util.AntPathMatcher;
import sun.misc.Service;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import java.io.*;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.*;
import java.util.jar.Manifest;
/**
* <h1>Spring App Module</h1>
*
* <p>The spring app deployment module produces the web app for hosting the API endpoints and documentation.</p>
*
* <p>The order of the spring app deployment module is 200, putting it after any of the other modules, including
* the documentation deployment module. The spring app deployment module maintains soft dependencies on the other
* Enunciate modules. If those modules are active, the spring app deployment modules will assemble their artifacts
* into a <a href="http://www.springframework.org/">spring</a>-supported web application.</p>
*
* <ul>
* <li><a href="#steps">steps</a></li>
* <li><a href="#config">configuration</a></li>
* <li><a href="#artifacts">artifacts</a></li>
* </ul>
*
* <h1><a name="steps">Steps</a></h1>
*
* <h3>generate</h3>
*
* <p>The "generate" step generates the deployment descriptors, and the <a href="http://www.springframework.org/">Spring</a>
* configuration file. Refer to <a href="#config">configuration</a> to learn how to customize the deployment
* descriptors and the spring config file.</p>
*
* <h3>compile</h3>
*
* <p>The "compile" step compiles all API source files, including the source files that were generated from other modules
* (e.g. JAX-WS module and XFire module).</p>
*
* <h3>build</h3>
*
* <p>The "build" step assembles all the generated artifacts, compiled classes, and deployment descriptors into an (expanded)
* war directory.</p>
*
* <p>All classes compiled in the compile step are copied to the WEB-INF/classes directory.</p>
*
* <p>A set of libraries are copied to the WEB-INF/lib directory. This set of libraries can be specified in the
* <a href="#config">configuration file</a>. Unless specified otherwise in the configuration file, the
* libraries copied will be filtered from the classpath specified to Enunciate at compile-time. The filtered libraries
* are those libraries that are determined to be specific to running the Enunciate compile-time engine. All other
* libraries on the classpath are assumed to be dependencies for the API and are therefore copied to WEB-INF/lib.
* (If a directory is found on the classpath, its contents are copied to WEB-INF/classes.)</p>
*
* <p>The web.xml file is copied to the WEB-INF directory. A tranformation can be applied to the web.xml file before the copy,
* if specified in the config, allowing you to apply your own servlet filters, etc. <i>Take care to preserve the existing elements
* when applying a transformation to the web.xml file, as losing data will result in missing or malfunctioning endpoints.</i></p>
*
* <p>The spring-servlet.xml file is generated and copied to the WEB-INF directory. You can specify other spring config files that
* will be copied (and imported by the spring-servlet.xml file) in the configuration. This option allows you to specify spring AOP
* interceptors and XFire in/out handlers to wrap your endpoints, if desired.</p>
*
* <p>Finally, the documentation (if found) is copied to the base of the web app directory.</p>
*
* <h3>package</h3>
*
* <p>The "package" step packages the expanded war and exports it.</p>
*
* <h1><a name="config">Configuration</a></h1>
*
* <p>The configuration for the Spring App deployment module is specified by the "spring-app" child element under the "modules" element
* of the enunciate configuration file.</p>
*
* <h3>Structure</h3>
*
* <p>The following example shows the structure of the configuration elements for this module. Note that this shows only the structure.
* Some configuration elements don't make sense when used together.</p>
*
* <code class="console">
* <enunciate>
* <modules>
* <spring-app compileDebugInfo="[true | false]"
* contextLoaderListenerClass="..."
* dispatcherServletClass="..."
* defaultDependencyCheck="[none | objects | simple | all]"
* defaultAutowire="[no | byName | byType | constructor | autodetect]">
* <war name="..." webXMLTransform="..." webXMLTransformURL="..."
* preBase="..." postBase="..."
* includeClasspathLibs="[true|false]" excludeDefaultLibs="[true|false]"
* docsDir="..." gwtAppDir="...">
* <includeLibs pattern="..." file="..."/>
* <includeLibs pattern="..." file="..."/>
* ...
*
* <excludeLibs pattern="..." file="..."/>
* <excludeLibs pattern="..." file="..."/>
* ...
*
* <manifest/>
* <attribute name="..." value="..."/>
* <attribute section="..." name="..." value="..."/>
* ...
* </manifest/>
* </war>
*
* <springImport file="..." uri="..."/>
* <springImport file="..." uri="..."/>
* ...
*
* <globalServiceInterceptor interceptorClass="..." beanName="..."/>
* <globalServiceInterceptor interceptorClass="..." beanName="..."/>
* ...
*
* <handlerInterceptor interceptorClass="..." beanName="..."/>
* <handlerInterceptor interceptorClass="..." beanName="..."/>
* ...
*
* <copyResources dir="..." pattern="..."/>
* <copyResources dir="..." pattern="..."/>
* ...
* </spring-app>
* </modules>
* </enunciate>
* </code>
*
* <h3>attributes</h3>
*
* <ul>
* <li>The "<b>compileDebugInfo</b>" attribute specifies that the compiled classes should be compiled with debug info. The default is "true."</li>
* <li>The "<b>dispatcherServletClass</b>" attribute specifies that FQN of the class to use as the Spring dispatcher servlet. The default is "org.springframework.web.servlet.DispatcherServlet".</li>
* <li>The "<b>contextLoaderListenerClass</b>" attribute specifies that FQN of the class to use as the Spring context loader listener. The default is "org.springframework.web.context.ContextLoaderListener".</li>
* <li>The "<b>defaultDependencyCheck</b>" attribute specifies that value of the "default-dependency-check" for the generated spring file.</li>
* <li>The "<b>defaultAutowire</b>" attribute specifies that value of the "default-autowire" for the generated spring file.</li>
* </ul>
*
* <h3>The "war" element</h3>
*
* <p>The "war" element is used to specify configuration for the assembly of the war. It supports the following attributes:</p>
*
* <ul>
* <li>The "<b>name</b>" attribute specifies the name of the war. The default is the enunciate configuration label.</li>
* <li>The "<b>docsDir</b>" attribute specifies a different directory in the war for the documentation (including WSDL and schemas). The default is the
* root directory of the war.</li>
* <li>The "<b>gwtAppDir</b>" attribute specifies a different directory in the war for the GWT appliction(s). The default is the
* root directory of the war.</li>
* <li>The "<b>webXMLTransform</b>" attribute specifies the XSLT tranform file that the web.xml file will pass through before being copied to the WEB-INF
* directory. No tranformation will be applied if none is specified.</li>
* <li>The "<b>webXMLTransformURL</b>" attribute specifies the URL to an XSLT tranform that the web.xml file will pass through before being copied to the WEB-INF
* directory. No tranformation will be applied if none is specified.</li>
* <li>The "<b>preBase</b>" attribute specifies a directory (could be gzipped) that supplies a "base" for the war. The directory contents will be copied to
* the building war directory <i>before</i> it is provided with any Enunciate-specific files and directories.</li>
* <li>The "<b>postBase</b>" attribute specifies a directory (could be gzipped) that supplies a "base" for the war. The directory contents will be copied to
* the building war directory <i>after</i> it is provided with any Enunciate-specific files and directories.</li>
* <li>The "<b>includeClasspathLibs</b>" attribute specifies whether Enunciate will use the libraries from the classpath for applying the include/exclude
* filters. If "false" only the libs explicitly included by file (see below) will be filtered.</li>
* <li>The "<b>excludeDefaultLibs</b>" attribute specifies whether Enunciate should perform its default filtering of known compile-time-only jars.</li>
* </ul>
*
* <p>By default, the war is constructed by copying jars that are on the classpath to its "lib" directory (the contents of <i>directories</i> on the classpath
* will be copied to the "classes" directory). You add a specific file to this list with the "file" attribute of the "includeLibs" element of the "war" element.</p>
*
* <p>Once the initial list of jars to be potentially copied is created, it is passed through an "include" filter that you may specify with nested "includeLibs"
* elements. For each of these elements, you can specify a set of files to include with the "pattern" attribute. This is an
* ant-style pattern matcher against the absolute path of the file (or directory). By default, all files are included.
*
* <p>Once the initial list is passed through the "include" filter, it will be passed through an "exclude" filter. There is a set of known jars that by default
* will not be copied to the "lib" directory. These include the jars that ship by default with the JDK and the jars that are known to be build-time-only jars
* for Enunciate. You can disable the default filter with the "excludeDefaultLibs" attribute of the "war" element. You can also specify additional jars that
* are to be excluded with an arbitrary number of "excludeLibs" child elements under the "war" element in the configuration file. The "excludeLibs" element
* supports either a "pattern" attribute or a "file" attribute. The "pattern" attribute is an ant-style pattern matcher against the absolute path of the
* file (or directory) on the classpath that should not be copied to the destination war. The "file" attribute refers to a specific file on the filesystem.
* Furthermore, the "excludeLibs" element supports a "includeInManifest" attribute specifying whether the exclude should be listed in the "Class-Path"
* attribute of the manifest, even though they are excluded in the war. The is useful if, for example, you're assembling an "ear" with multiple war files.
* By default, excluded jars are not included in the manifest.</p>
*
* <p>You can customize the manifest for the war by the "manifest" element of the "war" element. Underneath the "manifest" element can be an arbitrary number
* of "attribute" elements that can be used to specify the manifest attributes. Each "attribute" element supports a "name" attribute, a "value" attribute, and
* a "section" attribute. If no section is specified, the default section is assumed. If there is no "Class-Path" attribute in the main section, one will be
* provided listing the jars on the classpath.</p>
*
* <h3>The "springImport" element</h3>
*
* <p>The "springImport" element is used to specify a spring configuration file that will be imported by the main
* spring servlet config. It supports the following attributes:</p>
*
* <ul>
* <li>The "file" attribute specifies the spring import file on the filesystem. It will be copied to the WEB-INF directory.</li>
* <li>The "uri" attribute specifies the URI to the spring import file. The URI will not be resolved at compile-time, nor will anything be copied to the
* WEB-INF directory. The value of this attribute will be used to reference the spring import file in the main config file. This attribute is useful
* to specify an import file on the classpath, e.g. "classpath:com/myco/spring/config.xml".</li>
* </ul>
*
* <p>One use of specifying spring a import file is to wrap your endpoints with spring interceptors and/or XFire in/out/fault handlers. This can be done
* by simply declaring a bean that is an instance of your endpoint class. This bean can be advised as needed, and if it implements
* org.codehaus.xfire.handler.HandlerSupport (perhaps <a href="http://static.springframework.org/spring/docs/1.2.x/reference/aop.html#d0e4128">through the use
* of a mixin</a>?), the in/out/fault handlers will be used for the XFire invocation of that endpoint.</p>
*
* <p>It's important to note that the type on which the bean context will be searched is the type of the endpoint <i>interface</i>, and then only if it exists.
* If there are more than one beans that are assignable to the endpoint interface, the bean that is named the name of the service will be used. Otherwise,
* the deployment of your endpoint will fail.</p>
*
* <p>The same procedure can be used to specify the beans to use as REST endpoints, although the XFire in/out/fault handlers will be ignored. In this case,
* the bean context will be searched for each <i>REST interface</i> that the endpoint implements. If there is a bean that implements that interface, it will
* used instead of the default implementation. If there is more than one, the bean that is named the same as the REST endpoint will be used.</p>
*
* <p>There also exists a mechanism to add certain AOP interceptors to all service endpoint beans. Such interceptors are referred to as "global service
* interceptors." This can be done by using the "globalServiceInterceptor" element (see below), or by simply creating an interceptor that implements
* org.codehaus.enunciate.modules.spring_app.EnunciateServiceAdvice or org.codehaus.enunciate.modules.spring_app.EnunciateServiceAdvisor and declaring it in your
* imported spring beans file.</p>
*
* <p>Each global interceptor has an order. The default order is 0 (zero). If a global service interceptor implements org.springframework.core.Ordered, the
* order will be respected. As global service interceptors are added, it will be assigned a position in the chain according to it's order. Interceptors
* of the same order will be ordered together according to their position in the config file, with priority to those declared by the "globalServiceInterceptor"
* element, then to instances of org.codehaus.enunciate.modules.spring_app.EnunciateServiceAdvice, then to instances of
* org.codehaus.enunciate.modules.spring_app.EnunciateServiceAdvisor.</p>
*
* <p>For more information on spring bean configuration and interceptor advice, see
* <a href="http://static.springframework.org/spring/docs/1.2.x/reference/index.html">the spring reference documentation</a>.</p>
*
* <h3>The "globalServiceInterceptor" element</h3>
*
* <p>The "globalServiceInterceptor" element is used to specify a Spring interceptor (instance of org.aopalliance.aop.Advice or
* org.springframework.aop.Advisor) that is to be injected on all service endpoint beans.</p>
*
* <ul>
* <li>The "interceptorClass" attribute specified the class of the interceptor.</p>
* <li>The "beanName" attribute specifies the bean name of the interceptor.</p>
* </ul>
*
* <h3>The "handlerInterceptor" element</h3>
*
* <p>The "handlerInterceptor" element is used to specify a Spring interceptor (instance of org.springframework.web.servlet.HandlerInterceptor)
* that is to be injected on the handler mapping.</p>
*
* <ul>
* <li>The "interceptorClass" attribute specifies the class of the interceptor.</p>
* <li>The "beanName" attribute specifies the bean name of the interceptor.</p>
* </ul>
*
* <p>For more information on spring bean configuration and interceptor advice, see
* <a href="http://static.springframework.org/spring/docs/1.2.x/reference/index.html">the spring reference documentation</a>.</p>
*
* <h3>The "copyResources" element</h3>
*
* <p>The "copyResources" element is used to specify a pattern of resources to copy to the compile directory. It supports the following attributes:</p>
*
* <ul>
* <li>The "<b>dir</b>" attribute specifies the base directory of the resources to copy.</li>
* <li>The "<b>pattern</b>" attribute specifies an <a href="http://ant.apache.org/">Ant</a>-style
* pattern used to find the resources to copy. For more information, see the documentation for the
* <a href="http://static.springframework.org/spring/docs/1.2.x/api/org/springframework/util/AntPathMatcher.html">ant path matcher</a> in the Spring
* JavaDocs.</li>
* </ul>
*
* <h1><a name="artifacts">Artifacts</a></h1>
*
* <p>The spring app deployment module exports the following artifacts:</p>
*
* <ul>
* <li>The "spring.app.dir" artifact is the (expanded) web app directory, exported during the build step.</li>
* <li>The "spring.war.file" artifact is the packaged war, exported during the package step.</li>
* </ul>
*
* @author Ryan Heaton
*/
public class SpringAppDeploymentModule extends FreemarkerDeploymentModule {
private WarConfig warConfig;
private final List<SpringImport> springImports = new ArrayList<SpringImport>();
private final List<CopyResources> copyResources = new ArrayList<CopyResources>();
private final List<GlobalServiceInterceptor> globalServiceInterceptors = new ArrayList<GlobalServiceInterceptor>();
private final List<HandlerInterceptor> handlerInterceptors = new ArrayList<HandlerInterceptor>();
private boolean compileDebugInfo = true;
private String defaultAutowire = null;
private String defaultDependencyCheck = null;
private String contextLoaderListenerClass = "org.springframework.web.context.ContextLoaderListener";
private String dispatcherServletClass = "org.springframework.web.servlet.DispatcherServlet";
/**
* @return "spring-app"
*/
@Override
public String getName() {
return "spring-app";
}
/**
* @return The URL to "spring-servlet.fmt"
*/
protected URL getSpringServletTemplateURL() {
return SpringAppDeploymentModule.class.getResource("spring-servlet.fmt");
}
/**
* @return The URL to "spring-servlet.fmt"
*/
protected URL getApplicationContextTemplateURL() {
return SpringAppDeploymentModule.class.getResource("applicationContext.xml.fmt");
}
/**
* @return The URL to "web.xml.fmt"
*/
protected URL getWebXmlTemplateURL() {
return SpringAppDeploymentModule.class.getResource("web.xml.fmt");
}
@Override
public void doFreemarkerGenerate() throws IOException, TemplateException {
EnunciateFreemarkerModel model = getModel();
//generate the spring-servlet.xml
model.setFileOutputDirectory(getConfigGenerateDir());
model.put("springImports", getSpringImportURIs());
model.put("defaultDependencyCheck", getDefaultDependencyCheck());
model.put("defaultAutowire", getDefaultAutowire());
model.put("springContextLoaderListenerClass", getContextLoaderListenerClass());
model.put("springDispatcherServletClass", getDispatcherServletClass());
if (!globalServiceInterceptors.isEmpty()) {
for (GlobalServiceInterceptor interceptor : this.globalServiceInterceptors) {
if ((interceptor.getBeanName() == null) && (interceptor.getInterceptorClass() == null)) {
throw new IllegalStateException("A global interceptor must have either a bean name or a class set.");
}
}
model.put("globalServiceInterceptors", this.globalServiceInterceptors);
}
if (!handlerInterceptors.isEmpty()) {
for (HandlerInterceptor interceptor : this.handlerInterceptors) {
if ((interceptor.getBeanName() == null) && (interceptor.getInterceptorClass() == null)) {
throw new IllegalStateException("A handler interceptor must have either a bean name or a class set.");
}
}
model.put("handlerInterceptors", this.handlerInterceptors);
}
model.put("xfireEnabled", getEnunciate().isModuleEnabled("xfire"));
model.put("restEnabled", getEnunciate().isModuleEnabled("rest"));
model.put("gwtEnabled", getEnunciate().isModuleEnabled("gwt"));
String docsDir = "";
if ((this.warConfig != null) && (this.warConfig.getDocsDir() != null)) {
docsDir = this.warConfig.getDocsDir().trim();
if ((!"".equals(docsDir)) && (!docsDir.endsWith("/"))) {
docsDir = docsDir + "/";
}
}
model.put("docsDir", docsDir);
processTemplate(getApplicationContextTemplateURL(), model);
processTemplate(getSpringServletTemplateURL(), model);
processTemplate(getWebXmlTemplateURL(), model);
}
@Override
protected void doCompile() throws EnunciateException, IOException {
ArrayList<String> javacAdditionalArgs = new ArrayList<String>();
if (compileDebugInfo) {
javacAdditionalArgs.add("-g");
}
Enunciate enunciate = getEnunciate();
File compileDir = getCompileDir();
enunciate.invokeJavac(enunciate.getEnunciateClasspath(), compileDir, javacAdditionalArgs, enunciate.getSourceFiles());
File jaxwsSources = (File) enunciate.getProperty("jaxws.src.dir");
if (jaxwsSources != null) {
info("Compiling the JAX-WS support classes found in %s...", jaxwsSources);
Collection<String> jaxwsSourceFiles = new ArrayList<String>(enunciate.getJavaFiles(jaxwsSources));
File xfireSources = (File) enunciate.getProperty("xfire-server.src.dir");
if (xfireSources != null) {
//make sure we include all the wrappers generated for the rpc methods, too...
jaxwsSourceFiles.addAll(enunciate.getJavaFiles(xfireSources));
}
if (!jaxwsSourceFiles.isEmpty()) {
StringBuilder jaxwsClasspath = new StringBuilder(enunciate.getEnunciateClasspath());
jaxwsClasspath.append(File.pathSeparator).append(compileDir.getAbsolutePath());
enunciate.invokeJavac(jaxwsClasspath.toString(), compileDir, javacAdditionalArgs, jaxwsSourceFiles.toArray(new String[jaxwsSourceFiles.size()]));
}
else {
info("No JAX-WS source files have been found to compile.");
}
}
else {
info("No JAX-WS source directory has been found. SOAP services disabled.");
}
File gwtSources = (File) enunciate.getProperty("gwt.server.src.dir");
if (gwtSources != null) {
info("Copying the GWT client classes to %s...", compileDir);
File gwtClientCompileDir = (File) enunciate.getProperty("gwt.client.compile.dir");
if (gwtClientCompileDir == null) {
throw new EnunciateException("Required dependency on the GWT client classes not found.");
}
enunciate.copyDir(gwtClientCompileDir, compileDir);
info("Compiling the GWT support classes found in %s...", gwtSources);
Collection<String> gwtSourceFiles = new ArrayList<String>(enunciate.getJavaFiles(gwtSources));
StringBuilder gwtClasspath = new StringBuilder(enunciate.getEnunciateClasspath());
gwtClasspath.append(File.pathSeparator).append(compileDir.getAbsolutePath());
enunciate.invokeJavac(gwtClasspath.toString(), compileDir, javacAdditionalArgs, gwtSourceFiles.toArray(new String[gwtSourceFiles.size()]));
}
if (!this.copyResources.isEmpty()) {
AntPathMatcher matcher = new AntPathMatcher();
for (CopyResources copyResource : this.copyResources) {
String pattern = copyResource.getPattern();
if (pattern == null) {
throw new EnunciateException("A pattern must be specified for copying resources.");
}
if (!matcher.isPattern(pattern)) {
warn("'%s' is not a valid pattern. Resources NOT copied!", pattern);
continue;
}
File basedir;
if (copyResource.getDir() == null) {
File configFile = enunciate.getConfigFile();
if (configFile != null) {
basedir = configFile.getAbsoluteFile().getParentFile();
}
else {
basedir = new File(System.getProperty("user.dir"));
}
}
else {
basedir = enunciate.resolvePath(copyResource.getDir());
}
for (String file : enunciate.getFiles(basedir, new PatternFileFilter(basedir, pattern, matcher))) {
enunciate.copyFile(new File(file), basedir, compileDir);
}
}
}
}
@Override
protected void doBuild() throws IOException, EnunciateException {
Enunciate enunciate = getEnunciate();
File buildDir = getBuildDir();
if ((this.warConfig != null) && (this.warConfig.getPreBase() != null)) {
File preBase = enunciate.resolvePath(this.warConfig.getPreBase());
if (preBase.isDirectory()) {
info("Copying preBase directory %s to %s...", preBase, buildDir);
enunciate.copyDir(preBase, buildDir);
}
else {
info("Extracting preBase zip file %s to %s...", preBase, buildDir);
enunciate.extractBase(new FileInputStream(preBase), buildDir);
}
}
info("Building the expanded WAR in %s", buildDir);
File webinf = new File(buildDir, "WEB-INF");
File webinfClasses = new File(webinf, "classes");
File webinfLib = new File(webinf, "lib");
//copy the compiled classes to WEB-INF/classes.
enunciate.copyDir(getCompileDir(), webinfClasses);
//prime the list of libs to include in the war with what's on the enunciate classpath.
List<String> warLibs = new ArrayList<String>();
if (this.warConfig == null || this.warConfig.isIncludeClasspathLibs()) {
warLibs.addAll(Arrays.asList(enunciate.getEnunciateClasspath().split(File.pathSeparator)));
}
List<IncludeExcludeLibs> includePatterns = this.warConfig != null ? new ArrayList<IncludeExcludeLibs>(this.warConfig.getIncludeLibs()) : new ArrayList<IncludeExcludeLibs>();
List<IncludeExcludeLibs> includedFiles = new ArrayList<IncludeExcludeLibs>();
Iterator<IncludeExcludeLibs> includeLibsIt = includePatterns.iterator();
while (includeLibsIt.hasNext()) {
IncludeExcludeLibs el = includeLibsIt.next();
if (el.getFile() != null) {
includedFiles.add(el);
}
if (el.getPattern() == null) {
includeLibsIt.remove();
}
}
List<IncludeExcludeLibs> excludeLibs = this.warConfig != null ? new ArrayList<IncludeExcludeLibs>(this.warConfig.getExcludeLibs()) : new ArrayList<IncludeExcludeLibs>();
AntPathMatcher pathMatcher = new AntPathMatcher();
List<File> includedLibs = new ArrayList<File>();
// Now get the files that are to be explicitly included.
// If none are explicitly included, include all of them.
- INCLUDE_LOOP:
for (String warLib : warLibs) {
File libFile = new File(warLib);
if (libFile.exists()) {
if (includePatterns.isEmpty()) {
includedLibs.add(libFile);
}
else {
for (IncludeExcludeLibs includeJar : includePatterns) {
String pattern = includeJar.getPattern();
String absolutePath = libFile.getAbsolutePath();
if (absolutePath.startsWith(File.separator)) {
//lob off the beginning "/" for Linux boxes.
absolutePath = absolutePath.substring(1);
}
if ((pattern != null) && (pathMatcher.isPattern(pattern) && (pathMatcher.match(pattern, absolutePath)))) {
includedLibs.add(libFile);
- break INCLUDE_LOOP;
+ break;
}
}
}
}
}
//if there are any excludes, filter them out here.
boolean excludeDefaults = this.warConfig == null || this.warConfig.isExcludeDefaultLibs();
List<String> manifestClasspath = new ArrayList<String>();
Iterator<File> includeLibIt = includedLibs.iterator();
INCLUDE_LOOP:
while (includeLibIt.hasNext()) {
File includedLib = includeLibIt.next();
if (excludeDefaults && knownExclude(includedLib)) {
includeLibIt.remove();
}
else {
for (IncludeExcludeLibs excludeJar : excludeLibs) {
String pattern = excludeJar.getPattern();
String absolutePath = includedLib.getAbsolutePath();
if (absolutePath.startsWith(File.separator)) {
//lob off the beginning "/" for Linux boxes.
absolutePath = absolutePath.substring(1);
}
boolean exclude = ((excludeJar.getFile() != null) && (excludeJar.getFile().equals(includedLib))) ||
((pattern != null) && (pathMatcher.isPattern(pattern)) && (pathMatcher.match(pattern, absolutePath)));
if (exclude) {
includeLibIt.remove();
if ((excludeJar.isIncludeInManifest()) && (!includedLib.isDirectory())) {
//include it in the manifest anyway.
manifestClasspath.add(includedLib.getName());
}
continue INCLUDE_LOOP;
}
}
}
}
//now add the lib files that are explicitly included.
Iterator<IncludeExcludeLibs> includeIt = includedFiles.iterator();
while (includeIt.hasNext()) {
IncludeExcludeLibs includeJar = includeIt.next();
if (includeJar.getFile() != null) {
warLibs.add(includeJar.getFile().getAbsolutePath());
includeIt.remove();
}
}
for (File includedLib : includedLibs) {
if (includedLib.isDirectory()) {
info("Adding the contents of %s to WEB-INF/classes.", includedLib);
enunciate.copyDir(includedLib, webinfClasses);
}
else {
info("Including %s in WEB-INF/lib.", includedLib);
enunciate.copyFile(includedLib, includedLib.getParentFile(), webinfLib);
}
}
// write the manifest file.
Manifest manifest = this.warConfig == null ? WarConfig.getDefaultManifest() : this.warConfig.getManifest();
if ((manifestClasspath.size() > 0) && (manifest.getMainAttributes().getValue("Class-Path") == null)) {
StringBuilder manifestClasspathValue = new StringBuilder();
Iterator<String> manifestClasspathIt = manifestClasspath.iterator();
while (manifestClasspathIt.hasNext()) {
String entry = manifestClasspathIt.next();
manifestClasspathValue.append(entry);
if (manifestClasspathIt.hasNext()) {
manifestClasspathValue.append(" ");
}
}
manifest.getMainAttributes().putValue("Class-Path", manifestClasspathValue.toString());
}
File metaInf = new File(buildDir, "META-INF");
metaInf.mkdirs();
FileOutputStream manifestFileOut = new FileOutputStream(new File(metaInf, "MANIFEST.MF"));
manifest.write(manifestFileOut);
manifestFileOut.flush();
manifestFileOut.close();
//todo: assert that the necessary jars (spring, xfire, commons-whatever, etc.) are there?
//put the web.xml in WEB-INF. Pass it through a stylesheet, if specified.
File xfireConfigDir = getConfigGenerateDir();
File webXML = new File(xfireConfigDir, "web.xml");
File destWebXML = new File(webinf, "web.xml");
if ((this.warConfig != null) && (this.warConfig.getWebXMLTransformURL() != null)) {
URL transformURL = this.warConfig.getWebXMLTransformURL();
info("web.xml transform has been specified as %s.", transformURL);
try {
StreamSource source = new StreamSource(transformURL.openStream());
Transformer transformer = new TransformerFactoryImpl().newTransformer(source);
info("Transforming %s to %s.", webXML, destWebXML);
transformer.transform(new StreamSource(new FileReader(webXML)), new StreamResult(destWebXML));
}
catch (TransformerException e) {
throw new EnunciateException("Error during transformation of the web.xml (stylesheet " + transformURL + ", file " + webXML + ")", e);
}
}
else {
enunciate.copyFile(webXML, destWebXML);
}
//copy the spring application context and servlet config from the build dir to the WEB-INF directory.
enunciate.copyFile(new File(xfireConfigDir, "applicationContext.xml"), new File(webinf, "applicationContext.xml"));
enunciate.copyFile(new File(xfireConfigDir, "spring-servlet.xml"), new File(webinf, "spring-servlet.xml"));
for (SpringImport springImport : springImports) {
//copy the extra spring import files to the WEB-INF directory to be imported.
if (springImport.getFile() != null) {
File importFile = enunciate.resolvePath(springImport.getFile());
enunciate.copyFile(importFile, new File(webinf, importFile.getName()));
}
}
//now try to find the documentation and export it to the build directory...
Artifact artifact = enunciate.findArtifact("docs");
if (artifact != null) {
File docsDir = buildDir;
if ((this.warConfig != null) && (this.warConfig.getDocsDir() != null)) {
docsDir = new File(buildDir, this.warConfig.getDocsDir());
docsDir.mkdirs();
}
artifact.exportTo(docsDir, enunciate);
}
else {
warn("WARNING: No documentation artifact found!");
}
File gwtAppDir = (File) enunciate.getProperty("gwt.app.dir");
if (gwtAppDir != null) {
File gwtAppDest = buildDir;
if ((this.warConfig != null) && (this.warConfig.getGwtAppDir() != null)) {
gwtAppDest = new File(buildDir, this.warConfig.getDocsDir());
}
enunciate.copyDir(gwtAppDir, gwtAppDest);
}
else {
info("No GWT application directory was found. Skipping the copy...");
}
//extract a post base if specified.
if ((this.warConfig != null) && (this.warConfig.getPostBase() != null)) {
File postBase = enunciate.resolvePath(this.warConfig.getPostBase());
if (postBase.isDirectory()) {
info("Copying postBase directory %s to %s...", postBase, buildDir);
enunciate.copyDir(postBase, buildDir);
}
else {
info("Extracting postBase zip file %s to %s...", postBase, buildDir);
enunciate.extractBase(new FileInputStream(postBase), buildDir);
}
}
//export the expanded application directory.
enunciate.addArtifact(new FileArtifact(getName(), "spring.app.dir", buildDir));
}
@Override
protected void doPackage() throws EnunciateException, IOException {
File buildDir = getBuildDir();
File warFile = getWarFile();
if (!warFile.getParentFile().exists()) {
warFile.getParentFile().mkdirs();
}
Enunciate enunciate = getEnunciate();
info("Creating %s", warFile.getAbsolutePath());
enunciate.zip(warFile, buildDir);
enunciate.addArtifact(new FileArtifact(getName(), "spring.war.file", warFile));
}
/**
* The configuration for the war.
*
* @return The configuration for the war.
*/
public WarConfig getWarConfig() {
return warConfig;
}
/**
* The war file to create.
*
* @return The war file to create.
*/
public File getWarFile() {
String filename = "enunciate.war";
if (getEnunciate().getConfig().getLabel() != null) {
filename = getEnunciate().getConfig().getLabel() + ".war";
}
if ((this.warConfig != null) && (this.warConfig.getName() != null)) {
filename = this.warConfig.getName();
}
return new File(getPackageDir(), filename);
}
/**
* Set the configuration for the war.
*
* @param warConfig The configuration for the war.
*/
public void setWarConfig(WarConfig warConfig) {
this.warConfig = warConfig;
}
/**
* Get the string form of the spring imports that have been configured.
*
* @return The string form of the spring imports that have been configured.
*/
protected ArrayList<String> getSpringImportURIs() {
ArrayList<String> springImportURIs = new ArrayList<String>(this.springImports.size());
for (SpringImport springImport : springImports) {
if (springImport.getFile() != null) {
if (springImport.getUri() != null) {
throw new IllegalStateException("A spring import configuration must specify a file or a URI, but not both.");
}
springImportURIs.add(new File(springImport.getFile()).getName());
}
else if (springImport.getUri() != null) {
springImportURIs.add(springImport.getUri());
}
else {
throw new IllegalStateException("A spring import configuration must specify either a file or a URI.");
}
}
return springImportURIs;
}
/**
* Add a spring import.
*
* @param springImports The spring import to add.
*/
public void addSpringImport(SpringImport springImports) {
this.springImports.add(springImports);
}
/**
* Add a copy resources.
*
* @param copyResources The copy resources to add.
*/
public void addCopyResources(CopyResources copyResources) {
this.copyResources.add(copyResources);
}
/**
* Add a global service interceptor to the spring configuration.
*
* @param interceptorConfig The interceptor configuration.
*/
public void addGlobalServiceInterceptor(GlobalServiceInterceptor interceptorConfig) {
this.globalServiceInterceptors.add(interceptorConfig);
}
/**
* Add a handler interceptor to the spring configuration.
*
* @param interceptorConfig The interceptor configuration.
*/
public void addHandlerInterceptor(HandlerInterceptor interceptorConfig) {
this.handlerInterceptors.add(interceptorConfig);
}
/**
* The value for the spring default autowiring.
*
* @return The value for the spring default autowiring.
*/
public String getDefaultAutowire() {
return defaultAutowire;
}
/**
* The value for the spring default autowiring.
*
* @param defaultAutowire The value for the spring default autowiring.
*/
public void setDefaultAutowire(String defaultAutowire) {
this.defaultAutowire = defaultAutowire;
}
/**
* The value for the spring default dependency checking.
*
* @return The value for the spring default dependency checking.
*/
public String getDefaultDependencyCheck() {
return defaultDependencyCheck;
}
/**
* The value for the spring default dependency checking.
*
* @param defaultDependencyCheck The value for the spring default dependency checking.
*/
public void setDefaultDependencyCheck(String defaultDependencyCheck) {
this.defaultDependencyCheck = defaultDependencyCheck;
}
/**
* The class to use as the context loader listener.
*
* @return The class to use as the context loader listener.
*/
public String getContextLoaderListenerClass() {
return contextLoaderListenerClass;
}
/**
* The class to use as the context loader listener.
*
* @param contextLoaderListenerClass The class to use as the context loader listener.
*/
public void setContextLoaderListenerClass(String contextLoaderListenerClass) {
this.contextLoaderListenerClass = contextLoaderListenerClass;
}
/**
* The class to use as the dispatcher servlet.
*
* @return The class to use as the dispatcher servlet.
*/
public String getDispatcherServletClass() {
return dispatcherServletClass;
}
/**
* The class to use as the dispatcher servlet.
*
* @param dispatcherServletClass The class to use as the dispatcher servlet.
*/
public void setDispatcherServletClass(String dispatcherServletClass) {
this.dispatcherServletClass = dispatcherServletClass;
}
/**
* Whether to exclude a file from copying to the WEB-INF/lib directory.
*
* @param file The file to exclude.
* @return Whether to exclude a file from copying to the lib directory.
*/
protected boolean knownExclude(File file) throws IOException {
//instantiate a loader with this library only in its path...
URLClassLoader loader = new URLClassLoader(new URL[]{file.toURL()}, null);
if (loader.findResource("META-INF/enunciate/preserve-in-war") != null) {
debug("%s will be included in the war because it contains the entry META-INF/enunciate/preserve-in-war.", file);
//if a jar happens to have the enunciate "preserve-in-war" file, it is NOT excluded.
return false;
}
else if (loader.findResource(com.sun.tools.apt.Main.class.getName().replace('.', '/').concat(".class")) != null) {
debug("%s will be excluded from the war because it appears to be tools.jar.", file);
//exclude tools.jar.
return true;
}
else if (loader.findResource(net.sf.jelly.apt.Context.class.getName().replace('.', '/').concat(".class")) != null) {
debug("%s will be excluded from the war because it appears to be apt-jelly.", file);
//exclude apt-jelly-core.jar
return true;
}
else if (loader.findResource(net.sf.jelly.apt.freemarker.FreemarkerModel.class.getName().replace('.', '/').concat(".class")) != null) {
debug("%s will be excluded from the war because it appears to be the apt-jelly-freemarker libs.", file);
//exclude apt-jelly-freemarker.jar
return true;
}
else if (loader.findResource(freemarker.template.Configuration.class.getName().replace('.', '/').concat(".class")) != null) {
debug("%s will be excluded from the war because it appears to be the freemarker libs.", file);
//exclude freemarker.jar
return true;
}
else if (loader.findResource(Enunciate.class.getName().replace('.', '/').concat(".class")) != null) {
debug("%s will be excluded from the war because it appears to be the enunciate core jar.", file);
//exclude enunciate-core.jar
return true;
}
else if (loader.findResource("javax/servlet/ServletContext.class") != null) {
debug("%s will be excluded from the war because it appears to be the servlet api.", file);
//exclude the servlet api.
return true;
}
else if (loader.findResource("org/codehaus/enunciate/modules/xfire_client/EnunciatedClientSoapSerializerHandler.class") != null) {
debug("%s will be excluded from the war because it appears to be the enunciated xfire client tools jar.", file);
//exclude xfire-client-tools
return true;
}
else if (loader.findResource("javax/swing/SwingBeanInfoBase.class") != null) {
debug("%s will be excluded from the war because it appears to be dt.jar.", file);
//exclude dt.jar
return true;
}
else if (loader.findResource("HTMLConverter.class") != null) {
debug("%s will be excluded from the war because it appears to be htmlconverter.jar.", file);
return true;
}
else if (loader.findResource("sun/tools/jconsole/JConsole.class") != null) {
debug("%s will be excluded from the war because it appears to be jconsole.jar.", file);
return true;
}
else if (loader.findResource("sun/jvm/hotspot/debugger/Debugger.class") != null) {
debug("%s will be excluded from the war because it appears to be sa-jdi.jar.", file);
return true;
}
else if (loader.findResource("sun/io/ByteToCharDoubleByte.class") != null) {
debug("%s will be excluded from the war because it appears to be charsets.jar.", file);
return true;
}
else if (loader.findResource("com/sun/deploy/ClientContainer.class") != null) {
debug("%s will be excluded from the war because it appears to be deploy.jar.", file);
return true;
}
else if (loader.findResource("com/sun/javaws/Globals.class") != null) {
debug("%s will be excluded from the war because it appears to be javaws.jar.", file);
return true;
}
else if (loader.findResource("javax/crypto/SecretKey.class") != null) {
debug("%s will be excluded from the war because it appears to be jce.jar.", file);
return true;
}
else if (loader.findResource("sun/net/www/protocol/https/HttpsClient.class") != null) {
debug("%s will be excluded from the war because it appears to be jsse.jar.", file);
return true;
}
else if (loader.findResource("sun/plugin/JavaRunTime.class") != null) {
debug("%s will be excluded from the war because it appears to be plugin.jar.", file);
return true;
}
else if (loader.findResource("com/sun/corba/se/impl/activation/ServerMain.class") != null) {
debug("%s will be excluded from the war because it appears to be rt.jar.", file);
return true;
}
else if (Service.providers(DeploymentModule.class, loader).hasNext()) {
debug("%s will be excluded from the war because it appears to be an enunciate module.", file);
//exclude by default any deployment module libraries.
return true;
}
return false;
}
/**
* Configure whether to compile with debug info (default: true).
*
* @param compileDebugInfo Whether to compile with debug info (default: true).
*/
public void setCompileDebugInfo(boolean compileDebugInfo) {
this.compileDebugInfo = compileDebugInfo;
}
/**
* @return 200
*/
@Override
public int getOrder() {
return 200;
}
@Override
public RuleSet getConfigurationRules() {
return new SpringAppRuleSet();
}
@Override
public Validator getValidator() {
return new SpringAppValidator();
}
/**
* The directory where the config files are generated.
*
* @return The directory where the config files are generated.
*/
protected File getConfigGenerateDir() {
return new File(getGenerateDir(), "config");
}
}
| false | true | protected void doBuild() throws IOException, EnunciateException {
Enunciate enunciate = getEnunciate();
File buildDir = getBuildDir();
if ((this.warConfig != null) && (this.warConfig.getPreBase() != null)) {
File preBase = enunciate.resolvePath(this.warConfig.getPreBase());
if (preBase.isDirectory()) {
info("Copying preBase directory %s to %s...", preBase, buildDir);
enunciate.copyDir(preBase, buildDir);
}
else {
info("Extracting preBase zip file %s to %s...", preBase, buildDir);
enunciate.extractBase(new FileInputStream(preBase), buildDir);
}
}
info("Building the expanded WAR in %s", buildDir);
File webinf = new File(buildDir, "WEB-INF");
File webinfClasses = new File(webinf, "classes");
File webinfLib = new File(webinf, "lib");
//copy the compiled classes to WEB-INF/classes.
enunciate.copyDir(getCompileDir(), webinfClasses);
//prime the list of libs to include in the war with what's on the enunciate classpath.
List<String> warLibs = new ArrayList<String>();
if (this.warConfig == null || this.warConfig.isIncludeClasspathLibs()) {
warLibs.addAll(Arrays.asList(enunciate.getEnunciateClasspath().split(File.pathSeparator)));
}
List<IncludeExcludeLibs> includePatterns = this.warConfig != null ? new ArrayList<IncludeExcludeLibs>(this.warConfig.getIncludeLibs()) : new ArrayList<IncludeExcludeLibs>();
List<IncludeExcludeLibs> includedFiles = new ArrayList<IncludeExcludeLibs>();
Iterator<IncludeExcludeLibs> includeLibsIt = includePatterns.iterator();
while (includeLibsIt.hasNext()) {
IncludeExcludeLibs el = includeLibsIt.next();
if (el.getFile() != null) {
includedFiles.add(el);
}
if (el.getPattern() == null) {
includeLibsIt.remove();
}
}
List<IncludeExcludeLibs> excludeLibs = this.warConfig != null ? new ArrayList<IncludeExcludeLibs>(this.warConfig.getExcludeLibs()) : new ArrayList<IncludeExcludeLibs>();
AntPathMatcher pathMatcher = new AntPathMatcher();
List<File> includedLibs = new ArrayList<File>();
// Now get the files that are to be explicitly included.
// If none are explicitly included, include all of them.
INCLUDE_LOOP:
for (String warLib : warLibs) {
File libFile = new File(warLib);
if (libFile.exists()) {
if (includePatterns.isEmpty()) {
includedLibs.add(libFile);
}
else {
for (IncludeExcludeLibs includeJar : includePatterns) {
String pattern = includeJar.getPattern();
String absolutePath = libFile.getAbsolutePath();
if (absolutePath.startsWith(File.separator)) {
//lob off the beginning "/" for Linux boxes.
absolutePath = absolutePath.substring(1);
}
if ((pattern != null) && (pathMatcher.isPattern(pattern) && (pathMatcher.match(pattern, absolutePath)))) {
includedLibs.add(libFile);
break INCLUDE_LOOP;
}
}
}
}
}
//if there are any excludes, filter them out here.
boolean excludeDefaults = this.warConfig == null || this.warConfig.isExcludeDefaultLibs();
List<String> manifestClasspath = new ArrayList<String>();
Iterator<File> includeLibIt = includedLibs.iterator();
INCLUDE_LOOP:
while (includeLibIt.hasNext()) {
File includedLib = includeLibIt.next();
if (excludeDefaults && knownExclude(includedLib)) {
includeLibIt.remove();
}
else {
for (IncludeExcludeLibs excludeJar : excludeLibs) {
String pattern = excludeJar.getPattern();
String absolutePath = includedLib.getAbsolutePath();
if (absolutePath.startsWith(File.separator)) {
//lob off the beginning "/" for Linux boxes.
absolutePath = absolutePath.substring(1);
}
boolean exclude = ((excludeJar.getFile() != null) && (excludeJar.getFile().equals(includedLib))) ||
((pattern != null) && (pathMatcher.isPattern(pattern)) && (pathMatcher.match(pattern, absolutePath)));
if (exclude) {
includeLibIt.remove();
if ((excludeJar.isIncludeInManifest()) && (!includedLib.isDirectory())) {
//include it in the manifest anyway.
manifestClasspath.add(includedLib.getName());
}
continue INCLUDE_LOOP;
}
}
}
}
//now add the lib files that are explicitly included.
Iterator<IncludeExcludeLibs> includeIt = includedFiles.iterator();
while (includeIt.hasNext()) {
IncludeExcludeLibs includeJar = includeIt.next();
if (includeJar.getFile() != null) {
warLibs.add(includeJar.getFile().getAbsolutePath());
includeIt.remove();
}
}
for (File includedLib : includedLibs) {
if (includedLib.isDirectory()) {
info("Adding the contents of %s to WEB-INF/classes.", includedLib);
enunciate.copyDir(includedLib, webinfClasses);
}
else {
info("Including %s in WEB-INF/lib.", includedLib);
enunciate.copyFile(includedLib, includedLib.getParentFile(), webinfLib);
}
}
// write the manifest file.
Manifest manifest = this.warConfig == null ? WarConfig.getDefaultManifest() : this.warConfig.getManifest();
if ((manifestClasspath.size() > 0) && (manifest.getMainAttributes().getValue("Class-Path") == null)) {
StringBuilder manifestClasspathValue = new StringBuilder();
Iterator<String> manifestClasspathIt = manifestClasspath.iterator();
while (manifestClasspathIt.hasNext()) {
String entry = manifestClasspathIt.next();
manifestClasspathValue.append(entry);
if (manifestClasspathIt.hasNext()) {
manifestClasspathValue.append(" ");
}
}
manifest.getMainAttributes().putValue("Class-Path", manifestClasspathValue.toString());
}
File metaInf = new File(buildDir, "META-INF");
metaInf.mkdirs();
FileOutputStream manifestFileOut = new FileOutputStream(new File(metaInf, "MANIFEST.MF"));
manifest.write(manifestFileOut);
manifestFileOut.flush();
manifestFileOut.close();
//todo: assert that the necessary jars (spring, xfire, commons-whatever, etc.) are there?
//put the web.xml in WEB-INF. Pass it through a stylesheet, if specified.
File xfireConfigDir = getConfigGenerateDir();
File webXML = new File(xfireConfigDir, "web.xml");
File destWebXML = new File(webinf, "web.xml");
if ((this.warConfig != null) && (this.warConfig.getWebXMLTransformURL() != null)) {
URL transformURL = this.warConfig.getWebXMLTransformURL();
info("web.xml transform has been specified as %s.", transformURL);
try {
StreamSource source = new StreamSource(transformURL.openStream());
Transformer transformer = new TransformerFactoryImpl().newTransformer(source);
info("Transforming %s to %s.", webXML, destWebXML);
transformer.transform(new StreamSource(new FileReader(webXML)), new StreamResult(destWebXML));
}
catch (TransformerException e) {
throw new EnunciateException("Error during transformation of the web.xml (stylesheet " + transformURL + ", file " + webXML + ")", e);
}
}
else {
enunciate.copyFile(webXML, destWebXML);
}
//copy the spring application context and servlet config from the build dir to the WEB-INF directory.
enunciate.copyFile(new File(xfireConfigDir, "applicationContext.xml"), new File(webinf, "applicationContext.xml"));
enunciate.copyFile(new File(xfireConfigDir, "spring-servlet.xml"), new File(webinf, "spring-servlet.xml"));
for (SpringImport springImport : springImports) {
//copy the extra spring import files to the WEB-INF directory to be imported.
if (springImport.getFile() != null) {
File importFile = enunciate.resolvePath(springImport.getFile());
enunciate.copyFile(importFile, new File(webinf, importFile.getName()));
}
}
//now try to find the documentation and export it to the build directory...
Artifact artifact = enunciate.findArtifact("docs");
if (artifact != null) {
File docsDir = buildDir;
if ((this.warConfig != null) && (this.warConfig.getDocsDir() != null)) {
docsDir = new File(buildDir, this.warConfig.getDocsDir());
docsDir.mkdirs();
}
artifact.exportTo(docsDir, enunciate);
}
else {
warn("WARNING: No documentation artifact found!");
}
File gwtAppDir = (File) enunciate.getProperty("gwt.app.dir");
if (gwtAppDir != null) {
File gwtAppDest = buildDir;
if ((this.warConfig != null) && (this.warConfig.getGwtAppDir() != null)) {
gwtAppDest = new File(buildDir, this.warConfig.getDocsDir());
}
enunciate.copyDir(gwtAppDir, gwtAppDest);
}
else {
info("No GWT application directory was found. Skipping the copy...");
}
//extract a post base if specified.
if ((this.warConfig != null) && (this.warConfig.getPostBase() != null)) {
File postBase = enunciate.resolvePath(this.warConfig.getPostBase());
if (postBase.isDirectory()) {
info("Copying postBase directory %s to %s...", postBase, buildDir);
enunciate.copyDir(postBase, buildDir);
}
else {
info("Extracting postBase zip file %s to %s...", postBase, buildDir);
enunciate.extractBase(new FileInputStream(postBase), buildDir);
}
}
//export the expanded application directory.
enunciate.addArtifact(new FileArtifact(getName(), "spring.app.dir", buildDir));
}
| protected void doBuild() throws IOException, EnunciateException {
Enunciate enunciate = getEnunciate();
File buildDir = getBuildDir();
if ((this.warConfig != null) && (this.warConfig.getPreBase() != null)) {
File preBase = enunciate.resolvePath(this.warConfig.getPreBase());
if (preBase.isDirectory()) {
info("Copying preBase directory %s to %s...", preBase, buildDir);
enunciate.copyDir(preBase, buildDir);
}
else {
info("Extracting preBase zip file %s to %s...", preBase, buildDir);
enunciate.extractBase(new FileInputStream(preBase), buildDir);
}
}
info("Building the expanded WAR in %s", buildDir);
File webinf = new File(buildDir, "WEB-INF");
File webinfClasses = new File(webinf, "classes");
File webinfLib = new File(webinf, "lib");
//copy the compiled classes to WEB-INF/classes.
enunciate.copyDir(getCompileDir(), webinfClasses);
//prime the list of libs to include in the war with what's on the enunciate classpath.
List<String> warLibs = new ArrayList<String>();
if (this.warConfig == null || this.warConfig.isIncludeClasspathLibs()) {
warLibs.addAll(Arrays.asList(enunciate.getEnunciateClasspath().split(File.pathSeparator)));
}
List<IncludeExcludeLibs> includePatterns = this.warConfig != null ? new ArrayList<IncludeExcludeLibs>(this.warConfig.getIncludeLibs()) : new ArrayList<IncludeExcludeLibs>();
List<IncludeExcludeLibs> includedFiles = new ArrayList<IncludeExcludeLibs>();
Iterator<IncludeExcludeLibs> includeLibsIt = includePatterns.iterator();
while (includeLibsIt.hasNext()) {
IncludeExcludeLibs el = includeLibsIt.next();
if (el.getFile() != null) {
includedFiles.add(el);
}
if (el.getPattern() == null) {
includeLibsIt.remove();
}
}
List<IncludeExcludeLibs> excludeLibs = this.warConfig != null ? new ArrayList<IncludeExcludeLibs>(this.warConfig.getExcludeLibs()) : new ArrayList<IncludeExcludeLibs>();
AntPathMatcher pathMatcher = new AntPathMatcher();
List<File> includedLibs = new ArrayList<File>();
// Now get the files that are to be explicitly included.
// If none are explicitly included, include all of them.
for (String warLib : warLibs) {
File libFile = new File(warLib);
if (libFile.exists()) {
if (includePatterns.isEmpty()) {
includedLibs.add(libFile);
}
else {
for (IncludeExcludeLibs includeJar : includePatterns) {
String pattern = includeJar.getPattern();
String absolutePath = libFile.getAbsolutePath();
if (absolutePath.startsWith(File.separator)) {
//lob off the beginning "/" for Linux boxes.
absolutePath = absolutePath.substring(1);
}
if ((pattern != null) && (pathMatcher.isPattern(pattern) && (pathMatcher.match(pattern, absolutePath)))) {
includedLibs.add(libFile);
break;
}
}
}
}
}
//if there are any excludes, filter them out here.
boolean excludeDefaults = this.warConfig == null || this.warConfig.isExcludeDefaultLibs();
List<String> manifestClasspath = new ArrayList<String>();
Iterator<File> includeLibIt = includedLibs.iterator();
INCLUDE_LOOP:
while (includeLibIt.hasNext()) {
File includedLib = includeLibIt.next();
if (excludeDefaults && knownExclude(includedLib)) {
includeLibIt.remove();
}
else {
for (IncludeExcludeLibs excludeJar : excludeLibs) {
String pattern = excludeJar.getPattern();
String absolutePath = includedLib.getAbsolutePath();
if (absolutePath.startsWith(File.separator)) {
//lob off the beginning "/" for Linux boxes.
absolutePath = absolutePath.substring(1);
}
boolean exclude = ((excludeJar.getFile() != null) && (excludeJar.getFile().equals(includedLib))) ||
((pattern != null) && (pathMatcher.isPattern(pattern)) && (pathMatcher.match(pattern, absolutePath)));
if (exclude) {
includeLibIt.remove();
if ((excludeJar.isIncludeInManifest()) && (!includedLib.isDirectory())) {
//include it in the manifest anyway.
manifestClasspath.add(includedLib.getName());
}
continue INCLUDE_LOOP;
}
}
}
}
//now add the lib files that are explicitly included.
Iterator<IncludeExcludeLibs> includeIt = includedFiles.iterator();
while (includeIt.hasNext()) {
IncludeExcludeLibs includeJar = includeIt.next();
if (includeJar.getFile() != null) {
warLibs.add(includeJar.getFile().getAbsolutePath());
includeIt.remove();
}
}
for (File includedLib : includedLibs) {
if (includedLib.isDirectory()) {
info("Adding the contents of %s to WEB-INF/classes.", includedLib);
enunciate.copyDir(includedLib, webinfClasses);
}
else {
info("Including %s in WEB-INF/lib.", includedLib);
enunciate.copyFile(includedLib, includedLib.getParentFile(), webinfLib);
}
}
// write the manifest file.
Manifest manifest = this.warConfig == null ? WarConfig.getDefaultManifest() : this.warConfig.getManifest();
if ((manifestClasspath.size() > 0) && (manifest.getMainAttributes().getValue("Class-Path") == null)) {
StringBuilder manifestClasspathValue = new StringBuilder();
Iterator<String> manifestClasspathIt = manifestClasspath.iterator();
while (manifestClasspathIt.hasNext()) {
String entry = manifestClasspathIt.next();
manifestClasspathValue.append(entry);
if (manifestClasspathIt.hasNext()) {
manifestClasspathValue.append(" ");
}
}
manifest.getMainAttributes().putValue("Class-Path", manifestClasspathValue.toString());
}
File metaInf = new File(buildDir, "META-INF");
metaInf.mkdirs();
FileOutputStream manifestFileOut = new FileOutputStream(new File(metaInf, "MANIFEST.MF"));
manifest.write(manifestFileOut);
manifestFileOut.flush();
manifestFileOut.close();
//todo: assert that the necessary jars (spring, xfire, commons-whatever, etc.) are there?
//put the web.xml in WEB-INF. Pass it through a stylesheet, if specified.
File xfireConfigDir = getConfigGenerateDir();
File webXML = new File(xfireConfigDir, "web.xml");
File destWebXML = new File(webinf, "web.xml");
if ((this.warConfig != null) && (this.warConfig.getWebXMLTransformURL() != null)) {
URL transformURL = this.warConfig.getWebXMLTransformURL();
info("web.xml transform has been specified as %s.", transformURL);
try {
StreamSource source = new StreamSource(transformURL.openStream());
Transformer transformer = new TransformerFactoryImpl().newTransformer(source);
info("Transforming %s to %s.", webXML, destWebXML);
transformer.transform(new StreamSource(new FileReader(webXML)), new StreamResult(destWebXML));
}
catch (TransformerException e) {
throw new EnunciateException("Error during transformation of the web.xml (stylesheet " + transformURL + ", file " + webXML + ")", e);
}
}
else {
enunciate.copyFile(webXML, destWebXML);
}
//copy the spring application context and servlet config from the build dir to the WEB-INF directory.
enunciate.copyFile(new File(xfireConfigDir, "applicationContext.xml"), new File(webinf, "applicationContext.xml"));
enunciate.copyFile(new File(xfireConfigDir, "spring-servlet.xml"), new File(webinf, "spring-servlet.xml"));
for (SpringImport springImport : springImports) {
//copy the extra spring import files to the WEB-INF directory to be imported.
if (springImport.getFile() != null) {
File importFile = enunciate.resolvePath(springImport.getFile());
enunciate.copyFile(importFile, new File(webinf, importFile.getName()));
}
}
//now try to find the documentation and export it to the build directory...
Artifact artifact = enunciate.findArtifact("docs");
if (artifact != null) {
File docsDir = buildDir;
if ((this.warConfig != null) && (this.warConfig.getDocsDir() != null)) {
docsDir = new File(buildDir, this.warConfig.getDocsDir());
docsDir.mkdirs();
}
artifact.exportTo(docsDir, enunciate);
}
else {
warn("WARNING: No documentation artifact found!");
}
File gwtAppDir = (File) enunciate.getProperty("gwt.app.dir");
if (gwtAppDir != null) {
File gwtAppDest = buildDir;
if ((this.warConfig != null) && (this.warConfig.getGwtAppDir() != null)) {
gwtAppDest = new File(buildDir, this.warConfig.getDocsDir());
}
enunciate.copyDir(gwtAppDir, gwtAppDest);
}
else {
info("No GWT application directory was found. Skipping the copy...");
}
//extract a post base if specified.
if ((this.warConfig != null) && (this.warConfig.getPostBase() != null)) {
File postBase = enunciate.resolvePath(this.warConfig.getPostBase());
if (postBase.isDirectory()) {
info("Copying postBase directory %s to %s...", postBase, buildDir);
enunciate.copyDir(postBase, buildDir);
}
else {
info("Extracting postBase zip file %s to %s...", postBase, buildDir);
enunciate.extractBase(new FileInputStream(postBase), buildDir);
}
}
//export the expanded application directory.
enunciate.addArtifact(new FileArtifact(getName(), "spring.app.dir", buildDir));
}
|
diff --git a/source/ch/cyberduck/core/gdocs/GDPath.java b/source/ch/cyberduck/core/gdocs/GDPath.java
index 6771aee64..0bc270db0 100644
--- a/source/ch/cyberduck/core/gdocs/GDPath.java
+++ b/source/ch/cyberduck/core/gdocs/GDPath.java
@@ -1,969 +1,970 @@
package ch.cyberduck.core.gdocs;
/*
* Copyright (c) 2002-2010 David Kocher. All rights reserved.
*
* http://cyberduck.ch/
*
* 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.
*
* Bug fixes, suggestions and comments should be sent to:
* [email protected]
*/
import ch.cyberduck.core.*;
import ch.cyberduck.core.i18n.Locale;
import ch.cyberduck.core.io.BandwidthThrottle;
import ch.cyberduck.core.serializer.Deserializer;
import ch.cyberduck.core.serializer.Serializer;
import ch.cyberduck.core.threading.ThreadPool;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import com.google.gdata.client.CoreErrorDomain;
import com.google.gdata.client.DocumentQuery;
import com.google.gdata.client.GoogleAuthTokenFactory;
import com.google.gdata.client.Service;
import com.google.gdata.client.http.HttpGDataRequest;
import com.google.gdata.client.spreadsheet.SpreadsheetService;
import com.google.gdata.data.*;
import com.google.gdata.data.acl.AclEntry;
import com.google.gdata.data.acl.AclFeed;
import com.google.gdata.data.acl.AclRole;
import com.google.gdata.data.acl.AclScope;
import com.google.gdata.data.docs.*;
import com.google.gdata.data.media.MediaMultipart;
import com.google.gdata.data.media.MediaSource;
import com.google.gdata.data.media.MediaStreamSource;
import com.google.gdata.util.ContentType;
import com.google.gdata.util.NotImplementedException;
import com.google.gdata.util.ServiceException;
import javax.mail.MessagingException;
import java.io.*;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.MessageFormat;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class GDPath extends Path {
private static Logger log = Logger.getLogger(GDPath.class);
private static class Factory extends PathFactory<GDSession> {
@Override
protected Path create(GDSession session, String path, int type) {
return new GDPath(session, path, type);
}
@Override
protected Path create(GDSession session, String parent, String name, int type) {
return new GDPath(session, parent, name, type);
}
@Override
protected Path create(GDSession session, String parent, Local file) {
return new GDPath(session, parent, file);
}
@Override
protected <T> Path create(GDSession session, T dict) {
return new GDPath(session, dict);
}
}
public static PathFactory factory() {
return new Factory();
}
@Override
protected void init(Deserializer dict) {
String resourceIdObj = dict.stringForKey("ResourceId");
if(resourceIdObj != null) {
this.setResourceId(resourceIdObj);
}
String exportUriObj = dict.stringForKey("ExportUri");
if(exportUriObj != null) {
this.setExportUri(exportUriObj);
}
String documentTypeObj = dict.stringForKey("DocumentType");
if(documentTypeObj != null) {
this.setDocumentType(documentTypeObj);
}
super.init(dict);
}
@Override
protected <S> S getAsDictionary(Serializer dict) {
if(resourceId != null) {
dict.setStringForKey(resourceId, "ResourceId");
}
if(exportUri != null) {
dict.setStringForKey(exportUri, "ExportUri");
}
if(documentType != null) {
dict.setStringForKey(documentType, "DocumentType");
}
return super.<S>getAsDictionary(dict);
}
private final GDSession session;
protected GDPath(GDSession s, String parent, String name, int type) {
super(parent, name, type);
this.session = s;
}
protected GDPath(GDSession s, String path, int type) {
super(path, type);
this.session = s;
}
protected GDPath(GDSession s, String parent, Local file) {
super(parent, file);
this.session = s;
}
protected <T> GDPath(GDSession s, T dict) {
super(dict);
this.session = s;
}
/**
* Arbitrary file type not converted to Google Docs.
*/
private static final String DOCUMENT_FILE_TYPE = "file";
/**
* Kind of document or folder.
*/
private String documentType;
public String getDocumentType() {
if(null == documentType) {
if(attributes().isDirectory()) {
return FolderEntry.LABEL;
}
// Arbitrary file type not converted to Google Docs.
return DOCUMENT_FILE_TYPE;
}
return documentType;
}
public void setDocumentType(String documentType) {
this.documentType = documentType;
}
/**
* URL from where the document can be downloaded.
*/
private String exportUri;
/**
* @return Download URL without export format.
*/
public String getExportUri() {
if(StringUtils.isBlank(exportUri)) {
log.warn("Refetching Export URI for " + this.toString());
AttributedList<AbstractPath> l = this.getParent().children();
if(l.contains(this.getReference())) {
exportUri = ((GDPath) l.get(this.getReference())).getExportUri();
}
else {
log.error("Missing Export URI for " + this.toString());
}
}
return exportUri;
}
public void setExportUri(String exportUri) {
this.exportUri = exportUri;
}
/**
* Resource ID. Contains both the document type and document ID.
* For folders this is <code>folder:0BwoD_34YE1B4ZDFiZmMwNTAtMGFiMy00MmQ1LTg1NTQtNmFiYWFkNTg2MTQ3</code>
*/
private String resourceId;
public String getResourceId() {
if(StringUtils.isBlank(resourceId)) {
log.warn("Refetching Resource ID for " + this.toString());
AttributedList<AbstractPath> l = this.getParent().children();
if(l.contains(this.getReference())) {
resourceId = ((GDPath) l.get(this.getReference())).getResourceId();
}
else {
log.error("Missing Resource ID for " + this.toString());
}
}
return resourceId;
}
public void setResourceId(String resourceId) {
this.resourceId = resourceId;
}
private String documentUri;
/**
* @return The URL to the document editable in the web browser
*/
public String getDocumentUri() {
return documentUri;
}
public void setDocumentUri(String documentUri) {
this.documentUri = documentUri;
}
private String getDocumentId() {
// Removing document type from resourceId gives us the documentId
return StringUtils.removeStart(this.getResourceId(), this.getDocumentType() + ":");
}
/**
* @return Includes the protocol and hostname only
*/
protected StringBuilder getFeed() {
final StringBuilder feed = new StringBuilder(this.getSession().getHost().getProtocol().getScheme()).append("://");
feed.append(this.getSession().getHost().getHostname());
feed.append("/feeds/default/private/full/");
return feed;
}
protected String getResourceFeed() throws MalformedURLException {
return this.getFeed().append(this.getResourceId()).toString();
}
protected String getFolderFeed() throws MalformedURLException {
final StringBuilder feed = this.getFeed();
if(this.isRoot()) {
return feed.append("folder%3Aroot/contents").toString();
}
return feed.append("folder%3A").append(this.getDocumentId()).append("/contents").toString();
}
protected String getAclFeed() throws MalformedURLException {
final StringBuilder feed = new StringBuilder(this.getResourceFeed());
return feed.append("/acl").toString();
}
public String getRevisionsFeed() throws MalformedURLException {
final StringBuilder feed = new StringBuilder(this.getResourceFeed());
return feed.append("/revisions").toString();
}
@Override
public void readSize() {
;
}
@Override
public void readTimestamp() {
throw new UnsupportedOperationException();
}
@Override
public void readAcl() {
try {
this.getSession().check();
this.getSession().message(MessageFormat.format(Locale.localizedString("Getting permission of {0}", "Status"),
this.getName()));
Acl acl = new Acl();
AclFeed feed = this.getSession().getClient().getFeed(new URL(this.getAclFeed()), AclFeed.class);
for(AclEntry entry : feed.getEntries()) {
AclScope scope = entry.getScope();
AclScope.Type type = scope.getType();
AclRole role = entry.getRole();
if(type.equals(AclScope.Type.USER)) {
// Only editable if not owner of document. Changing owner is not supported.
boolean editable = !role.getValue().equals(AclRole.OWNER.getValue());
acl.addAll(new Acl.EmailUser(scope.getValue(), editable),
new Acl.Role(role.getValue(), editable));
}
else if(type.equals(AclScope.Type.DOMAIN)) {
// Google Apps Domain grant.
acl.addAll(new Acl.DomainUser(scope.getValue()), new Acl.Role(role.getValue()));
}
else if(type.equals(AclScope.Type.GROUP)) {
// Google Group email grant
acl.addAll(new Acl.GroupUser(scope.getValue(), true), new Acl.Role(role.getValue()));
}
else if(type.equals(AclScope.Type.DEFAULT)) {
// Value of scope is null. Default access for non authenticated
// users. Publicly shared with all users.
acl.addAll(new Acl.CanonicalUser(AclScope.Type.DEFAULT.name(), Locale.localizedString("Public"), false),
new Acl.Role(role.getValue()));
}
else {
log.warn("Unsupported scope:" + type);
}
}
this.attributes().setAcl(acl);
}
catch(IOException e) {
this.error("Cannot read file attributes", e);
}
catch(ServiceException e) {
this.error("Cannot read file attributes", e);
}
}
@Override
public void writeAcl(Acl acl, boolean recursive) {
try {
// Delete all previous ACLs before inserting updated set.
AclFeed feed = this.getSession().getClient().getFeed(new URL(this.getAclFeed()), AclFeed.class);
for(AclEntry entry : feed.getEntries()) {
if(entry.getRole().toString().equals(AclRole.OWNER.toString())) {
// Do not remove owner of document
continue;
}
entry.delete();
}
for(Acl.User user : acl.keySet()) {
if(!user.isValid()) {
continue;
}
if(!user.isEditable()) {
continue;
}
// The API supports sharing permissions on multiple levels. These values
// correspond to the <gAcl:scope> type attribute
AclScope scope = null;
if(user instanceof Acl.EmailUser) {
// a user's email address. Creating an ACL entry that shares a document or folder with users will notify
// relevant users via email that they have new access to the document or folder
scope = new AclScope(AclScope.Type.USER, user.getIdentifier());
}
else if(user instanceof Acl.GroupUser) {
// a Google Group email address
scope = new AclScope(AclScope.Type.GROUP, user.getIdentifier());
}
else if(user instanceof Acl.DomainUser) {
// a Google Apps domain.
scope = new AclScope(AclScope.Type.DOMAIN, user.getIdentifier());
}
else if(user instanceof Acl.CanonicalUser) {
if(user.getIdentifier().equals(AclScope.Type.DEFAULT.name())) {
// Publicly shared with all users
scope = new AclScope(AclScope.Type.DEFAULT, null);
}
}
if(null == scope) {
log.warn("Unsupported scope:" + user);
continue;
}
for(Acl.Role role : acl.get(user)) {
if(!role.isValid()) {
continue;
}
AclEntry entry = new AclEntry();
entry.setScope(scope);
entry.setRole(new AclRole(role.getName()));
// Insert updated ACL entry for scope
this.getSession().getClient().insert(new URL(this.getAclFeed()), entry);
}
}
}
catch(IOException e) {
this.error("Cannot change permissions", e);
}
catch(ServiceException e) {
this.error("Cannot change permissions", e);
}
finally {
this.attributes().clear(false, false, true, false);
}
if(attributes().isDirectory()) {
if(recursive) {
// All child objects of the folder reflect will reflect the new
// sharing permission regardless.
}
}
}
@Override
public GDSession getSession() {
return session;
}
@Override
protected void download(BandwidthThrottle throttle, StreamListener listener, boolean check) {
if(attributes().isFile()) {
OutputStream out = null;
InputStream in = null;
try {
if(check) {
this.getSession().check();
}
this.getSession().message(MessageFormat.format(Locale.localizedString("Downloading {0}", "Status"),
this.getName()));
MediaContent mc = new MediaContent();
StringBuilder uri = new StringBuilder(this.getExportUri());
final String type = this.getDocumentType();
final GoogleAuthTokenFactory.UserToken token
= (GoogleAuthTokenFactory.UserToken) this.getSession().getClient().getAuthTokenFactory().getAuthToken();
try {
if(type.equals(SpreadsheetEntry.LABEL)) {
// Authenticate against the Spreadsheets API to obtain an auth token
SpreadsheetService spreadsheet = new SpreadsheetService(this.getSession().getUserAgent());
final Credentials credentials = this.getSession().getHost().getCredentials();
spreadsheet.setUserCredentials(credentials.getUsername(), credentials.getPassword());
// Substitute the spreadsheets token for the docs token
this.getSession().getClient().setUserToken(
((GoogleAuthTokenFactory.UserToken) spreadsheet.getAuthTokenFactory().getAuthToken()).getValue());
}
if(StringUtils.isNotEmpty(getExportFormat(type))) {
uri.append("&exportFormat=").append(getExportFormat(type));
}
mc.setUri(uri.toString());
MediaSource ms = this.getSession().getClient().getMedia(mc);
in = ms.getInputStream();
if(null == in) {
throw new IOException("Unable opening data stream");
}
out = this.getLocal().getOutputStream(this.status().isResume());
this.download(in, out, throttle, listener);
}
finally {
// Restore docs token for our DocList client
this.getSession().getClient().setUserToken(token.getValue());
}
}
catch(IOException e) {
this.error("Download failed", e);
}
catch(ServiceException e) {
this.error("Download failed", e);
}
finally {
IOUtils.closeQuietly(in);
IOUtils.closeQuietly(out);
}
}
}
/**
* Google Apps Premier domains can upload files of arbitrary type. Uploading an arbitrary file is
* the same as uploading documents (with and without metadata), except there is no
* restriction on the file's Content-Type. Unlike normal document uploads, arbitrary
* file uploads preserve their original format/extension, meaning there is no loss in
* fidelity when the file is stored in Google Docs.
* <p/>
* By default, uploaded document files will be converted to a native Google Docs format.
* For example, an .xls upload will create a Google Spreadsheet. To keep the file as an Excel
* spreadsheet (and therefore upload the file as an arbitrary file), specify the convert=false
* parameter to preserve the original format. The convert parameter is true by default for
* document files. The parameter will be ignored for types that cannot be
* converted (e.g. .exe, .mp3, .mov, etc.).
*
* @param throttle The bandwidth limit
* @param listener The stream listener to notify about bytes received and sent
* @param check Check for open connection and open if needed before transfer
*/
@Override
protected void upload(BandwidthThrottle throttle, StreamListener listener, boolean check) {
try {
if(attributes().isFile()) {
if(check) {
this.getSession().check();
}
this.getSession().message(MessageFormat.format(Locale.localizedString("Uploading {0}", "Status"),
this.getName()));
InputStream in = null;
OutputStream out = null;
try {
final String mime = this.getLocal().getMimeType();
final MediaStreamSource source = new MediaStreamSource(this.getLocal().getInputStream(), mime,
new DateTime(this.attributes().getModificationDate()),
this.getLocal().attributes().getSize());
if(this.exists()) {
// First, fetch entry using the resourceId
URL url = new URL(this.getResourceFeed());
final DocumentListEntry updated = this.getSession().getClient().getEntry(url, DocumentListEntry.class);
updated.setMediaSource(source);
updated.updateMedia(true);
}
else {
final MediaContent content = new MediaContent();
content.setMediaSource(source);
content.setMimeType(new ContentType(mime));
content.setLength(this.getLocal().attributes().getSize());
final DocumentListEntry document = new DocumentListEntry();
document.setContent(content);
document.setTitle(new PlainTextConstruct(this.getName()));
this.getSession().message(MessageFormat.format(Locale.localizedString("Uploading {0}", "Status"),
this.getName()));
status().setResume(false);
String feed = ((GDPath) this.getParent()).getFolderFeed();
StringBuilder url = new StringBuilder(feed);
if(this.isOcrSupported()) {
// Image file type
url.append("?ocr=").append(Preferences.instance().getProperty("google.docs.upload.ocr"));
}
else if(this.isConversionSupported()) {
// Convertible to Google Docs file type
url.append("?convert=").append(Preferences.instance().getProperty("google.docs.upload.convert"));
}
Service.GDataRequest request = null;
try {
// Write as MIME multipart containing the entry and media. Use the
// content type from the multipart since this contains auto-generated
// boundary attributes.
final MediaMultipart multipart = new MediaMultipart(document, document.getMediaSource());
request = this.getSession().getClient().createRequest(
Service.GDataRequest.RequestType.INSERT, new URL(url.toString()),
new ContentType(multipart.getContentType()));
if(request instanceof HttpGDataRequest) {
// No internal buffering of request with a known content length
// Size is incorect because of additional MIME header
// ((HttpGDataRequest)request).getConnection().setFixedLengthStreamingMode(
// (int) this.getLocal().attributes().getSize()
// );
// Use chunked upload with default chunk size.
((HttpGDataRequest) request).getConnection().setChunkedStreamingMode(0);
}
+ request.setHeader("Expect", "100-Continue");
out = request.getRequestStream();
final PipedOutputStream pipe = new PipedOutputStream();
in = new PipedInputStream(pipe);
ThreadPool.instance().execute(new Runnable() {
public void run() {
try {
multipart.writeTo(pipe);
pipe.flush();
pipe.close();
}
catch(IOException e) {
log.error(e.getMessage());
}
catch(MessagingException e) {
log.error(e.getMessage());
}
}
});
this.upload(out, in, throttle, listener);
// Parse response for HTTP error message.
try {
request.execute();
}
catch(ServiceException e) {
this.status().setComplete(false);
throw e;
}
}
catch(MessagingException e) {
throw new ServiceException(
CoreErrorDomain.ERR.cantWriteMimeMultipart, e);
}
finally {
if(request != null) {
request.end();
}
}
}
}
finally {
IOUtils.closeQuietly(in);
IOUtils.closeQuietly(out);
}
}
}
catch(ServiceException e) {
this.error("Upload failed", e);
}
catch(IOException e) {
this.error("Upload failed", e);
}
}
/**
* @return True for image formats supported by OCR
*/
protected boolean isOcrSupported() {
return this.getMimeType().endsWith("png") || this.getMimeType().endsWith("jpeg")
|| this.getMimeType().endsWith("gif");
}
/**
* @return True if the document, spreadsheet or presentation format is recognized by Google Docs.
*/
protected boolean isConversionSupported() {
// The convert parameter will be ignored for types that cannot be converted. Therefore we
// can always return true.
return true;
}
@Override
public AttributedList<Path> list() {
final AttributedList<Path> children = new AttributedList<Path>();
try {
this.getSession().check();
this.getSession().message(MessageFormat.format(Locale.localizedString("Listing directory {0}", "Status"),
this.getName()));
this.getSession().setWorkdir(this);
children.addAll(this.list(new DocumentQuery(new URL(this.getFolderFeed()))));
}
catch(ServiceException e) {
log.warn("Listing directory failed:" + e.getMessage());
children.attributes().setReadable(false);
if(this.cache().isEmpty()) {
this.error(e.getMessage(), e);
}
}
catch(IOException e) {
log.warn("Listing directory failed:" + e.getMessage());
children.attributes().setReadable(false);
if(this.cache().isEmpty()) {
this.error(e.getMessage(), e);
}
}
return children;
}
/**
* @param query
* @return
* @throws ServiceException
* @throws IOException
*/
private AttributedList<Path> list(DocumentQuery query) throws ServiceException, IOException {
final AttributedList<Path> children = new AttributedList<Path>();
DocumentListFeed pager = this.getSession().getClient().getFeed(query, DocumentListFeed.class);
do {
for(final DocumentListEntry entry : pager.getEntries()) {
log.debug("Resource:" + entry.getResourceId());
boolean include = false;
for(Person person : entry.getAuthors()) {
log.debug("Author of document " + entry.getResourceId() + ":" + person.getEmail());
if(person.getEmail().equals(this.getSession().getHost().getCredentials().getUsername())) {
include = true;
break;
}
}
if(!include) {
log.warn("Skip document with different owner:" + entry);
continue;
}
final String type = entry.getType();
GDPath path = new GDPath(this.getSession(), this.getAbsolute(), entry.getTitle().getPlainText(),
FolderEntry.LABEL.equals(type) ? Path.DIRECTORY_TYPE : Path.FILE_TYPE);
path.setParent(this);
path.setDocumentType(type);
// Download URL
path.setExportUri(((OutOfLineContent) entry.getContent()).getUri());
// Link to Google Docs Editor
path.setDocumentUri(entry.getDocumentLink().getHref());
path.setResourceId(entry.getResourceId());
// Add unique document ID as checksum
path.attributes().setChecksum(entry.getEtag());
if(null != entry.getMediaSource()) {
path.attributes().setSize(entry.getMediaSource().getContentLength());
}
if(entry.getQuotaBytesUsed() > 0) {
path.attributes().setSize(entry.getQuotaBytesUsed());
}
final DateTime lastViewed = entry.getLastViewed();
if(lastViewed != null) {
path.attributes().setAccessedDate(lastViewed.getValue());
}
for(Person person : entry.getAuthors()) {
path.attributes().setOwner(person.getEmail());
}
final DateTime updated = entry.getUpdated();
if(updated != null) {
path.attributes().setModificationDate(updated.getValue());
}
if(children.contains(path.getReference())) {
// Google Docs allows files to be named the same. Not really a duplicate.
path.attributes().setDuplicate(true);
path.setReference(null);
}
// Add to listing
children.add(path);
if(path.attributes().isFile()) {
// Fetch revisions
if(Preferences.instance().getBoolean("google.docs.revisions.enable")) {
try {
final List<RevisionEntry> revisions = this.getSession().getClient().getFeed(
new URL(path.getRevisionsFeed()), RevisionFeed.class).getEntries();
Collections.sort(revisions, new Comparator<RevisionEntry>() {
public int compare(RevisionEntry o1, RevisionEntry o2) {
return o1.getUpdated().compareTo(o2.getUpdated());
}
});
int i = 0;
for(RevisionEntry revisionEntry : revisions) {
GDPath revision = new GDPath(this.getSession(), revisionEntry.getTitle().getPlainText(),
FolderEntry.LABEL.equals(type) ? Path.DIRECTORY_TYPE : Path.FILE_TYPE);
revision.setParent(this);
revision.setDocumentType(type);
revision.setExportUri(((OutOfLineContent) revisionEntry.getContent()).getUri());
final long size = ((OutOfLineContent) revisionEntry.getContent()).getLength();
if(size > 0) {
revision.attributes().setSize(size);
}
revision.attributes().setOwner(revisionEntry.getModifyingUser().getName());
revision.attributes().setModificationDate(revisionEntry.getUpdated().getValue());
// Versioning is enabled if non null.
revision.attributes().setVersionId(revisionEntry.getVersionId());
revision.attributes().setChecksum(revisionEntry.getEtag());
revision.attributes().setRevision(++i);
revision.attributes().setDuplicate(true);
// Add to listing
children.add(revision);
}
}
catch(NotImplementedException e) {
log.error("No revisions available:" + e.getMessage());
}
}
}
}
Link next = pager.getNextLink();
if(null == next) {
// No link to next page.
break;
}
// More pages available
pager = this.getSession().getClient().getFeed(new URL(next.getHref()), DocumentListFeed.class);
}
while(pager.getEntries().size() > 0);
return children;
}
@Override
public String getMimeType() {
if(attributes().isFile()) {
final String exportFormat = getExportFormat(this.getDocumentType());
if(StringUtils.isNotEmpty(exportFormat)) {
return getMimeType(exportFormat);
}
}
return super.getMimeType();
}
@Override
public String getExtension() {
if(attributes().isFile()) {
final String exportFormat = getExportFormat(this.getDocumentType());
if(StringUtils.isNotEmpty(exportFormat)) {
return exportFormat;
}
}
return super.getExtension();
}
@Override
public String getName() {
if(attributes().isFile()) {
final String exportFormat = getExportFormat(this.getDocumentType());
if(StringUtils.isNotEmpty(exportFormat)) {
if(!super.getName().endsWith(exportFormat)) {
return super.getName() + "." + exportFormat;
}
}
}
return super.getName();
}
/**
* @param type The document type
* @return
*/
protected static String getExportFormat(String type) {
if(type.equals(DocumentEntry.LABEL)) {
return Preferences.instance().getProperty("google.docs.export.document");
}
if(type.equals(PresentationEntry.LABEL)) {
return Preferences.instance().getProperty("google.docs.export.presentation");
}
if(type.equals(SpreadsheetEntry.LABEL)) {
return Preferences.instance().getProperty("google.docs.export.spreadsheet");
}
if(type.equals(DOCUMENT_FILE_TYPE)) {
// For files not converted to Google Docs.
// DOCUMENT_FILE_TYPE
log.debug("No output format conversion for document type:" + type);
return null;
}
log.warn("Unknown document type:" + type);
return null;
}
@Override
public void mkdir() {
if(this.attributes().isDirectory()) {
try {
this.getSession().check();
this.getSession().message(MessageFormat.format(Locale.localizedString("Making directory {0}", "Status"),
this.getName()));
DocumentListEntry folder = new FolderEntry();
folder.setTitle(new PlainTextConstruct(this.getName()));
try {
this.getSession().getClient().insert(new URL(((GDPath) this.getParent()).getFolderFeed()), folder);
}
catch(ServiceException e) {
throw new IOException(e.getMessage());
}
this.cache().put(this.getReference(), AttributedList.<Path>emptyList());
// The directory listing is no more current
this.getParent().invalidate();
}
catch(IOException e) {
this.error("Cannot create folder", e);
}
}
}
@Override
public void readUnixPermission() {
throw new UnsupportedOperationException();
}
@Override
public void writeUnixPermission(Permission perm, boolean recursive) {
throw new UnsupportedOperationException();
}
@Override
public void writeTimestamp(long created, long modified, long accessed) {
throw new UnsupportedOperationException();
}
@Override
public void delete() {
try {
if(this.attributes().isDuplicate()) {
log.warn("Cannot delete revision " + this.attributes().getRevision());
return;
}
this.getSession().check();
this.getSession().message(MessageFormat.format(Locale.localizedString("Deleting {0}", "Status"),
this.getName()));
try {
this.getSession().getClient().delete(
new URL(this.getResourceFeed()), this.attributes().getChecksum());
}
catch(ServiceException e) {
throw new IOException(e.getMessage());
}
catch(MalformedURLException e) {
throw new IOException(e.getMessage());
}
// The directory listing is no more current
this.getParent().invalidate();
}
catch(IOException e) {
if(this.attributes().isFile()) {
this.error("Cannot delete file", e);
}
if(this.attributes().isDirectory()) {
this.error("Cannot delete folder", e);
}
}
}
@Override
public void rename(AbstractPath renamed) {
try {
this.getSession().check();
this.getSession().message(MessageFormat.format(Locale.localizedString("Renaming {0} to {1}", "Status"),
this.getName(), renamed));
DocumentListEntry moved = new DocumentListEntry();
moved.setId("https://docs.google.com/feeds/id/" + this.getResourceId());
if(this.getParent().equals(renamed.getParent())) {
// Rename file
moved.setTitle(new PlainTextConstruct(renamed.getName()));
try {
// Move into new folder
this.getSession().getClient().update(new URL(this.getResourceFeed()), moved, this.attributes().getChecksum());
}
catch(ServiceException e) {
throw new IOException(e.getMessage());
}
catch(MalformedURLException e) {
throw new IOException(e.getMessage());
}
}
else {
try {
// Move into new folder
final DocumentListEntry update
= this.getSession().getClient().insert(new URL(((GDPath) renamed.getParent()).getFolderFeed()), moved);
// Move out of previous folder
this.getSession().getClient().delete(new URL((((GDPath) this.getParent()).getFolderFeed()) +
"/" + this.getResourceId()), update.getEtag());
}
catch(ServiceException e) {
throw new IOException(e.getMessage());
}
catch(MalformedURLException e) {
throw new IOException(e.getMessage());
}
}
// The directory listing is no more current
this.getParent().invalidate();
renamed.getParent().invalidate();
}
catch(IOException e) {
if(this.attributes().isFile()) {
this.error("Cannot rename file", e);
}
if(this.attributes().isDirectory()) {
this.error("Cannot rename folder", e);
}
}
}
@Override
public void touch() {
if(this.attributes().isFile()) {
try {
this.getSession().check();
this.getSession().message(MessageFormat.format(Locale.localizedString("Uploading {0}", "Status"),
this.getName()));
DocumentListEntry file = new DocumentEntry();
file.setTitle(new PlainTextConstruct(this.getName()));
try {
this.getSession().getClient().insert(new URL(((GDPath) this.getParent()).getFolderFeed()), file);
}
catch(ServiceException e) {
throw new IOException(e.getMessage());
}
// The directory listing is no more current
this.getParent().invalidate();
}
catch(IOException e) {
this.error("Cannot create file", e);
}
}
}
@Override
public String toHttpURL() {
return this.getDocumentUri();
}
}
| true | true | protected void upload(BandwidthThrottle throttle, StreamListener listener, boolean check) {
try {
if(attributes().isFile()) {
if(check) {
this.getSession().check();
}
this.getSession().message(MessageFormat.format(Locale.localizedString("Uploading {0}", "Status"),
this.getName()));
InputStream in = null;
OutputStream out = null;
try {
final String mime = this.getLocal().getMimeType();
final MediaStreamSource source = new MediaStreamSource(this.getLocal().getInputStream(), mime,
new DateTime(this.attributes().getModificationDate()),
this.getLocal().attributes().getSize());
if(this.exists()) {
// First, fetch entry using the resourceId
URL url = new URL(this.getResourceFeed());
final DocumentListEntry updated = this.getSession().getClient().getEntry(url, DocumentListEntry.class);
updated.setMediaSource(source);
updated.updateMedia(true);
}
else {
final MediaContent content = new MediaContent();
content.setMediaSource(source);
content.setMimeType(new ContentType(mime));
content.setLength(this.getLocal().attributes().getSize());
final DocumentListEntry document = new DocumentListEntry();
document.setContent(content);
document.setTitle(new PlainTextConstruct(this.getName()));
this.getSession().message(MessageFormat.format(Locale.localizedString("Uploading {0}", "Status"),
this.getName()));
status().setResume(false);
String feed = ((GDPath) this.getParent()).getFolderFeed();
StringBuilder url = new StringBuilder(feed);
if(this.isOcrSupported()) {
// Image file type
url.append("?ocr=").append(Preferences.instance().getProperty("google.docs.upload.ocr"));
}
else if(this.isConversionSupported()) {
// Convertible to Google Docs file type
url.append("?convert=").append(Preferences.instance().getProperty("google.docs.upload.convert"));
}
Service.GDataRequest request = null;
try {
// Write as MIME multipart containing the entry and media. Use the
// content type from the multipart since this contains auto-generated
// boundary attributes.
final MediaMultipart multipart = new MediaMultipart(document, document.getMediaSource());
request = this.getSession().getClient().createRequest(
Service.GDataRequest.RequestType.INSERT, new URL(url.toString()),
new ContentType(multipart.getContentType()));
if(request instanceof HttpGDataRequest) {
// No internal buffering of request with a known content length
// Size is incorect because of additional MIME header
// ((HttpGDataRequest)request).getConnection().setFixedLengthStreamingMode(
// (int) this.getLocal().attributes().getSize()
// );
// Use chunked upload with default chunk size.
((HttpGDataRequest) request).getConnection().setChunkedStreamingMode(0);
}
out = request.getRequestStream();
final PipedOutputStream pipe = new PipedOutputStream();
in = new PipedInputStream(pipe);
ThreadPool.instance().execute(new Runnable() {
public void run() {
try {
multipart.writeTo(pipe);
pipe.flush();
pipe.close();
}
catch(IOException e) {
log.error(e.getMessage());
}
catch(MessagingException e) {
log.error(e.getMessage());
}
}
});
this.upload(out, in, throttle, listener);
// Parse response for HTTP error message.
try {
request.execute();
}
catch(ServiceException e) {
this.status().setComplete(false);
throw e;
}
}
catch(MessagingException e) {
throw new ServiceException(
CoreErrorDomain.ERR.cantWriteMimeMultipart, e);
}
finally {
if(request != null) {
request.end();
}
}
}
}
finally {
IOUtils.closeQuietly(in);
IOUtils.closeQuietly(out);
}
}
}
catch(ServiceException e) {
this.error("Upload failed", e);
}
catch(IOException e) {
this.error("Upload failed", e);
}
}
| protected void upload(BandwidthThrottle throttle, StreamListener listener, boolean check) {
try {
if(attributes().isFile()) {
if(check) {
this.getSession().check();
}
this.getSession().message(MessageFormat.format(Locale.localizedString("Uploading {0}", "Status"),
this.getName()));
InputStream in = null;
OutputStream out = null;
try {
final String mime = this.getLocal().getMimeType();
final MediaStreamSource source = new MediaStreamSource(this.getLocal().getInputStream(), mime,
new DateTime(this.attributes().getModificationDate()),
this.getLocal().attributes().getSize());
if(this.exists()) {
// First, fetch entry using the resourceId
URL url = new URL(this.getResourceFeed());
final DocumentListEntry updated = this.getSession().getClient().getEntry(url, DocumentListEntry.class);
updated.setMediaSource(source);
updated.updateMedia(true);
}
else {
final MediaContent content = new MediaContent();
content.setMediaSource(source);
content.setMimeType(new ContentType(mime));
content.setLength(this.getLocal().attributes().getSize());
final DocumentListEntry document = new DocumentListEntry();
document.setContent(content);
document.setTitle(new PlainTextConstruct(this.getName()));
this.getSession().message(MessageFormat.format(Locale.localizedString("Uploading {0}", "Status"),
this.getName()));
status().setResume(false);
String feed = ((GDPath) this.getParent()).getFolderFeed();
StringBuilder url = new StringBuilder(feed);
if(this.isOcrSupported()) {
// Image file type
url.append("?ocr=").append(Preferences.instance().getProperty("google.docs.upload.ocr"));
}
else if(this.isConversionSupported()) {
// Convertible to Google Docs file type
url.append("?convert=").append(Preferences.instance().getProperty("google.docs.upload.convert"));
}
Service.GDataRequest request = null;
try {
// Write as MIME multipart containing the entry and media. Use the
// content type from the multipart since this contains auto-generated
// boundary attributes.
final MediaMultipart multipart = new MediaMultipart(document, document.getMediaSource());
request = this.getSession().getClient().createRequest(
Service.GDataRequest.RequestType.INSERT, new URL(url.toString()),
new ContentType(multipart.getContentType()));
if(request instanceof HttpGDataRequest) {
// No internal buffering of request with a known content length
// Size is incorect because of additional MIME header
// ((HttpGDataRequest)request).getConnection().setFixedLengthStreamingMode(
// (int) this.getLocal().attributes().getSize()
// );
// Use chunked upload with default chunk size.
((HttpGDataRequest) request).getConnection().setChunkedStreamingMode(0);
}
request.setHeader("Expect", "100-Continue");
out = request.getRequestStream();
final PipedOutputStream pipe = new PipedOutputStream();
in = new PipedInputStream(pipe);
ThreadPool.instance().execute(new Runnable() {
public void run() {
try {
multipart.writeTo(pipe);
pipe.flush();
pipe.close();
}
catch(IOException e) {
log.error(e.getMessage());
}
catch(MessagingException e) {
log.error(e.getMessage());
}
}
});
this.upload(out, in, throttle, listener);
// Parse response for HTTP error message.
try {
request.execute();
}
catch(ServiceException e) {
this.status().setComplete(false);
throw e;
}
}
catch(MessagingException e) {
throw new ServiceException(
CoreErrorDomain.ERR.cantWriteMimeMultipart, e);
}
finally {
if(request != null) {
request.end();
}
}
}
}
finally {
IOUtils.closeQuietly(in);
IOUtils.closeQuietly(out);
}
}
}
catch(ServiceException e) {
this.error("Upload failed", e);
}
catch(IOException e) {
this.error("Upload failed", e);
}
}
|
diff --git a/src/main/java/com/miraclem4n/mchat/api/Parser.java b/src/main/java/com/miraclem4n/mchat/api/Parser.java
index ff868bb..4c9a482 100644
--- a/src/main/java/com/miraclem4n/mchat/api/Parser.java
+++ b/src/main/java/com/miraclem4n/mchat/api/Parser.java
@@ -1,522 +1,522 @@
package com.miraclem4n.mchat.api;
import com.herocraftonline.heroes.Heroes;
import com.herocraftonline.heroes.characters.Hero;
import com.herocraftonline.heroes.characters.classes.HeroClass;
import com.herocraftonline.heroes.util.Messaging;
import com.miraclem4n.mchat.MChat;
import com.miraclem4n.mchat.configs.CensorUtil;
import com.miraclem4n.mchat.types.EventType;
import com.miraclem4n.mchat.types.IndicatorType;
import com.miraclem4n.mchat.types.InfoType;
import com.miraclem4n.mchat.types.config.ConfigType;
import com.miraclem4n.mchat.types.config.LocaleType;
import com.miraclem4n.mchat.util.MessageUtil;
import com.palmergames.bukkit.towny.TownyFormatter;
import com.palmergames.bukkit.towny.object.Nation;
import com.palmergames.bukkit.towny.object.Resident;
import com.palmergames.bukkit.towny.object.Town;
import com.palmergames.bukkit.towny.object.TownyUniverse;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Parser {
// Heroes
public static Boolean heroesB;
public static Heroes heroes;
// Towny
public static Boolean townyB;
public static void initialize(MChat instance) {
heroesB = instance.heroesB;
heroes = instance.heroes;
townyB = instance.townyB;
}
/**
* Core Formatting
* @param pName Name of Player being reflected upon.
* @param world Player's World.
* @param msg Message being displayed.
* @param format Resulting Format.
* @return Formatted Message.
*/
public static String parseMessage(String pName, String world, String msg, String format) {
Object prefix = Reader.getRawPrefix(pName, InfoType.USER, world);
Object suffix = Reader.getRawSuffix(pName, InfoType.USER, world);
Object group = Reader.getRawGroup(pName, InfoType.USER, world);
String vI = ConfigType.MCHAT_VAR_INDICATOR.getString();
if (msg == null)
msg = "";
if (prefix == null)
prefix = "";
if (suffix == null)
suffix = "";
if (group == null)
group = "";
// Heroes Vars
String hSClass = "";
String hClass = "";
String hHealth = "";
String hHBar = "";
String hMana = "";
String hMBar = "";
String hParty = "";
String hMastered = "";
String hLevel = "";
String hSLevel = "";
String hExp = "";
String hSExp = "";
String hEBar = "";
String hSEBar = "";
// Towny Vars
String tTown = "";
String tTownName = "";
String tTitle = "";
String tSurname = "";
String tResidentName = "";
String tPrefix = "";
String tNamePrefix = "";
String tPostfix = "";
String tNamePostfix = "";
String tNation = "";
String tNationName = "";
String tNationTag = "";
// Location
Double locX = (double) randomNumber(-100, 100);
Double locY = (double) randomNumber(-100, 100);
Double locZ = (double) randomNumber(-100, 100);
String loc = ("X: " + locX + ", " + "Y: " + locY + ", " + "Z: " + locZ);
// Health
String healthbar = "";
String health = String.valueOf(randomNumber(1, 20));
// World
String pWorld = "";
// 1.8 Vars
String hungerLevel = String.valueOf(randomNumber(0, 20));
String hungerBar = API.createBasicBar(randomNumber(0, 20), 20, 10);
String level = String.valueOf(randomNumber(1, 2));
String exp = String.valueOf(randomNumber(0, 200))+ "/" + ((randomNumber(1, 2) + 1) * 10);
String expBar = API.createBasicBar(randomNumber(0, 200), ((randomNumber(1, 2) + 1) * 10), 10);
String tExp = String.valueOf(randomNumber(0, 300));
String gMode = String.valueOf(randomNumber(0, 1));
// Time Var
Date now = new Date();
SimpleDateFormat dateFormat = new SimpleDateFormat(LocaleType.FORMAT_DATE.getRaw());
String time = dateFormat.format(now);
// Display Name
String dName = pName;
// Chat Distance Type
String dType = "";
- /*if (MChat.isShouting.get(pName) != null
+ if (MChat.isShouting.get(pName) != null
&& MChat.isShouting.get(pName)) {
dType = LocaleType.FORMAT_SHOUT.getVal();
- } else */if (ConfigType.MCHAT_CHAT_DISTANCE.getDouble() > 0) {
+ } else if (ConfigType.MCHAT_CHAT_DISTANCE.getDouble() > 0) {
dType = LocaleType.FORMAT_LOCAL.getVal();
}
// Chat Distance Type
String sType = "";
if (MChat.isSpying.get(pName) != null
&& MChat.isSpying.get(pName))
sType = LocaleType.FORMAT_SPY.getVal();
// Player Object Stuff
if (Bukkit.getServer().getPlayer(pName) != null) {
Player player = Bukkit.getServer().getPlayer(pName);
// Location
locX = player.getLocation().getX();
locY = player.getLocation().getY();
locZ = player.getLocation().getZ();
loc = ("X: " + locX + ", " + "Y: " + locY + ", " + "Z: " + locZ);
// Health
healthbar = API.createHealthBar(player);
health = String.valueOf(player.getHealth());
// World
pWorld = player.getWorld().getName();
// 1.8 Vars
hungerLevel = String.valueOf(player.getFoodLevel());
hungerBar = API.createBasicBar(player.getFoodLevel(), 20, 10);
level = String.valueOf(player.getLevel());
exp = String.valueOf(player.getExp()) + "/" + ((player.getLevel() + 1) * 10);
expBar = API.createBasicBar(player.getExp(), ((player.getLevel() + 1) * 10), 10);
tExp = String.valueOf(player.getTotalExperience());
gMode = "";
if (player.getGameMode() != null && player.getGameMode().name() != null)
gMode = player.getGameMode().name();
// Display Name
dName = player.getDisplayName();
// Initialize Heroes Vars
if (heroesB) {
Hero hero = heroes.getCharacterManager().getHero(player);
HeroClass heroClass = hero.getHeroClass();
HeroClass heroSClass = hero.getSecondClass();
int hL = hero.getLevel();
int hSL = hero.getLevel(heroSClass);
double hE = hero.getExperience(heroClass);
double hSE = hero.getExperience(heroSClass);
hClass = hero.getHeroClass().getName();
hHealth = String.valueOf(hero.getHealth());
hHBar = Messaging.createHealthBar(hero.getHealth(), hero.getMaxHealth());
hMana = String.valueOf(hero.getMana());
hLevel = String.valueOf(hL);
hExp = String.valueOf(hE);
hEBar = Messaging.createExperienceBar(hero, heroClass);
Integer hMMana = hero.getMaxMana();
if (hMMana != null)
hMBar = Messaging.createManaBar(hero.getMana(), hero.getMaxMana());
if (hero.getParty() != null)
hParty = hero.getParty().toString();
if (heroSClass != null) {
hSClass = heroSClass.getName();
hSLevel = String.valueOf(hSL);
hSExp = String.valueOf(hSE);
hSEBar = Messaging.createExperienceBar(hero, heroSClass);
}
if ((hero.isMaster(heroClass))
&& (heroSClass == null || hero.isMaster(heroSClass)))
hMastered = LocaleType.MESSAGE_HEROES_TRUE.getVal();
else
hMastered = LocaleType.MESSAGE_HEROES_FALSE.getVal();
}
if (townyB) {
try {
Resident resident = TownyUniverse.getDataSource().getResident(pName);
if (resident.hasTown()) {
Town town = resident.getTown();
tTown = town.getName();
tTownName = TownyFormatter.getFormattedTownName(town);
tTitle = resident.getTitle();
tSurname = resident.getSurname();
tResidentName = resident.getFormattedName();
tPrefix = resident.hasTitle() ? resident.getTitle() : TownyFormatter.getNamePrefix(resident);
tNamePrefix = TownyFormatter.getNamePrefix(resident);
tPostfix = resident.hasSurname() ? resident.getSurname() : TownyFormatter.getNamePostfix(resident);
tNamePostfix = TownyFormatter.getNamePostfix(resident);
if (resident.hasNation()) {
Nation nation = town.getNation();
tNation = nation.getName();
tNationName = nation.getFormattedName();
tNationTag = nation.getTag();
}
}
} catch (Exception ignored) {}
}
}
String formatAll = parseVars(format, pName, world);
msg = msg.replaceAll("%", "%%");
formatAll = formatAll.replaceAll("%", "%%");
formatAll = MessageUtil.addColour(formatAll);
if (ConfigType.MCHAT_CAPS_LOCK_RANGE.getInteger() > 0)
msg = fixCaps(msg, ConfigType.MCHAT_CAPS_LOCK_RANGE.getInteger());
if (formatAll == null)
return msg;
if (API.checkPermissions(pName, world, "mchat.coloredchat"))
msg = MessageUtil.addColour(msg);
if (!API.checkPermissions(pName, world, "mchat.censorbypass"))
msg = replaceCensoredWords(msg);
TreeMap<String, Object> fVarMap = new TreeMap<String, Object>();
TreeMap<String, Object> rVarMap = new TreeMap<String, Object>();
TreeMap<String, Object> lVarMap = new TreeMap<String, Object>();
addVar(fVarMap, vI + "mnameformat," + vI + "mnf", LocaleType.FORMAT_NAME.getVal());
addVar(fVarMap, vI + "healthbar," + vI + "hb", healthbar);
addVar(rVarMap, vI + "distancetype," + vI + "dtype", dType);
addVar(rVarMap, vI + "displayname," + vI + "dname," + vI + "dn", dName);
addVar(rVarMap, vI + "experiencebar," + vI + "expb," + vI + "ebar," + vI + "eb", expBar);
addVar(rVarMap, vI + "experience," + vI + "exp", exp);
addVar(rVarMap, vI + "gamemode," + vI + "gm", gMode);
addVar(rVarMap, vI + "group," + vI + "g", group);
addVar(rVarMap, vI + "hungerbar," + vI + "hub", hungerBar);
addVar(rVarMap, vI + "hunger", hungerLevel);
addVar(rVarMap, vI + "health," + vI + "h", health);
addVar(rVarMap, vI + "location," + vI + "loc", loc);
addVar(rVarMap, vI + "level," + vI + "l", level);
addVar(rVarMap, vI + "mname," + vI + "mn", Reader.getMName(pName));
addVar(rVarMap, vI + "pname," + vI + "n", pName);
addVar(rVarMap, vI + "prefix," + vI + "p", prefix);
addVar(rVarMap, vI + "spying," + vI + "spy", sType);
addVar(rVarMap, vI + "suffix," + vI + "s", suffix);
addVar(rVarMap, vI + "totalexp," + vI + "texp," + vI + "te", tExp);
addVar(rVarMap, vI + "time," + vI + "t", time);
addVar(rVarMap, vI + "world," + vI + "w", pWorld);
addVar(rVarMap, vI + "Groupname," + vI + "Gname," + vI + "G", Reader.getGroupName(group.toString()));
addVar(rVarMap, vI + "HClass," + vI + "HC", hClass);
addVar(rVarMap, vI + "HExp," + vI + "HEx", hExp);
addVar(rVarMap, vI + "HEBar," + vI + "HEb", hEBar);
addVar(rVarMap, vI + "HHBar," + vI + "HHB", hHBar);
addVar(rVarMap, vI + "HHealth," + vI + "HH", hHealth);
addVar(rVarMap, vI + "HLevel," + vI + "HL", hLevel);
addVar(rVarMap, vI + "HMastered," + vI + "HMa", hMastered);
addVar(rVarMap, vI + "HMana," + vI + "HMn", hMana);
addVar(rVarMap, vI + "HMBar," + vI + "HMb", hMBar);
addVar(rVarMap, vI + "HParty," + vI + "HPa", hParty);
addVar(rVarMap, vI + "HSecClass," + vI + "HSC", hSClass);
addVar(rVarMap, vI + "HSecExp," + vI + "HSEx", hSExp);
addVar(rVarMap, vI + "HSecEBar," + vI + "HSEb", hSEBar);
addVar(rVarMap, vI + "HSecLevel," + vI + "HSL", hSLevel);
addVar(rVarMap, vI + "town", tTown);
addVar(rVarMap, vI + "townname", tTownName);
addVar(rVarMap, vI + "townysurname", tSurname);
addVar(rVarMap, vI + "townytitle", tTitle);
addVar(rVarMap, vI + "townyresidentname", tResidentName);
addVar(rVarMap, vI + "townyprefix", tPrefix);
addVar(rVarMap, vI + "townynameprefix", tNamePrefix);
addVar(rVarMap, vI + "townypostfix", tPostfix);
addVar(rVarMap, vI + "townynamepostfix", tNamePostfix);
addVar(rVarMap, vI + "townynation", tNation);
addVar(rVarMap, vI + "townynationname", tNationName);
addVar(rVarMap, vI + "townynationtag", tNationTag);
addVar(rVarMap, vI + "Worldname," + vI + "Wname," + vI + "W", Reader.getWorldName(pWorld));
addVar(lVarMap, vI + "message," + vI + "msg," + vI + "m", msg);
formatAll = replaceCustVars(pName, formatAll);
formatAll = replaceVars(formatAll, fVarMap.descendingMap(), true);
formatAll = replaceVars(formatAll, rVarMap.descendingMap(), true);
formatAll = replaceVars(formatAll, lVarMap.descendingMap(), false);
return formatAll;
}
/**
* Chat Formatting
* @param pName Name of Player being reflected upon.
* @param world Name of Player's World.
* @param msg Message being displayed.
* @return Formatted Chat Message.
*/
public static String parseChatMessage(String pName, String world, String msg) {
return parseMessage(pName, world, msg, ConfigType.FORMAT_CHAT.getString());
}
/**
* Player Name Formatting
* @param pName Name of Player being reflected upon.
* @param world Name of Player's World.
* @return Formatted Player Name.
*/
public static String parsePlayerName(String pName, String world) {
return parseMessage(pName, world, "", LocaleType.FORMAT_NAME.getRaw());
}
/**
* Event Message Formatting
* @param pName Name of Player being reflected upon.
* @param world Name of Player's World.
* @return Formatted Event Message.
*/
public static String parseEvent(String pName, String world, EventType type) {
return parseMessage(pName, world, "", API.replace(Reader.getEventMessage(type), "player", parsePlayerName(pName, world), IndicatorType.LOCALE_VAR));
}
/**
* TabbedList Formatting
* @param pName Name of Player being reflected upon.
* @param world Name of Player's World.
* @return Formatted TabbedList Name.
*/
public static String parseTabbedList(String pName, String world) {
return parseMessage(pName, world, "", LocaleType.FORMAT_TABBED_LIST.getRaw());
}
/**
* ListCommand Formatting
* @param pName Name of Player being reflected upon.
* @param world Name of Player's World.
* @return Formatted ListCommand Name.
*/
public static String parseListCmd(String pName, String world) {
return parseMessage(pName, world, "", LocaleType.FORMAT_LIST_CMD.getRaw());
}
/**
* Me Formatting
* @param pName Name of Player being reflected upon.
* @param world Name of Player's World.
* @param msg Message being displayed.
* @return Formatted Me Message.
*/
public static String parseMe(String pName, String world, String msg) {
return parseMessage(pName, world, msg, LocaleType.FORMAT_ME.getRaw());
}
// Misc Stuff
private static TreeMap<String, Object> addVar(TreeMap<String, Object> map, String keys, Object value) {
if (keys.contains(","))
for (String s : keys.split(",")) {
if (s == null || value == null)
continue;
map.put(s, value);
}
else if (value != null)
map.put(keys, value);
return map;
}
private static String fixCaps(String format, Integer range) {
if (range < 1)
return format;
Pattern pattern = Pattern.compile("([A-Z]{" + range + ",300})");
Matcher matcher = pattern.matcher(format);
StringBuffer sb = new StringBuffer();
while (matcher.find())
matcher.appendReplacement(sb, Matcher.quoteReplacement(matcher.group().toLowerCase()));
matcher.appendTail(sb);
format = sb.toString();
return format;
}
private static String parseVars(String format, String pName, String world) {
String vI = "\\" + ConfigType.MCHAT_VAR_INDICATOR.getString();
Pattern pattern = Pattern.compile(vI + "<(.*?)>");
Matcher matcher = pattern.matcher(format);
StringBuffer sb = new StringBuffer();
while (matcher.find()) {
String var = Reader.getRawInfo(pName, InfoType.USER, world, matcher.group(1)).toString();
matcher.appendReplacement(sb, Matcher.quoteReplacement(var));
}
matcher.appendTail(sb);
return sb.toString();
}
private static String replaceVars(String format, Map<String, Object> map, Boolean doColour) {
for (Map.Entry<String, Object> entry : map.entrySet()) {
String value = entry.getValue().toString();
if (doColour)
value = MessageUtil.addColour(value);
format = format.replace(entry.getKey(), value);
}
return format;
}
private static String replaceCustVars(String pName, String format) {
Set<Map.Entry<String, String>> varSet = API.varMap.entrySet();
for (Map.Entry<String, String> entry : varSet) {
String pKey = IndicatorType.CUS_VAR.getValue() + entry.getKey().replace(pName + "|", "");
String value = entry.getValue();
if (format.contains(pKey))
format = format.replace(pKey, MessageUtil.addColour(value));
}
for (Map.Entry<String, String> entry : varSet) {
String gKey = IndicatorType.CUS_VAR.getValue() + entry.getKey().replace("%^global^%|", "");
String value = entry.getValue();
if (format.contains(gKey))
format = format.replace(gKey, MessageUtil.addColour(value));
}
return format;
}
private static String replaceCensoredWords(String msg) {
if (ConfigType.MCHAT_IP_CENSOR.getBoolean())
msg = replacer(msg, "([0-9]{1,3}\\.){3}([0-9]{1,3})", "*.*.*.*");
for (Map.Entry<String, Object> entry : CensorUtil.getConfig().getValues(false).entrySet()) {
String val = entry.getValue().toString();
msg = replacer(msg, "(?i)" + entry.getKey(), val);
}
return msg;
}
private static String replacer(String msg, String regex, String replacement) {
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(msg);
StringBuffer sb = new StringBuffer();
while (matcher.find())
matcher.appendReplacement(sb, Matcher.quoteReplacement(replacement));
matcher.appendTail(sb);
msg = sb.toString();
return msg;
}
private static Integer randomNumber(Integer minValue, Integer maxValue) {
Random random = new Random();
return random.nextInt(maxValue - minValue + 1) + minValue;
}
}
| false | true | public static String parseMessage(String pName, String world, String msg, String format) {
Object prefix = Reader.getRawPrefix(pName, InfoType.USER, world);
Object suffix = Reader.getRawSuffix(pName, InfoType.USER, world);
Object group = Reader.getRawGroup(pName, InfoType.USER, world);
String vI = ConfigType.MCHAT_VAR_INDICATOR.getString();
if (msg == null)
msg = "";
if (prefix == null)
prefix = "";
if (suffix == null)
suffix = "";
if (group == null)
group = "";
// Heroes Vars
String hSClass = "";
String hClass = "";
String hHealth = "";
String hHBar = "";
String hMana = "";
String hMBar = "";
String hParty = "";
String hMastered = "";
String hLevel = "";
String hSLevel = "";
String hExp = "";
String hSExp = "";
String hEBar = "";
String hSEBar = "";
// Towny Vars
String tTown = "";
String tTownName = "";
String tTitle = "";
String tSurname = "";
String tResidentName = "";
String tPrefix = "";
String tNamePrefix = "";
String tPostfix = "";
String tNamePostfix = "";
String tNation = "";
String tNationName = "";
String tNationTag = "";
// Location
Double locX = (double) randomNumber(-100, 100);
Double locY = (double) randomNumber(-100, 100);
Double locZ = (double) randomNumber(-100, 100);
String loc = ("X: " + locX + ", " + "Y: " + locY + ", " + "Z: " + locZ);
// Health
String healthbar = "";
String health = String.valueOf(randomNumber(1, 20));
// World
String pWorld = "";
// 1.8 Vars
String hungerLevel = String.valueOf(randomNumber(0, 20));
String hungerBar = API.createBasicBar(randomNumber(0, 20), 20, 10);
String level = String.valueOf(randomNumber(1, 2));
String exp = String.valueOf(randomNumber(0, 200))+ "/" + ((randomNumber(1, 2) + 1) * 10);
String expBar = API.createBasicBar(randomNumber(0, 200), ((randomNumber(1, 2) + 1) * 10), 10);
String tExp = String.valueOf(randomNumber(0, 300));
String gMode = String.valueOf(randomNumber(0, 1));
// Time Var
Date now = new Date();
SimpleDateFormat dateFormat = new SimpleDateFormat(LocaleType.FORMAT_DATE.getRaw());
String time = dateFormat.format(now);
// Display Name
String dName = pName;
// Chat Distance Type
String dType = "";
/*if (MChat.isShouting.get(pName) != null
&& MChat.isShouting.get(pName)) {
dType = LocaleType.FORMAT_SHOUT.getVal();
} else */if (ConfigType.MCHAT_CHAT_DISTANCE.getDouble() > 0) {
dType = LocaleType.FORMAT_LOCAL.getVal();
}
// Chat Distance Type
String sType = "";
if (MChat.isSpying.get(pName) != null
&& MChat.isSpying.get(pName))
sType = LocaleType.FORMAT_SPY.getVal();
// Player Object Stuff
if (Bukkit.getServer().getPlayer(pName) != null) {
Player player = Bukkit.getServer().getPlayer(pName);
// Location
locX = player.getLocation().getX();
locY = player.getLocation().getY();
locZ = player.getLocation().getZ();
loc = ("X: " + locX + ", " + "Y: " + locY + ", " + "Z: " + locZ);
// Health
healthbar = API.createHealthBar(player);
health = String.valueOf(player.getHealth());
// World
pWorld = player.getWorld().getName();
// 1.8 Vars
hungerLevel = String.valueOf(player.getFoodLevel());
hungerBar = API.createBasicBar(player.getFoodLevel(), 20, 10);
level = String.valueOf(player.getLevel());
exp = String.valueOf(player.getExp()) + "/" + ((player.getLevel() + 1) * 10);
expBar = API.createBasicBar(player.getExp(), ((player.getLevel() + 1) * 10), 10);
tExp = String.valueOf(player.getTotalExperience());
gMode = "";
if (player.getGameMode() != null && player.getGameMode().name() != null)
gMode = player.getGameMode().name();
// Display Name
dName = player.getDisplayName();
// Initialize Heroes Vars
if (heroesB) {
Hero hero = heroes.getCharacterManager().getHero(player);
HeroClass heroClass = hero.getHeroClass();
HeroClass heroSClass = hero.getSecondClass();
int hL = hero.getLevel();
int hSL = hero.getLevel(heroSClass);
double hE = hero.getExperience(heroClass);
double hSE = hero.getExperience(heroSClass);
hClass = hero.getHeroClass().getName();
hHealth = String.valueOf(hero.getHealth());
hHBar = Messaging.createHealthBar(hero.getHealth(), hero.getMaxHealth());
hMana = String.valueOf(hero.getMana());
hLevel = String.valueOf(hL);
hExp = String.valueOf(hE);
hEBar = Messaging.createExperienceBar(hero, heroClass);
Integer hMMana = hero.getMaxMana();
if (hMMana != null)
hMBar = Messaging.createManaBar(hero.getMana(), hero.getMaxMana());
if (hero.getParty() != null)
hParty = hero.getParty().toString();
if (heroSClass != null) {
hSClass = heroSClass.getName();
hSLevel = String.valueOf(hSL);
hSExp = String.valueOf(hSE);
hSEBar = Messaging.createExperienceBar(hero, heroSClass);
}
if ((hero.isMaster(heroClass))
&& (heroSClass == null || hero.isMaster(heroSClass)))
hMastered = LocaleType.MESSAGE_HEROES_TRUE.getVal();
else
hMastered = LocaleType.MESSAGE_HEROES_FALSE.getVal();
}
if (townyB) {
try {
Resident resident = TownyUniverse.getDataSource().getResident(pName);
if (resident.hasTown()) {
Town town = resident.getTown();
tTown = town.getName();
tTownName = TownyFormatter.getFormattedTownName(town);
tTitle = resident.getTitle();
tSurname = resident.getSurname();
tResidentName = resident.getFormattedName();
tPrefix = resident.hasTitle() ? resident.getTitle() : TownyFormatter.getNamePrefix(resident);
tNamePrefix = TownyFormatter.getNamePrefix(resident);
tPostfix = resident.hasSurname() ? resident.getSurname() : TownyFormatter.getNamePostfix(resident);
tNamePostfix = TownyFormatter.getNamePostfix(resident);
if (resident.hasNation()) {
Nation nation = town.getNation();
tNation = nation.getName();
tNationName = nation.getFormattedName();
tNationTag = nation.getTag();
}
}
} catch (Exception ignored) {}
}
}
String formatAll = parseVars(format, pName, world);
msg = msg.replaceAll("%", "%%");
formatAll = formatAll.replaceAll("%", "%%");
formatAll = MessageUtil.addColour(formatAll);
if (ConfigType.MCHAT_CAPS_LOCK_RANGE.getInteger() > 0)
msg = fixCaps(msg, ConfigType.MCHAT_CAPS_LOCK_RANGE.getInteger());
if (formatAll == null)
return msg;
if (API.checkPermissions(pName, world, "mchat.coloredchat"))
msg = MessageUtil.addColour(msg);
if (!API.checkPermissions(pName, world, "mchat.censorbypass"))
msg = replaceCensoredWords(msg);
TreeMap<String, Object> fVarMap = new TreeMap<String, Object>();
TreeMap<String, Object> rVarMap = new TreeMap<String, Object>();
TreeMap<String, Object> lVarMap = new TreeMap<String, Object>();
addVar(fVarMap, vI + "mnameformat," + vI + "mnf", LocaleType.FORMAT_NAME.getVal());
addVar(fVarMap, vI + "healthbar," + vI + "hb", healthbar);
addVar(rVarMap, vI + "distancetype," + vI + "dtype", dType);
addVar(rVarMap, vI + "displayname," + vI + "dname," + vI + "dn", dName);
addVar(rVarMap, vI + "experiencebar," + vI + "expb," + vI + "ebar," + vI + "eb", expBar);
addVar(rVarMap, vI + "experience," + vI + "exp", exp);
addVar(rVarMap, vI + "gamemode," + vI + "gm", gMode);
addVar(rVarMap, vI + "group," + vI + "g", group);
addVar(rVarMap, vI + "hungerbar," + vI + "hub", hungerBar);
addVar(rVarMap, vI + "hunger", hungerLevel);
addVar(rVarMap, vI + "health," + vI + "h", health);
addVar(rVarMap, vI + "location," + vI + "loc", loc);
addVar(rVarMap, vI + "level," + vI + "l", level);
addVar(rVarMap, vI + "mname," + vI + "mn", Reader.getMName(pName));
addVar(rVarMap, vI + "pname," + vI + "n", pName);
addVar(rVarMap, vI + "prefix," + vI + "p", prefix);
addVar(rVarMap, vI + "spying," + vI + "spy", sType);
addVar(rVarMap, vI + "suffix," + vI + "s", suffix);
addVar(rVarMap, vI + "totalexp," + vI + "texp," + vI + "te", tExp);
addVar(rVarMap, vI + "time," + vI + "t", time);
addVar(rVarMap, vI + "world," + vI + "w", pWorld);
addVar(rVarMap, vI + "Groupname," + vI + "Gname," + vI + "G", Reader.getGroupName(group.toString()));
addVar(rVarMap, vI + "HClass," + vI + "HC", hClass);
addVar(rVarMap, vI + "HExp," + vI + "HEx", hExp);
addVar(rVarMap, vI + "HEBar," + vI + "HEb", hEBar);
addVar(rVarMap, vI + "HHBar," + vI + "HHB", hHBar);
addVar(rVarMap, vI + "HHealth," + vI + "HH", hHealth);
addVar(rVarMap, vI + "HLevel," + vI + "HL", hLevel);
addVar(rVarMap, vI + "HMastered," + vI + "HMa", hMastered);
addVar(rVarMap, vI + "HMana," + vI + "HMn", hMana);
addVar(rVarMap, vI + "HMBar," + vI + "HMb", hMBar);
addVar(rVarMap, vI + "HParty," + vI + "HPa", hParty);
addVar(rVarMap, vI + "HSecClass," + vI + "HSC", hSClass);
addVar(rVarMap, vI + "HSecExp," + vI + "HSEx", hSExp);
addVar(rVarMap, vI + "HSecEBar," + vI + "HSEb", hSEBar);
addVar(rVarMap, vI + "HSecLevel," + vI + "HSL", hSLevel);
addVar(rVarMap, vI + "town", tTown);
addVar(rVarMap, vI + "townname", tTownName);
addVar(rVarMap, vI + "townysurname", tSurname);
addVar(rVarMap, vI + "townytitle", tTitle);
addVar(rVarMap, vI + "townyresidentname", tResidentName);
addVar(rVarMap, vI + "townyprefix", tPrefix);
addVar(rVarMap, vI + "townynameprefix", tNamePrefix);
addVar(rVarMap, vI + "townypostfix", tPostfix);
addVar(rVarMap, vI + "townynamepostfix", tNamePostfix);
addVar(rVarMap, vI + "townynation", tNation);
addVar(rVarMap, vI + "townynationname", tNationName);
addVar(rVarMap, vI + "townynationtag", tNationTag);
addVar(rVarMap, vI + "Worldname," + vI + "Wname," + vI + "W", Reader.getWorldName(pWorld));
addVar(lVarMap, vI + "message," + vI + "msg," + vI + "m", msg);
formatAll = replaceCustVars(pName, formatAll);
formatAll = replaceVars(formatAll, fVarMap.descendingMap(), true);
formatAll = replaceVars(formatAll, rVarMap.descendingMap(), true);
formatAll = replaceVars(formatAll, lVarMap.descendingMap(), false);
return formatAll;
}
| public static String parseMessage(String pName, String world, String msg, String format) {
Object prefix = Reader.getRawPrefix(pName, InfoType.USER, world);
Object suffix = Reader.getRawSuffix(pName, InfoType.USER, world);
Object group = Reader.getRawGroup(pName, InfoType.USER, world);
String vI = ConfigType.MCHAT_VAR_INDICATOR.getString();
if (msg == null)
msg = "";
if (prefix == null)
prefix = "";
if (suffix == null)
suffix = "";
if (group == null)
group = "";
// Heroes Vars
String hSClass = "";
String hClass = "";
String hHealth = "";
String hHBar = "";
String hMana = "";
String hMBar = "";
String hParty = "";
String hMastered = "";
String hLevel = "";
String hSLevel = "";
String hExp = "";
String hSExp = "";
String hEBar = "";
String hSEBar = "";
// Towny Vars
String tTown = "";
String tTownName = "";
String tTitle = "";
String tSurname = "";
String tResidentName = "";
String tPrefix = "";
String tNamePrefix = "";
String tPostfix = "";
String tNamePostfix = "";
String tNation = "";
String tNationName = "";
String tNationTag = "";
// Location
Double locX = (double) randomNumber(-100, 100);
Double locY = (double) randomNumber(-100, 100);
Double locZ = (double) randomNumber(-100, 100);
String loc = ("X: " + locX + ", " + "Y: " + locY + ", " + "Z: " + locZ);
// Health
String healthbar = "";
String health = String.valueOf(randomNumber(1, 20));
// World
String pWorld = "";
// 1.8 Vars
String hungerLevel = String.valueOf(randomNumber(0, 20));
String hungerBar = API.createBasicBar(randomNumber(0, 20), 20, 10);
String level = String.valueOf(randomNumber(1, 2));
String exp = String.valueOf(randomNumber(0, 200))+ "/" + ((randomNumber(1, 2) + 1) * 10);
String expBar = API.createBasicBar(randomNumber(0, 200), ((randomNumber(1, 2) + 1) * 10), 10);
String tExp = String.valueOf(randomNumber(0, 300));
String gMode = String.valueOf(randomNumber(0, 1));
// Time Var
Date now = new Date();
SimpleDateFormat dateFormat = new SimpleDateFormat(LocaleType.FORMAT_DATE.getRaw());
String time = dateFormat.format(now);
// Display Name
String dName = pName;
// Chat Distance Type
String dType = "";
if (MChat.isShouting.get(pName) != null
&& MChat.isShouting.get(pName)) {
dType = LocaleType.FORMAT_SHOUT.getVal();
} else if (ConfigType.MCHAT_CHAT_DISTANCE.getDouble() > 0) {
dType = LocaleType.FORMAT_LOCAL.getVal();
}
// Chat Distance Type
String sType = "";
if (MChat.isSpying.get(pName) != null
&& MChat.isSpying.get(pName))
sType = LocaleType.FORMAT_SPY.getVal();
// Player Object Stuff
if (Bukkit.getServer().getPlayer(pName) != null) {
Player player = Bukkit.getServer().getPlayer(pName);
// Location
locX = player.getLocation().getX();
locY = player.getLocation().getY();
locZ = player.getLocation().getZ();
loc = ("X: " + locX + ", " + "Y: " + locY + ", " + "Z: " + locZ);
// Health
healthbar = API.createHealthBar(player);
health = String.valueOf(player.getHealth());
// World
pWorld = player.getWorld().getName();
// 1.8 Vars
hungerLevel = String.valueOf(player.getFoodLevel());
hungerBar = API.createBasicBar(player.getFoodLevel(), 20, 10);
level = String.valueOf(player.getLevel());
exp = String.valueOf(player.getExp()) + "/" + ((player.getLevel() + 1) * 10);
expBar = API.createBasicBar(player.getExp(), ((player.getLevel() + 1) * 10), 10);
tExp = String.valueOf(player.getTotalExperience());
gMode = "";
if (player.getGameMode() != null && player.getGameMode().name() != null)
gMode = player.getGameMode().name();
// Display Name
dName = player.getDisplayName();
// Initialize Heroes Vars
if (heroesB) {
Hero hero = heroes.getCharacterManager().getHero(player);
HeroClass heroClass = hero.getHeroClass();
HeroClass heroSClass = hero.getSecondClass();
int hL = hero.getLevel();
int hSL = hero.getLevel(heroSClass);
double hE = hero.getExperience(heroClass);
double hSE = hero.getExperience(heroSClass);
hClass = hero.getHeroClass().getName();
hHealth = String.valueOf(hero.getHealth());
hHBar = Messaging.createHealthBar(hero.getHealth(), hero.getMaxHealth());
hMana = String.valueOf(hero.getMana());
hLevel = String.valueOf(hL);
hExp = String.valueOf(hE);
hEBar = Messaging.createExperienceBar(hero, heroClass);
Integer hMMana = hero.getMaxMana();
if (hMMana != null)
hMBar = Messaging.createManaBar(hero.getMana(), hero.getMaxMana());
if (hero.getParty() != null)
hParty = hero.getParty().toString();
if (heroSClass != null) {
hSClass = heroSClass.getName();
hSLevel = String.valueOf(hSL);
hSExp = String.valueOf(hSE);
hSEBar = Messaging.createExperienceBar(hero, heroSClass);
}
if ((hero.isMaster(heroClass))
&& (heroSClass == null || hero.isMaster(heroSClass)))
hMastered = LocaleType.MESSAGE_HEROES_TRUE.getVal();
else
hMastered = LocaleType.MESSAGE_HEROES_FALSE.getVal();
}
if (townyB) {
try {
Resident resident = TownyUniverse.getDataSource().getResident(pName);
if (resident.hasTown()) {
Town town = resident.getTown();
tTown = town.getName();
tTownName = TownyFormatter.getFormattedTownName(town);
tTitle = resident.getTitle();
tSurname = resident.getSurname();
tResidentName = resident.getFormattedName();
tPrefix = resident.hasTitle() ? resident.getTitle() : TownyFormatter.getNamePrefix(resident);
tNamePrefix = TownyFormatter.getNamePrefix(resident);
tPostfix = resident.hasSurname() ? resident.getSurname() : TownyFormatter.getNamePostfix(resident);
tNamePostfix = TownyFormatter.getNamePostfix(resident);
if (resident.hasNation()) {
Nation nation = town.getNation();
tNation = nation.getName();
tNationName = nation.getFormattedName();
tNationTag = nation.getTag();
}
}
} catch (Exception ignored) {}
}
}
String formatAll = parseVars(format, pName, world);
msg = msg.replaceAll("%", "%%");
formatAll = formatAll.replaceAll("%", "%%");
formatAll = MessageUtil.addColour(formatAll);
if (ConfigType.MCHAT_CAPS_LOCK_RANGE.getInteger() > 0)
msg = fixCaps(msg, ConfigType.MCHAT_CAPS_LOCK_RANGE.getInteger());
if (formatAll == null)
return msg;
if (API.checkPermissions(pName, world, "mchat.coloredchat"))
msg = MessageUtil.addColour(msg);
if (!API.checkPermissions(pName, world, "mchat.censorbypass"))
msg = replaceCensoredWords(msg);
TreeMap<String, Object> fVarMap = new TreeMap<String, Object>();
TreeMap<String, Object> rVarMap = new TreeMap<String, Object>();
TreeMap<String, Object> lVarMap = new TreeMap<String, Object>();
addVar(fVarMap, vI + "mnameformat," + vI + "mnf", LocaleType.FORMAT_NAME.getVal());
addVar(fVarMap, vI + "healthbar," + vI + "hb", healthbar);
addVar(rVarMap, vI + "distancetype," + vI + "dtype", dType);
addVar(rVarMap, vI + "displayname," + vI + "dname," + vI + "dn", dName);
addVar(rVarMap, vI + "experiencebar," + vI + "expb," + vI + "ebar," + vI + "eb", expBar);
addVar(rVarMap, vI + "experience," + vI + "exp", exp);
addVar(rVarMap, vI + "gamemode," + vI + "gm", gMode);
addVar(rVarMap, vI + "group," + vI + "g", group);
addVar(rVarMap, vI + "hungerbar," + vI + "hub", hungerBar);
addVar(rVarMap, vI + "hunger", hungerLevel);
addVar(rVarMap, vI + "health," + vI + "h", health);
addVar(rVarMap, vI + "location," + vI + "loc", loc);
addVar(rVarMap, vI + "level," + vI + "l", level);
addVar(rVarMap, vI + "mname," + vI + "mn", Reader.getMName(pName));
addVar(rVarMap, vI + "pname," + vI + "n", pName);
addVar(rVarMap, vI + "prefix," + vI + "p", prefix);
addVar(rVarMap, vI + "spying," + vI + "spy", sType);
addVar(rVarMap, vI + "suffix," + vI + "s", suffix);
addVar(rVarMap, vI + "totalexp," + vI + "texp," + vI + "te", tExp);
addVar(rVarMap, vI + "time," + vI + "t", time);
addVar(rVarMap, vI + "world," + vI + "w", pWorld);
addVar(rVarMap, vI + "Groupname," + vI + "Gname," + vI + "G", Reader.getGroupName(group.toString()));
addVar(rVarMap, vI + "HClass," + vI + "HC", hClass);
addVar(rVarMap, vI + "HExp," + vI + "HEx", hExp);
addVar(rVarMap, vI + "HEBar," + vI + "HEb", hEBar);
addVar(rVarMap, vI + "HHBar," + vI + "HHB", hHBar);
addVar(rVarMap, vI + "HHealth," + vI + "HH", hHealth);
addVar(rVarMap, vI + "HLevel," + vI + "HL", hLevel);
addVar(rVarMap, vI + "HMastered," + vI + "HMa", hMastered);
addVar(rVarMap, vI + "HMana," + vI + "HMn", hMana);
addVar(rVarMap, vI + "HMBar," + vI + "HMb", hMBar);
addVar(rVarMap, vI + "HParty," + vI + "HPa", hParty);
addVar(rVarMap, vI + "HSecClass," + vI + "HSC", hSClass);
addVar(rVarMap, vI + "HSecExp," + vI + "HSEx", hSExp);
addVar(rVarMap, vI + "HSecEBar," + vI + "HSEb", hSEBar);
addVar(rVarMap, vI + "HSecLevel," + vI + "HSL", hSLevel);
addVar(rVarMap, vI + "town", tTown);
addVar(rVarMap, vI + "townname", tTownName);
addVar(rVarMap, vI + "townysurname", tSurname);
addVar(rVarMap, vI + "townytitle", tTitle);
addVar(rVarMap, vI + "townyresidentname", tResidentName);
addVar(rVarMap, vI + "townyprefix", tPrefix);
addVar(rVarMap, vI + "townynameprefix", tNamePrefix);
addVar(rVarMap, vI + "townypostfix", tPostfix);
addVar(rVarMap, vI + "townynamepostfix", tNamePostfix);
addVar(rVarMap, vI + "townynation", tNation);
addVar(rVarMap, vI + "townynationname", tNationName);
addVar(rVarMap, vI + "townynationtag", tNationTag);
addVar(rVarMap, vI + "Worldname," + vI + "Wname," + vI + "W", Reader.getWorldName(pWorld));
addVar(lVarMap, vI + "message," + vI + "msg," + vI + "m", msg);
formatAll = replaceCustVars(pName, formatAll);
formatAll = replaceVars(formatAll, fVarMap.descendingMap(), true);
formatAll = replaceVars(formatAll, rVarMap.descendingMap(), true);
formatAll = replaceVars(formatAll, lVarMap.descendingMap(), false);
return formatAll;
}
|
diff --git a/src/garin/artemiy/sqlitesimple/example/MainApplication.java b/src/garin/artemiy/sqlitesimple/example/MainApplication.java
index 63d127a..2165cba 100644
--- a/src/garin/artemiy/sqlitesimple/example/MainApplication.java
+++ b/src/garin/artemiy/sqlitesimple/example/MainApplication.java
@@ -1,31 +1,31 @@
package garin.artemiy.sqlitesimple.example;
import android.app.Application;
import android.util.Log;
import garin.artemiy.sqlitesimple.example.model.Record;
import garin.artemiy.sqlitesimple.example.model.Test;
import garin.artemiy.sqlitesimple.example.operator.TestDAO;
import garin.artemiy.sqlitesimple.library.SQLiteSimple;
/**
* author: Artemiy Garin
* date: 13.12.12
*/
public class MainApplication extends Application {
@Override
public void onCreate() {
super.onCreate();
- SQLiteSimple databaseSimple = new SQLiteSimple(this, 2);
+ SQLiteSimple databaseSimple = new SQLiteSimple(this);
databaseSimple.create(Record.class);
SQLiteSimple localSimple = new SQLiteSimple(this, "test.sqlite");
localSimple.create(Test.class);
TestDAO testDAO = new TestDAO(this);
Log.d("SQLiteSimple: Local database rows", String.valueOf(testDAO.getCount()));
}
}
| true | true | public void onCreate() {
super.onCreate();
SQLiteSimple databaseSimple = new SQLiteSimple(this, 2);
databaseSimple.create(Record.class);
SQLiteSimple localSimple = new SQLiteSimple(this, "test.sqlite");
localSimple.create(Test.class);
TestDAO testDAO = new TestDAO(this);
Log.d("SQLiteSimple: Local database rows", String.valueOf(testDAO.getCount()));
}
| public void onCreate() {
super.onCreate();
SQLiteSimple databaseSimple = new SQLiteSimple(this);
databaseSimple.create(Record.class);
SQLiteSimple localSimple = new SQLiteSimple(this, "test.sqlite");
localSimple.create(Test.class);
TestDAO testDAO = new TestDAO(this);
Log.d("SQLiteSimple: Local database rows", String.valueOf(testDAO.getCount()));
}
|
diff --git a/SoarSuite/Environments/JavaTankSoar/source/tanksoar/Tank.java b/SoarSuite/Environments/JavaTankSoar/source/tanksoar/Tank.java
index 4f8e7fd3b..af776b3da 100644
--- a/SoarSuite/Environments/JavaTankSoar/source/tanksoar/Tank.java
+++ b/SoarSuite/Environments/JavaTankSoar/source/tanksoar/Tank.java
@@ -1,622 +1,642 @@
package tanksoar;
import simulation.*;
import utilities.*;
import sml.*;
public class Tank extends WorldEntity {
private final static String kMoveID = "move";
private final static String kDirectionID = "direction";
private final static String kBackwardID = "backward";
private final static String kForwardID = "forward";
public final static String kLeftID = "left";
public final static String kRightID = "right";
private final static String kFireID = "fire";
private final static String kRadarID = "radar";
private final static String kSwitchID = "switch";
//private final static String kOff = "off";
private final static String kOn = "on";
private final static String kRadarPowerID = "radar-power";
private final static String kSettingID = "setting";
private final static String kShieldsID = "shields";
private final static String kRotateID = "rotate";
private TankSoarCell[][] radarCells = new TankSoarCell[kRadarWidth][kRadarHeight];
public final static int kRadarWidth = 3;
public final static int kRadarHeight = 14;
private final static int kSheildEnergyUsage = 20;
private final static int kMissileHealthDamage = 400;
private final static int kMissileEnergyDamage = 250;
private final static int kCollisionHealthDamage = 100;
private final static int kMaximumEnergy = 1000;
private final static int kMaximumHealth = 1000;
private RelativeDirections m_RD = new RelativeDirections();
private TankSoarWorld m_World;
private String m_InitialFacing;
private MapPoint m_InitialLocation;
private InputLinkManager m_ILM;
private MoveInfo m_LastMove;
private int m_RWaves;
private int m_Missiles;
private boolean m_ShieldStatus;
private int m_Health;
private int m_Energy;
private int m_RadarPower;
private boolean m_RadarSwitch;
private int m_RadarDistance;
private int m_SmellDistance;
private String m_SmellColor;
private int m_InitialEnergy = 1000;
private int m_InitialHealth = 1000;
private int m_InitialMissiles = 15;
public Tank(Agent agent, String productions, String color, MapPoint location, String facing, int energy, int health, int missiles, TankSoarWorld world) {
super(agent, productions, color, location);
m_World = world;
if (facing == null) {
facing = WorldEntity.kNorth;
}
m_InitialFacing = facing;
m_InitialLocation = location;
if (energy != -1) {
m_InitialEnergy = energy;
}
if (health != -1) {
m_InitialHealth = health;
}
if (missiles != -1) {
m_InitialMissiles = missiles;
}
m_LastMove = new MoveInfo();
if (m_Agent != null) {
m_ILM = new InputLinkManager(m_World, this);
}
reset();
}
public MapPoint getInitialLocation() {
return m_InitialLocation;
}
public void reset() {
m_RadarPower = 0;
m_RadarDistance = 0;
m_SmellDistance = 0;
m_SmellColor = null;
m_RadarSwitch = false;
m_RWaves = 0;
m_Missiles = m_InitialMissiles;
m_ShieldStatus = false;
m_Health = m_InitialHealth;
m_Energy = m_InitialEnergy;
m_LastMove.reset();
m_Facing = m_InitialFacing;
setFacingInt();
m_RD.calculate(getFacingInt());
clearRadar();
if (m_Agent != null) {
m_ILM.clear();
}
}
public boolean getRadarStatus() {
return m_RadarSwitch;
}
public int getRadarSetting() {
return m_RadarPower;
}
// TODO: possibly move calculation in to this class
void setSmell(int distance, String color) {
m_SmellDistance = distance;
m_SmellColor = color;
}
public TankSoarCell[][] getRadarCells() {
return radarCells;
}
public int getRadarDistance() {
return m_RadarDistance;
}
public int getSmellDistance() {
return m_SmellDistance;
}
public String getSmellColor() {
return m_SmellColor;
}
public void humanInput(MoveInfo move) {
assert move != null;
m_LastMove.reset();
m_LastMove = move;
m_RWaves = 0;
// Must check missile count now
if (m_LastMove.fire) {
if (m_Missiles <= 0) {
m_Logger.log(getName() + ": Attempted to fire missle with no missiles.");
m_LastMove.fire = false;
}
}
// Shields must be handled pronto
if (m_LastMove.shields) {
handleShields();
}
if (m_LastMove.rotate) {
rotate(m_LastMove.rotateDirection);
// Do not allow a move if we rotated.
if (m_LastMove.move) {
m_Logger.log("Tried to move with a rotation, rotating only.");
m_LastMove.move = false;
}
}
}
public void readOutputLink() {
m_LastMove.reset();
m_RWaves = 0;
assert m_Agent != null;
int numberOfCommands = m_Agent.GetNumberCommands();
if (numberOfCommands == 0) {
m_Logger.log(getName() + " issued no command.");
return;
}
+ Identifier moveId = null;
for (int i = 0; i < numberOfCommands; ++i) {
Identifier commandId = m_Agent.GetCommand(i);
String commandName = commandId.GetAttribute();
if (commandName.equalsIgnoreCase(kMoveID)) {
if (m_LastMove.move == true) {
m_Logger.log(getName() + ": Detected more than one move command on output link, ignoring.");
+ commandId.AddStatusError();
continue;
}
String moveDirection = commandId.GetParameterValue(kDirectionID);
if (moveDirection == null) {
m_Logger.log(getName() + ": null move direction.");
+ commandId.AddStatusError();
continue;
}
if (moveDirection.equalsIgnoreCase(kForwardID)) {
m_LastMove.moveDirection = m_RD.forward;
} else if (moveDirection.equalsIgnoreCase(kBackwardID)) {
m_LastMove.moveDirection = m_RD.backward;
} else if (moveDirection.equalsIgnoreCase(kLeftID)) {
m_LastMove.moveDirection = m_RD.left;
} else if (moveDirection.equalsIgnoreCase(kRightID)) {
m_LastMove.moveDirection = m_RD.right;
} else {
m_Logger.log(getName() + ": illegal move direction: " + moveDirection);
+ commandId.AddStatusError();
continue;
}
+ moveId = commandId;
m_LastMove.move = true;
} else if (commandName.equalsIgnoreCase(kFireID)) {
if (m_LastMove.fire == true) {
m_Logger.log(getName() + ": Detected more than one fire command on output link, ignoring.");
+ commandId.AddStatusError();
continue;
}
if (m_Missiles > 0) {
m_LastMove.fire = true;
} else {
m_Logger.log(getName() + ": Attempted to fire missle with no missiles.");
+ commandId.AddStatusError();
continue;
}
// Weapon ignored
} else if (commandName.equalsIgnoreCase(kRadarID)) {
if (m_LastMove.radar == true) {
m_Logger.log(getName() + ": Detected more than one radar command on output link, ignoring.");
+ commandId.AddStatusError();
continue;
}
String radarSwitch = commandId.GetParameterValue(kSwitchID);
if (radarSwitch == null) {
m_Logger.log(getName() + ": null radar switch.");
+ commandId.AddStatusError();
continue;
}
m_LastMove.radar = true;
m_LastMove.radarSwitch = radarSwitch.equalsIgnoreCase(kOn) ? true : false;
} else if (commandName.equalsIgnoreCase(kRadarPowerID)) {
if (m_LastMove.radarPower == true) {
m_Logger.log(getName() + ": Detected more than one radar power command on output link, ignoring.");
+ commandId.AddStatusError();
continue;
}
String powerValue = commandId.GetParameterValue(kSettingID);
if (powerValue == null) {
m_Logger.log(getName() + ": null radar power value.");
+ commandId.AddStatusError();
continue;
}
try {
m_LastMove.radarPowerSetting = Integer.decode(powerValue).intValue();
} catch (NumberFormatException e) {
m_Logger.log(getName() + ": Unable to parse radar power setting " + powerValue + ": " + e.getMessage());
+ commandId.AddStatusError();
continue;
}
m_LastMove.radarPower = true;
} else if (commandName.equalsIgnoreCase(kShieldsID)) {
if (m_LastMove.shields == true) {
m_Logger.log(getName() + ": Detected more than one shields command on output link, ignoring.");
+ commandId.AddStatusError();
continue;
}
String shieldsSetting = commandId.GetParameterValue(kSwitchID);
if (shieldsSetting == null) {
m_Logger.log(getName() + ": null shields setting.");
+ commandId.AddStatusError();
continue;
}
m_LastMove.shields = true;
m_LastMove.shieldsSetting = shieldsSetting.equalsIgnoreCase(kOn) ? true : false;
// Shields must be handled pronto
handleShields();
} else if (commandName.equalsIgnoreCase(kRotateID)) {
if (m_LastMove.rotate == true) {
m_Logger.log(getName() + ": Detected more than one rotate command on output link, ignoring.");
+ commandId.AddStatusError();
continue;
}
m_LastMove.rotateDirection = commandId.GetParameterValue(kDirectionID);
if (m_LastMove.rotateDirection == null) {
m_Logger.log(getName() + ": null rotation direction.");
+ commandId.AddStatusError();
continue;
}
m_LastMove.rotate = true;
// Rotation must be handled pronto and never fails.
if (m_LastMove.rotate) {
rotate(m_LastMove.rotateDirection);
}
} else {
m_Logger.log(getName() + ": Unknown command: " + commandName);
+ commandId.AddStatusError();
continue;
}
commandId.AddStatusComplete();
}
m_Agent.ClearOutputLinkChanges();
m_Agent.Commit();
// Do not allow a move if we rotated.
if (m_LastMove.rotate) {
if (m_LastMove.move) {
m_Logger.log("Tried to move with a rotation, rotating only.");
+ assert moveId != null;
+ moveId.AddStatusError();
+ moveId = null;
m_LastMove.move = false;
}
}
}
private void handleShields() {
// Handle shields.
boolean desiredShieldStatus = m_LastMove.shields ? m_LastMove.shieldsSetting : m_ShieldStatus;
boolean enoughPowerForShields = m_Energy >= kSheildEnergyUsage;
// If the agent wants to turn the shield on
if (!m_ShieldStatus && desiredShieldStatus) {
// Turn the shield on if there is enough power.
if (enoughPowerForShields) {
m_ShieldStatus = true;
}
}
// If the agent wants the shield off or there isn't enough power
if ((m_ShieldStatus && !desiredShieldStatus) || !enoughPowerForShields) {
// Turn the shield off.
m_ShieldStatus = false;
}
// Consume shield energy.
if (m_ShieldStatus) {
m_Energy -= kSheildEnergyUsage;
}
}
public void updateSensors(TankSoarWorld world) {
TankSoarCell cell = world.getCell(getLocation());
// Chargers
if (m_Health > 0) {
if (cell.isEnergyRecharger()) {
m_Energy += 250;
m_Energy = m_Energy > kMaximumEnergy ? kMaximumEnergy : m_Energy;
}
if (cell.isHealthRecharger()) {
m_Health += 250;
m_Health = m_Health > kMaximumHealth ? kMaximumHealth : m_Health;
}
}
// Handle radar.
// Figure out desired radar power.
int desiredRadarPower = m_LastMove.radarPower ? m_LastMove.radarPowerSetting : m_RadarPower;
// Never exceed max power
desiredRadarPower = desiredRadarPower > Tank.kRadarHeight ? Tank.kRadarHeight : desiredRadarPower;
// Never exceed current energy usage
desiredRadarPower = desiredRadarPower > m_Energy ? m_Energy : desiredRadarPower;
// If the power setting changed, set it.
if (m_RadarPower != desiredRadarPower) {
m_RadarPower = desiredRadarPower;
}
// Figure out desired radar status
boolean desiredRadarStatus = m_LastMove.radar ? m_LastMove.radarSwitch : m_RadarSwitch;
// If the agent wants to turn the radar on
if (!m_RadarSwitch && desiredRadarStatus) {
// Turn the radar on.
if (m_RadarPower > 0) {
m_RadarSwitch = true;
}
}
// If the agent wants to turn the radar off or there isn't enough power
if ((m_RadarSwitch && !desiredRadarStatus) || (m_RadarPower == 0)) {
// Turn the radar off.
m_RadarSwitch = false;
}
// Consume radar energy.
if (m_RadarSwitch) {
m_Energy -= m_RadarPower;
m_RadarDistance = scan(m_RadarPower);
} else {
clearRadar();
m_RadarDistance = 0;
}
// Missiles
if (m_LastMove.fire) {
m_Missiles -= 1;
}
}
private void clearRadar() {
for (int i = 0; i < kRadarWidth; ++i) {
for (int j = 0; j < kRadarHeight; ++j) {
radarCells[i][j] = null;
}
}
}
private int scan(int setting) {
MapPoint location = new MapPoint(getLocation());
int distance = 0;
for (int i = 0; i <= setting; ++i) {
distance = i;
if (scanCells(i, location) == true) {
// Blocked
clearCells(i, location);
break;
}
// Update for next distance
location.travel(forward());
}
return distance;
}
static final int kRadarLeft = 0;
static final int kRadarCenter = 1;
static final int kRadarRight = 2;
private boolean scanCells(int distance, MapPoint location) {
for (int i = 0; i < Tank.kRadarWidth; ++i) {
// Scan center then left then right
int position = 0;
int relativeDirection = 0;
switch (i) {
case 0:
position = kRadarCenter;
relativeDirection = 0;
break;
default:
case 1:
position = kRadarLeft;
relativeDirection = left();
break;
case 2:
position = kRadarRight;
relativeDirection = right();
break;
}
radarCells[position][distance] = m_World.getCell(location, relativeDirection);
if (!(position == 1 && distance == 0)) {
if (radarCells[position][distance].containsTank()) {
radarCells[position][distance].getTank().setRWaves(backward());
}
}
if ((position == kRadarCenter) && radarCells[position][distance].isBlocked()) {
if ((position != kRadarCenter) || (distance != 0)) {
return true;
}
}
radarCells[position][distance].setRadarTouch();
}
return false;
}
private void clearCells(int initialDistance, MapPoint location) {
for (int j = initialDistance; j < Tank.kRadarHeight; ++j) {
for (int i = 0; i < Tank.kRadarWidth; ++i) {
if ((i == 1) && (j == initialDistance)) {
// skip first center
continue;
}
radarCells[i][j] = null;
}
}
}
public void writeInputLink() {
if (m_Agent != null) {
m_ILM.write();
}
}
public int forward() {
return m_RD.forward;
}
public int backward() {
return m_RD.backward;
}
public int left() {
return m_RD.left;
}
public int right() {
return m_RD.right;
}
public void addMissiles(int numberToAdd) {
m_Missiles += numberToAdd;
}
public int getMissiles() {
return m_Missiles;
}
public int getHealth() {
return m_Health;
}
public void hitBy(Tank attacker, TankSoarCell currentCell) {
// Missile damage
if (m_ShieldStatus) {
m_Energy -= kMissileEnergyDamage;
if (m_Energy < 0) {
m_Energy = 0;
}
} else {
m_Health -= kMissileHealthDamage;
if (m_Health < 0) {
m_Health = 0;
}
}
// Chargers
if (m_Health > 0) {
if (currentCell.isEnergyRecharger()) {
// Instant death
m_Health = 0;
}
if (currentCell.isHealthRecharger()) {
// Instant death
m_Health = 0;
}
}
if (m_Health <= 0) {
adjustPoints(TankSoarWorld.kKillPenalty);
// TODO: multiple missiles!
attacker.adjustPoints(TankSoarWorld.kKillAward);
}
}
public void collide() {
// Collision damage
m_Health -= kCollisionHealthDamage;
if (m_Health < 0) {
m_Health = 0;
}
m_LastMove.move = false;
}
public int getEnergy() {
return m_Energy;
}
public boolean getShieldStatus() {
return m_ShieldStatus;
}
public boolean recentlyMovedOrRotated() {
return m_LastMove.move || m_LastMove.rotate;
}
public boolean recentlyMoved() {
return m_LastMove.move;
}
public boolean recentlyRotated() {
return m_LastMove.rotate;
}
public int lastMoveDirection() {
return m_LastMove.moveDirection;
}
private void rotate(String direction) {
int facing = 0;
if (direction.equalsIgnoreCase(kLeftID)) {
facing = m_RD.left;
} else if (direction.equalsIgnoreCase(kRightID)) {
facing = m_RD.right;
}
switch (facing) {
case kNorthInt:
m_Facing = kNorth;
break;
case kSouthInt:
m_Facing = kSouth;
break;
case kEastInt:
m_Facing = kEast;
break;
case kWestInt:
m_Facing = kWest;
break;
}
setFacingInt();
m_RD.calculate(getFacingInt());
}
public boolean firedMissile() {
return m_LastMove.fire;
}
public int getRWaves() {
return m_RWaves;
}
void setRWaves(int fromDirection) {
m_RWaves |= fromDirection;
}
}
| false | true | public void readOutputLink() {
m_LastMove.reset();
m_RWaves = 0;
assert m_Agent != null;
int numberOfCommands = m_Agent.GetNumberCommands();
if (numberOfCommands == 0) {
m_Logger.log(getName() + " issued no command.");
return;
}
for (int i = 0; i < numberOfCommands; ++i) {
Identifier commandId = m_Agent.GetCommand(i);
String commandName = commandId.GetAttribute();
if (commandName.equalsIgnoreCase(kMoveID)) {
if (m_LastMove.move == true) {
m_Logger.log(getName() + ": Detected more than one move command on output link, ignoring.");
continue;
}
String moveDirection = commandId.GetParameterValue(kDirectionID);
if (moveDirection == null) {
m_Logger.log(getName() + ": null move direction.");
continue;
}
if (moveDirection.equalsIgnoreCase(kForwardID)) {
m_LastMove.moveDirection = m_RD.forward;
} else if (moveDirection.equalsIgnoreCase(kBackwardID)) {
m_LastMove.moveDirection = m_RD.backward;
} else if (moveDirection.equalsIgnoreCase(kLeftID)) {
m_LastMove.moveDirection = m_RD.left;
} else if (moveDirection.equalsIgnoreCase(kRightID)) {
m_LastMove.moveDirection = m_RD.right;
} else {
m_Logger.log(getName() + ": illegal move direction: " + moveDirection);
continue;
}
m_LastMove.move = true;
} else if (commandName.equalsIgnoreCase(kFireID)) {
if (m_LastMove.fire == true) {
m_Logger.log(getName() + ": Detected more than one fire command on output link, ignoring.");
continue;
}
if (m_Missiles > 0) {
m_LastMove.fire = true;
} else {
m_Logger.log(getName() + ": Attempted to fire missle with no missiles.");
continue;
}
// Weapon ignored
} else if (commandName.equalsIgnoreCase(kRadarID)) {
if (m_LastMove.radar == true) {
m_Logger.log(getName() + ": Detected more than one radar command on output link, ignoring.");
continue;
}
String radarSwitch = commandId.GetParameterValue(kSwitchID);
if (radarSwitch == null) {
m_Logger.log(getName() + ": null radar switch.");
continue;
}
m_LastMove.radar = true;
m_LastMove.radarSwitch = radarSwitch.equalsIgnoreCase(kOn) ? true : false;
} else if (commandName.equalsIgnoreCase(kRadarPowerID)) {
if (m_LastMove.radarPower == true) {
m_Logger.log(getName() + ": Detected more than one radar power command on output link, ignoring.");
continue;
}
String powerValue = commandId.GetParameterValue(kSettingID);
if (powerValue == null) {
m_Logger.log(getName() + ": null radar power value.");
continue;
}
try {
m_LastMove.radarPowerSetting = Integer.decode(powerValue).intValue();
} catch (NumberFormatException e) {
m_Logger.log(getName() + ": Unable to parse radar power setting " + powerValue + ": " + e.getMessage());
continue;
}
m_LastMove.radarPower = true;
} else if (commandName.equalsIgnoreCase(kShieldsID)) {
if (m_LastMove.shields == true) {
m_Logger.log(getName() + ": Detected more than one shields command on output link, ignoring.");
continue;
}
String shieldsSetting = commandId.GetParameterValue(kSwitchID);
if (shieldsSetting == null) {
m_Logger.log(getName() + ": null shields setting.");
continue;
}
m_LastMove.shields = true;
m_LastMove.shieldsSetting = shieldsSetting.equalsIgnoreCase(kOn) ? true : false;
// Shields must be handled pronto
handleShields();
} else if (commandName.equalsIgnoreCase(kRotateID)) {
if (m_LastMove.rotate == true) {
m_Logger.log(getName() + ": Detected more than one rotate command on output link, ignoring.");
continue;
}
m_LastMove.rotateDirection = commandId.GetParameterValue(kDirectionID);
if (m_LastMove.rotateDirection == null) {
m_Logger.log(getName() + ": null rotation direction.");
continue;
}
m_LastMove.rotate = true;
// Rotation must be handled pronto and never fails.
if (m_LastMove.rotate) {
rotate(m_LastMove.rotateDirection);
}
} else {
m_Logger.log(getName() + ": Unknown command: " + commandName);
continue;
}
commandId.AddStatusComplete();
}
m_Agent.ClearOutputLinkChanges();
m_Agent.Commit();
// Do not allow a move if we rotated.
if (m_LastMove.rotate) {
if (m_LastMove.move) {
m_Logger.log("Tried to move with a rotation, rotating only.");
m_LastMove.move = false;
}
}
}
| public void readOutputLink() {
m_LastMove.reset();
m_RWaves = 0;
assert m_Agent != null;
int numberOfCommands = m_Agent.GetNumberCommands();
if (numberOfCommands == 0) {
m_Logger.log(getName() + " issued no command.");
return;
}
Identifier moveId = null;
for (int i = 0; i < numberOfCommands; ++i) {
Identifier commandId = m_Agent.GetCommand(i);
String commandName = commandId.GetAttribute();
if (commandName.equalsIgnoreCase(kMoveID)) {
if (m_LastMove.move == true) {
m_Logger.log(getName() + ": Detected more than one move command on output link, ignoring.");
commandId.AddStatusError();
continue;
}
String moveDirection = commandId.GetParameterValue(kDirectionID);
if (moveDirection == null) {
m_Logger.log(getName() + ": null move direction.");
commandId.AddStatusError();
continue;
}
if (moveDirection.equalsIgnoreCase(kForwardID)) {
m_LastMove.moveDirection = m_RD.forward;
} else if (moveDirection.equalsIgnoreCase(kBackwardID)) {
m_LastMove.moveDirection = m_RD.backward;
} else if (moveDirection.equalsIgnoreCase(kLeftID)) {
m_LastMove.moveDirection = m_RD.left;
} else if (moveDirection.equalsIgnoreCase(kRightID)) {
m_LastMove.moveDirection = m_RD.right;
} else {
m_Logger.log(getName() + ": illegal move direction: " + moveDirection);
commandId.AddStatusError();
continue;
}
moveId = commandId;
m_LastMove.move = true;
} else if (commandName.equalsIgnoreCase(kFireID)) {
if (m_LastMove.fire == true) {
m_Logger.log(getName() + ": Detected more than one fire command on output link, ignoring.");
commandId.AddStatusError();
continue;
}
if (m_Missiles > 0) {
m_LastMove.fire = true;
} else {
m_Logger.log(getName() + ": Attempted to fire missle with no missiles.");
commandId.AddStatusError();
continue;
}
// Weapon ignored
} else if (commandName.equalsIgnoreCase(kRadarID)) {
if (m_LastMove.radar == true) {
m_Logger.log(getName() + ": Detected more than one radar command on output link, ignoring.");
commandId.AddStatusError();
continue;
}
String radarSwitch = commandId.GetParameterValue(kSwitchID);
if (radarSwitch == null) {
m_Logger.log(getName() + ": null radar switch.");
commandId.AddStatusError();
continue;
}
m_LastMove.radar = true;
m_LastMove.radarSwitch = radarSwitch.equalsIgnoreCase(kOn) ? true : false;
} else if (commandName.equalsIgnoreCase(kRadarPowerID)) {
if (m_LastMove.radarPower == true) {
m_Logger.log(getName() + ": Detected more than one radar power command on output link, ignoring.");
commandId.AddStatusError();
continue;
}
String powerValue = commandId.GetParameterValue(kSettingID);
if (powerValue == null) {
m_Logger.log(getName() + ": null radar power value.");
commandId.AddStatusError();
continue;
}
try {
m_LastMove.radarPowerSetting = Integer.decode(powerValue).intValue();
} catch (NumberFormatException e) {
m_Logger.log(getName() + ": Unable to parse radar power setting " + powerValue + ": " + e.getMessage());
commandId.AddStatusError();
continue;
}
m_LastMove.radarPower = true;
} else if (commandName.equalsIgnoreCase(kShieldsID)) {
if (m_LastMove.shields == true) {
m_Logger.log(getName() + ": Detected more than one shields command on output link, ignoring.");
commandId.AddStatusError();
continue;
}
String shieldsSetting = commandId.GetParameterValue(kSwitchID);
if (shieldsSetting == null) {
m_Logger.log(getName() + ": null shields setting.");
commandId.AddStatusError();
continue;
}
m_LastMove.shields = true;
m_LastMove.shieldsSetting = shieldsSetting.equalsIgnoreCase(kOn) ? true : false;
// Shields must be handled pronto
handleShields();
} else if (commandName.equalsIgnoreCase(kRotateID)) {
if (m_LastMove.rotate == true) {
m_Logger.log(getName() + ": Detected more than one rotate command on output link, ignoring.");
commandId.AddStatusError();
continue;
}
m_LastMove.rotateDirection = commandId.GetParameterValue(kDirectionID);
if (m_LastMove.rotateDirection == null) {
m_Logger.log(getName() + ": null rotation direction.");
commandId.AddStatusError();
continue;
}
m_LastMove.rotate = true;
// Rotation must be handled pronto and never fails.
if (m_LastMove.rotate) {
rotate(m_LastMove.rotateDirection);
}
} else {
m_Logger.log(getName() + ": Unknown command: " + commandName);
commandId.AddStatusError();
continue;
}
commandId.AddStatusComplete();
}
m_Agent.ClearOutputLinkChanges();
m_Agent.Commit();
// Do not allow a move if we rotated.
if (m_LastMove.rotate) {
if (m_LastMove.move) {
m_Logger.log("Tried to move with a rotation, rotating only.");
assert moveId != null;
moveId.AddStatusError();
moveId = null;
m_LastMove.move = false;
}
}
}
|
diff --git a/src/minecraft/ml/boxes/inventory/ContainerBox.java b/src/minecraft/ml/boxes/inventory/ContainerBox.java
index dd43b48..7727a55 100644
--- a/src/minecraft/ml/boxes/inventory/ContainerBox.java
+++ b/src/minecraft/ml/boxes/inventory/ContainerBox.java
@@ -1,103 +1,103 @@
package ml.boxes.inventory;
import invtweaks.api.container.ChestContainer;
import java.util.List;
import ml.boxes.data.IBoxContainer;
import ml.boxes.data.ItemBoxContainer;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.inventory.Container;
import net.minecraft.inventory.Slot;
import net.minecraft.item.ItemStack;
@ChestContainer
public class ContainerBox extends Container {
public final IBoxContainer box;
public final EntityPlayer player;
public ContainerBox(IBoxContainer box, EntityPlayer pl) {
this.box = box;
this.player = pl;
box.boxOpen();
int leftCol = 9;
int ySize = 168;
List<Slot> boxSlots = box.getBox().getSlots();
for (Slot slt : boxSlots){
addSlotToContainer(slt);
}
for (int slt=9; slt < pl.inventory.mainInventory.length; slt++){
int row = (int)Math.floor(slt/9) -1;
addSlotToContainer(new Slot(pl.inventory, slt, 9 + (slt%9)*18, ySize - 83 + row*18));
}
for (int hotbarSlot = 0; hotbarSlot < 9; hotbarSlot++) {
addSlotToContainer(new Slot(pl.inventory, hotbarSlot, leftCol + hotbarSlot * 18, ySize - 25));
}
}
@Override
public boolean canInteractWith(EntityPlayer var1) {
return box.boxUseableByPlayer(var1) && (!(box instanceof ItemBoxContainer) || ((ItemBoxContainer)box).stack == var1.getCurrentEquippedItem());
}
@Override
public ItemStack slotClick(int slotNum, int mouseBtn, int action,
EntityPlayer par4EntityPlayer) {
if (!box.slotPreClick(this, slotNum, mouseBtn, action, par4EntityPlayer))
return null;
ItemStack ret = super.slotClick(slotNum, mouseBtn, action, par4EntityPlayer);
save(par4EntityPlayer);
return ret;
}
@Override
- public ItemStack transferStackInSlot(EntityPlayer par1EntityPlayer, int par2)
+ public ItemStack transferStackInSlot(EntityPlayer par1EntityPlayer, int par2) //TODO Fix so no Shift+Clicking Boxes
{
ItemStack var3 = null;
Slot var4 = (Slot)this.inventorySlots.get(par2);
int bxSize = box.getBox().getSizeInventory();
if (var4 != null && var4.getHasStack())
{
ItemStack var5 = var4.getStack();
var3 = var5.copy();
if (par2 < bxSize){
if (!mergeItemStack(var5, bxSize,inventorySlots.size(), true))
return null;
- } else if (!mergeItemStack(var5, 0, bxSize, false)){
+ } else if (!box.getBox().mergeItemStack(var5, 0, bxSize)){
return null;
}
if (var5.stackSize == 0)
{
var4.putStack((ItemStack)null);
}
else
{
var4.onSlotChanged();
}
}
return var3;
}
@Override
public void onContainerClosed(EntityPlayer par1EntityPlayer) {
super.onContainerClosed(par1EntityPlayer);
save(par1EntityPlayer);
box.boxClose();
}
private void save(EntityPlayer pl){
if (!pl.worldObj.isRemote){
box.saveData();
}
}
}
| false | true | public ItemStack transferStackInSlot(EntityPlayer par1EntityPlayer, int par2)
{
ItemStack var3 = null;
Slot var4 = (Slot)this.inventorySlots.get(par2);
int bxSize = box.getBox().getSizeInventory();
if (var4 != null && var4.getHasStack())
{
ItemStack var5 = var4.getStack();
var3 = var5.copy();
if (par2 < bxSize){
if (!mergeItemStack(var5, bxSize,inventorySlots.size(), true))
return null;
} else if (!mergeItemStack(var5, 0, bxSize, false)){
return null;
}
if (var5.stackSize == 0)
{
var4.putStack((ItemStack)null);
}
else
{
var4.onSlotChanged();
}
}
return var3;
}
| public ItemStack transferStackInSlot(EntityPlayer par1EntityPlayer, int par2) //TODO Fix so no Shift+Clicking Boxes
{
ItemStack var3 = null;
Slot var4 = (Slot)this.inventorySlots.get(par2);
int bxSize = box.getBox().getSizeInventory();
if (var4 != null && var4.getHasStack())
{
ItemStack var5 = var4.getStack();
var3 = var5.copy();
if (par2 < bxSize){
if (!mergeItemStack(var5, bxSize,inventorySlots.size(), true))
return null;
} else if (!box.getBox().mergeItemStack(var5, 0, bxSize)){
return null;
}
if (var5.stackSize == 0)
{
var4.putStack((ItemStack)null);
}
else
{
var4.onSlotChanged();
}
}
return var3;
}
|
diff --git a/htroot/Wiki.java b/htroot/Wiki.java
index 106d3472a..4a8cacda6 100644
--- a/htroot/Wiki.java
+++ b/htroot/Wiki.java
@@ -1,267 +1,274 @@
// Wiki.java
// -----------------------
// part of the AnomicHTTPD caching proxy
// (C) by Michael Peter Christen; [email protected]
// first published on http://www.anomic.de
// Frankfurt, Germany, 2004
// last major change: 01.07.2003
//
// 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
//
// Using this software in any meaning (reading, learning, copying, compiling,
// running) means that you agree that the Author(s) is (are) not responsible
// for cost, loss of data or any harm that may be caused directly or indirectly
// by usage of this softare or this documentation. The usage of this software
// is on your own risk. The installation and usage (starting/running) of this
// software may allow other people or application to access your computer and
// any attached devices and is highly dependent on the configuration of the
// software which must be done by the user of the software; the author(s) is
// (are) also not responsible for proper configuration and usage of the
// software, even if provoked by documentation provided together with
// the software.
//
// Any changes to this file according to the GPL as documented in the file
// gpl.txt aside this file in the shipment you received can be done to the
// lines that follows this copyright notice here, but changes must not be
// done inside the copyright notive above. A re-distribution must contain
// the intact and unchanged copyright notice.
// Contributions and changes to the program code must be marked as such.
// Contains contributions from Alexander Schier [AS]
// and Marc Nause [MN]
// You must compile this file with
// javac -classpath .:../classes Wiki.java
// if the shell's current path is HTROOT
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import de.anomic.data.Diff;
import de.anomic.data.wikiBoard;
import de.anomic.http.httpHeader;
import de.anomic.plasma.plasmaSwitchboard;
import de.anomic.server.serverObjects;
import de.anomic.server.serverSwitch;
import de.anomic.yacy.yacyCore;
import de.anomic.yacy.yacyNewsRecord;
public class Wiki {
//private static String ListLevel = "";
//private static String numListLevel = "";
private static SimpleDateFormat SimpleFormatter = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
public static String dateString(Date date) {
return SimpleFormatter.format(date);
}
public static serverObjects respond(httpHeader header, serverObjects post, serverSwitch env) throws IOException {
plasmaSwitchboard switchboard = (plasmaSwitchboard) env;
serverObjects prop = new serverObjects();
if (post == null) {
post = new serverObjects();
post.put("page", "start");
}
String access = switchboard.getConfig("WikiAccess", "admin");
String pagename = post.get("page", "start");
String ip = post.get("CLIENTIP", "127.0.0.1");
String author = post.get("author", "anonymous");
if (author.equals("anonymous")) {
author = wikiBoard.guessAuthor(ip);
if (author == null) {
if (de.anomic.yacy.yacyCore.seedDB.mySeed == null) author = "anonymous";
else author = de.anomic.yacy.yacyCore.seedDB.mySeed.get("Name", "anonymous");
}
}
if (post.containsKey("access")) {
// only the administrator may change the access right
if (!switchboard.verifyAuthentication(header, true)) {
// check access right for admin
prop.put("AUTHENTICATE", "admin log-in"); // force log-in
return prop;
}
access = post.get("access", "admin");
switchboard.setConfig("WikiAccess", access);
}
if (access.equals("admin")) prop.put("mode_access", 0);
if (access.equals("all")) prop.put("mode_access", 1);
if (post.containsKey("submit")) {
if ((access.equals("admin") && (!switchboard.verifyAuthentication(header, true)))) {
// check access right for admin
prop.put("AUTHENTICATE", "admin log-in"); // force log-in
return prop;
}
// store a new page
byte[] content;
try {
content = post.get("content", "").getBytes("UTF-8");
} catch (UnsupportedEncodingException e) {
content = post.get("content", "").getBytes();
}
switchboard.wikiDB.write(switchboard.wikiDB.newEntry(pagename, author, ip, post.get("reason", "edit"), content));
// create a news message
HashMap map = new HashMap();
map.put("page", pagename);
map.put("author", author.replace(',', ' '));
yacyCore.newsPool.publishMyNews(new yacyNewsRecord("wiki_upd", map));
}
wikiBoard.entry page = switchboard.wikiDB.read(pagename);
if (post.containsKey("edit")) {
if ((access.equals("admin") && (!switchboard.verifyAuthentication(header, true)))) {
// check access right for admin
prop.put("AUTHENTICATE", "admin log-in"); // force log-in
return prop;
}
// edit the page
try {
prop.put("mode", 1); //edit
prop.put("mode_author", author);
- prop.put("mode_page-code", new String(page.page(), "UTF-8").replaceAll("<","<").replaceAll(">",">"));
+ prop.put("mode_page-code", new String(page.page(), "UTF-8"));
prop.put("mode_pagename", pagename);
} catch (UnsupportedEncodingException e) {}
}
//contributed by [MN]
else if (post.containsKey("preview")) {
// preview the page
prop.put("mode", 2);//preview
prop.put("mode_pagename", pagename);
prop.put("mode_author", author);
prop.put("mode_date", dateString(new Date()));
prop.putWiki("mode_page", post.get("content", ""));
prop.put("mode_page-code", post.get("content", ""));
}
//end contrib of [MN]
else if (post.containsKey("index")) {
// view an index
prop.put("mode", 3); //Index
String subject;
try {
Iterator i = switchboard.wikiDB.keys(true);
wikiBoard.entry entry;
int count=0;
while (i.hasNext()) {
subject = (String) i.next();
entry = switchboard.wikiDB.read(subject);
prop.put("mode_pages_"+count+"_name",wikiBoard.webalize(subject));
prop.put("mode_pages_"+count+"_subject", subject);
prop.put("mode_pages_"+count+"_date", dateString(entry.date()));
prop.put("mode_pages_"+count+"_author", entry.author());
count++;
}
prop.put("mode_pages", count);
} catch (IOException e) {
prop.put("mode_error", 1); //IO Error reading Wiki
prop.put("mode_error_message", e.getMessage());
}
prop.put("mode_pagename", pagename);
}
else if (post.containsKey("diff")) {
+ // Diff
prop.put("mode", 4);
prop.put("mode_page", pagename);
prop.put("mode_error_page", pagename);
try {
Iterator it = switchboard.wikiDB.keysBkp(true);
wikiBoard.entry entry;
wikiBoard.entry oentry = null;
wikiBoard.entry nentry = null;
int count = 0;
boolean oldselected = false, newselected = false;
while (it.hasNext()) {
entry = switchboard.wikiDB.readBkp((String)it.next());
prop.put("mode_error_versions_" + count + "_date", wikiBoard.dateString(entry.date()));
prop.put("mode_error_versions_" + count + "_fdate", dateString(entry.date()));
if (wikiBoard.dateString(entry.date()).equals(post.get("old", null))) {
prop.put("mode_error_versions_" + count + "_oldselected", 1);
oentry = entry;
oldselected = true;
} else if (wikiBoard.dateString(entry.date()).equals(post.get("new", null))) {
prop.put("mode_error_versions_" + count + "_newselected", 1);
nentry = entry;
newselected = true;
}
count++;
}
count--; // don't show current version
if (!oldselected) // select latest old entry
prop.put("mode_error_versions_" + (count - 1) + "_oldselected", 1);
if (!newselected) // select latest new entry (== current)
prop.put("mode_error_curselected", 1);
if (count == 0) {
prop.put("mode_error", 2); // no entries found
} else {
prop.put("mode_error_versions", count);
}
entry = switchboard.wikiDB.read(pagename);
if (entry != null) {
prop.put("mode_error_curdate", wikiBoard.dateString(entry.date()));
prop.put("mode_error_curfdate", dateString(entry.date()));
}
if (nentry == null) nentry = entry;
- if (post.get("diff", "").length() > 0 && oentry != null && nentry != null) {
+ if (post.containsKey("compare") && oentry != null && nentry != null) {
// TODO: split into paragraphs and compare them with the same diff-algo
Diff diff = new Diff(
new String(oentry.page(), "UTF-8"),
- new String(nentry.page(), "UTF-8"), 5);
- prop.putASIS("mode_diff", Diff.toHTML(new Diff[] { diff }));
- } else {
- prop.put("mode_diff", "");
+ new String(nentry.page(), "UTF-8"), 3);
+ prop.putASIS("mode_versioning_diff", Diff.toHTML(new Diff[] { diff }));
+ prop.put("mode_versioning", 1);
+ } else if (post.containsKey("viewold") && oentry != null) {
+ prop.put("mode_versioning", 2);
+ prop.put("mode_versioning_pagename", pagename);
+ prop.put("mode_versioning_author", oentry.author());
+ prop.put("mode_versioning_date", dateString(oentry.date()));
+ prop.putWiki("mode_versioning_page", oentry.page());
+ prop.put("mode_versioning_page-code", new String(oentry.page(), "UTF-8"));
}
} catch (IOException e) {
prop.put("mode_error", 1); //IO Error reading Wiki
prop.put("mode_error_message", e.getMessage());
}
}
else {
// show page
prop.put("mode", 0); //viewing
prop.put("mode_pagename", pagename);
prop.put("mode_author", page.author());
prop.put("mode_date", dateString(page.date()));
prop.putWiki("mode_page", page.page());
prop.put("controls", 0);
prop.put("controls_pagename", pagename);
}
// return rewrite properties
return prop;
}
}
| false | true | public static serverObjects respond(httpHeader header, serverObjects post, serverSwitch env) throws IOException {
plasmaSwitchboard switchboard = (plasmaSwitchboard) env;
serverObjects prop = new serverObjects();
if (post == null) {
post = new serverObjects();
post.put("page", "start");
}
String access = switchboard.getConfig("WikiAccess", "admin");
String pagename = post.get("page", "start");
String ip = post.get("CLIENTIP", "127.0.0.1");
String author = post.get("author", "anonymous");
if (author.equals("anonymous")) {
author = wikiBoard.guessAuthor(ip);
if (author == null) {
if (de.anomic.yacy.yacyCore.seedDB.mySeed == null) author = "anonymous";
else author = de.anomic.yacy.yacyCore.seedDB.mySeed.get("Name", "anonymous");
}
}
if (post.containsKey("access")) {
// only the administrator may change the access right
if (!switchboard.verifyAuthentication(header, true)) {
// check access right for admin
prop.put("AUTHENTICATE", "admin log-in"); // force log-in
return prop;
}
access = post.get("access", "admin");
switchboard.setConfig("WikiAccess", access);
}
if (access.equals("admin")) prop.put("mode_access", 0);
if (access.equals("all")) prop.put("mode_access", 1);
if (post.containsKey("submit")) {
if ((access.equals("admin") && (!switchboard.verifyAuthentication(header, true)))) {
// check access right for admin
prop.put("AUTHENTICATE", "admin log-in"); // force log-in
return prop;
}
// store a new page
byte[] content;
try {
content = post.get("content", "").getBytes("UTF-8");
} catch (UnsupportedEncodingException e) {
content = post.get("content", "").getBytes();
}
switchboard.wikiDB.write(switchboard.wikiDB.newEntry(pagename, author, ip, post.get("reason", "edit"), content));
// create a news message
HashMap map = new HashMap();
map.put("page", pagename);
map.put("author", author.replace(',', ' '));
yacyCore.newsPool.publishMyNews(new yacyNewsRecord("wiki_upd", map));
}
wikiBoard.entry page = switchboard.wikiDB.read(pagename);
if (post.containsKey("edit")) {
if ((access.equals("admin") && (!switchboard.verifyAuthentication(header, true)))) {
// check access right for admin
prop.put("AUTHENTICATE", "admin log-in"); // force log-in
return prop;
}
// edit the page
try {
prop.put("mode", 1); //edit
prop.put("mode_author", author);
prop.put("mode_page-code", new String(page.page(), "UTF-8").replaceAll("<","<").replaceAll(">",">"));
prop.put("mode_pagename", pagename);
} catch (UnsupportedEncodingException e) {}
}
//contributed by [MN]
else if (post.containsKey("preview")) {
// preview the page
prop.put("mode", 2);//preview
prop.put("mode_pagename", pagename);
prop.put("mode_author", author);
prop.put("mode_date", dateString(new Date()));
prop.putWiki("mode_page", post.get("content", ""));
prop.put("mode_page-code", post.get("content", ""));
}
//end contrib of [MN]
else if (post.containsKey("index")) {
// view an index
prop.put("mode", 3); //Index
String subject;
try {
Iterator i = switchboard.wikiDB.keys(true);
wikiBoard.entry entry;
int count=0;
while (i.hasNext()) {
subject = (String) i.next();
entry = switchboard.wikiDB.read(subject);
prop.put("mode_pages_"+count+"_name",wikiBoard.webalize(subject));
prop.put("mode_pages_"+count+"_subject", subject);
prop.put("mode_pages_"+count+"_date", dateString(entry.date()));
prop.put("mode_pages_"+count+"_author", entry.author());
count++;
}
prop.put("mode_pages", count);
} catch (IOException e) {
prop.put("mode_error", 1); //IO Error reading Wiki
prop.put("mode_error_message", e.getMessage());
}
prop.put("mode_pagename", pagename);
}
else if (post.containsKey("diff")) {
prop.put("mode", 4);
prop.put("mode_page", pagename);
prop.put("mode_error_page", pagename);
try {
Iterator it = switchboard.wikiDB.keysBkp(true);
wikiBoard.entry entry;
wikiBoard.entry oentry = null;
wikiBoard.entry nentry = null;
int count = 0;
boolean oldselected = false, newselected = false;
while (it.hasNext()) {
entry = switchboard.wikiDB.readBkp((String)it.next());
prop.put("mode_error_versions_" + count + "_date", wikiBoard.dateString(entry.date()));
prop.put("mode_error_versions_" + count + "_fdate", dateString(entry.date()));
if (wikiBoard.dateString(entry.date()).equals(post.get("old", null))) {
prop.put("mode_error_versions_" + count + "_oldselected", 1);
oentry = entry;
oldselected = true;
} else if (wikiBoard.dateString(entry.date()).equals(post.get("new", null))) {
prop.put("mode_error_versions_" + count + "_newselected", 1);
nentry = entry;
newselected = true;
}
count++;
}
count--; // don't show current version
if (!oldselected) // select latest old entry
prop.put("mode_error_versions_" + (count - 1) + "_oldselected", 1);
if (!newselected) // select latest new entry (== current)
prop.put("mode_error_curselected", 1);
if (count == 0) {
prop.put("mode_error", 2); // no entries found
} else {
prop.put("mode_error_versions", count);
}
entry = switchboard.wikiDB.read(pagename);
if (entry != null) {
prop.put("mode_error_curdate", wikiBoard.dateString(entry.date()));
prop.put("mode_error_curfdate", dateString(entry.date()));
}
if (nentry == null) nentry = entry;
if (post.get("diff", "").length() > 0 && oentry != null && nentry != null) {
// TODO: split into paragraphs and compare them with the same diff-algo
Diff diff = new Diff(
new String(oentry.page(), "UTF-8"),
new String(nentry.page(), "UTF-8"), 5);
prop.putASIS("mode_diff", Diff.toHTML(new Diff[] { diff }));
} else {
prop.put("mode_diff", "");
}
} catch (IOException e) {
prop.put("mode_error", 1); //IO Error reading Wiki
prop.put("mode_error_message", e.getMessage());
}
}
else {
// show page
prop.put("mode", 0); //viewing
prop.put("mode_pagename", pagename);
prop.put("mode_author", page.author());
prop.put("mode_date", dateString(page.date()));
prop.putWiki("mode_page", page.page());
prop.put("controls", 0);
prop.put("controls_pagename", pagename);
}
// return rewrite properties
return prop;
}
| public static serverObjects respond(httpHeader header, serverObjects post, serverSwitch env) throws IOException {
plasmaSwitchboard switchboard = (plasmaSwitchboard) env;
serverObjects prop = new serverObjects();
if (post == null) {
post = new serverObjects();
post.put("page", "start");
}
String access = switchboard.getConfig("WikiAccess", "admin");
String pagename = post.get("page", "start");
String ip = post.get("CLIENTIP", "127.0.0.1");
String author = post.get("author", "anonymous");
if (author.equals("anonymous")) {
author = wikiBoard.guessAuthor(ip);
if (author == null) {
if (de.anomic.yacy.yacyCore.seedDB.mySeed == null) author = "anonymous";
else author = de.anomic.yacy.yacyCore.seedDB.mySeed.get("Name", "anonymous");
}
}
if (post.containsKey("access")) {
// only the administrator may change the access right
if (!switchboard.verifyAuthentication(header, true)) {
// check access right for admin
prop.put("AUTHENTICATE", "admin log-in"); // force log-in
return prop;
}
access = post.get("access", "admin");
switchboard.setConfig("WikiAccess", access);
}
if (access.equals("admin")) prop.put("mode_access", 0);
if (access.equals("all")) prop.put("mode_access", 1);
if (post.containsKey("submit")) {
if ((access.equals("admin") && (!switchboard.verifyAuthentication(header, true)))) {
// check access right for admin
prop.put("AUTHENTICATE", "admin log-in"); // force log-in
return prop;
}
// store a new page
byte[] content;
try {
content = post.get("content", "").getBytes("UTF-8");
} catch (UnsupportedEncodingException e) {
content = post.get("content", "").getBytes();
}
switchboard.wikiDB.write(switchboard.wikiDB.newEntry(pagename, author, ip, post.get("reason", "edit"), content));
// create a news message
HashMap map = new HashMap();
map.put("page", pagename);
map.put("author", author.replace(',', ' '));
yacyCore.newsPool.publishMyNews(new yacyNewsRecord("wiki_upd", map));
}
wikiBoard.entry page = switchboard.wikiDB.read(pagename);
if (post.containsKey("edit")) {
if ((access.equals("admin") && (!switchboard.verifyAuthentication(header, true)))) {
// check access right for admin
prop.put("AUTHENTICATE", "admin log-in"); // force log-in
return prop;
}
// edit the page
try {
prop.put("mode", 1); //edit
prop.put("mode_author", author);
prop.put("mode_page-code", new String(page.page(), "UTF-8"));
prop.put("mode_pagename", pagename);
} catch (UnsupportedEncodingException e) {}
}
//contributed by [MN]
else if (post.containsKey("preview")) {
// preview the page
prop.put("mode", 2);//preview
prop.put("mode_pagename", pagename);
prop.put("mode_author", author);
prop.put("mode_date", dateString(new Date()));
prop.putWiki("mode_page", post.get("content", ""));
prop.put("mode_page-code", post.get("content", ""));
}
//end contrib of [MN]
else if (post.containsKey("index")) {
// view an index
prop.put("mode", 3); //Index
String subject;
try {
Iterator i = switchboard.wikiDB.keys(true);
wikiBoard.entry entry;
int count=0;
while (i.hasNext()) {
subject = (String) i.next();
entry = switchboard.wikiDB.read(subject);
prop.put("mode_pages_"+count+"_name",wikiBoard.webalize(subject));
prop.put("mode_pages_"+count+"_subject", subject);
prop.put("mode_pages_"+count+"_date", dateString(entry.date()));
prop.put("mode_pages_"+count+"_author", entry.author());
count++;
}
prop.put("mode_pages", count);
} catch (IOException e) {
prop.put("mode_error", 1); //IO Error reading Wiki
prop.put("mode_error_message", e.getMessage());
}
prop.put("mode_pagename", pagename);
}
else if (post.containsKey("diff")) {
// Diff
prop.put("mode", 4);
prop.put("mode_page", pagename);
prop.put("mode_error_page", pagename);
try {
Iterator it = switchboard.wikiDB.keysBkp(true);
wikiBoard.entry entry;
wikiBoard.entry oentry = null;
wikiBoard.entry nentry = null;
int count = 0;
boolean oldselected = false, newselected = false;
while (it.hasNext()) {
entry = switchboard.wikiDB.readBkp((String)it.next());
prop.put("mode_error_versions_" + count + "_date", wikiBoard.dateString(entry.date()));
prop.put("mode_error_versions_" + count + "_fdate", dateString(entry.date()));
if (wikiBoard.dateString(entry.date()).equals(post.get("old", null))) {
prop.put("mode_error_versions_" + count + "_oldselected", 1);
oentry = entry;
oldselected = true;
} else if (wikiBoard.dateString(entry.date()).equals(post.get("new", null))) {
prop.put("mode_error_versions_" + count + "_newselected", 1);
nentry = entry;
newselected = true;
}
count++;
}
count--; // don't show current version
if (!oldselected) // select latest old entry
prop.put("mode_error_versions_" + (count - 1) + "_oldselected", 1);
if (!newselected) // select latest new entry (== current)
prop.put("mode_error_curselected", 1);
if (count == 0) {
prop.put("mode_error", 2); // no entries found
} else {
prop.put("mode_error_versions", count);
}
entry = switchboard.wikiDB.read(pagename);
if (entry != null) {
prop.put("mode_error_curdate", wikiBoard.dateString(entry.date()));
prop.put("mode_error_curfdate", dateString(entry.date()));
}
if (nentry == null) nentry = entry;
if (post.containsKey("compare") && oentry != null && nentry != null) {
// TODO: split into paragraphs and compare them with the same diff-algo
Diff diff = new Diff(
new String(oentry.page(), "UTF-8"),
new String(nentry.page(), "UTF-8"), 3);
prop.putASIS("mode_versioning_diff", Diff.toHTML(new Diff[] { diff }));
prop.put("mode_versioning", 1);
} else if (post.containsKey("viewold") && oentry != null) {
prop.put("mode_versioning", 2);
prop.put("mode_versioning_pagename", pagename);
prop.put("mode_versioning_author", oentry.author());
prop.put("mode_versioning_date", dateString(oentry.date()));
prop.putWiki("mode_versioning_page", oentry.page());
prop.put("mode_versioning_page-code", new String(oentry.page(), "UTF-8"));
}
} catch (IOException e) {
prop.put("mode_error", 1); //IO Error reading Wiki
prop.put("mode_error_message", e.getMessage());
}
}
else {
// show page
prop.put("mode", 0); //viewing
prop.put("mode_pagename", pagename);
prop.put("mode_author", page.author());
prop.put("mode_date", dateString(page.date()));
prop.putWiki("mode_page", page.page());
prop.put("controls", 0);
prop.put("controls_pagename", pagename);
}
// return rewrite properties
return prop;
}
|
diff --git a/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/TestDFSRollback.java b/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/TestDFSRollback.java
index b07bad252e..282ad68a37 100644
--- a/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/TestDFSRollback.java
+++ b/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/TestDFSRollback.java
@@ -1,313 +1,313 @@
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.hdfs;
import static org.apache.hadoop.hdfs.server.common.HdfsServerConstants.NodeType.DATA_NODE;
import static org.apache.hadoop.hdfs.server.common.HdfsServerConstants.NodeType.NAME_NODE;
import java.io.File;
import java.io.IOException;
import java.util.Collections;
import java.util.List;
import junit.framework.TestCase;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hdfs.server.common.StorageInfo;
import org.apache.hadoop.hdfs.server.common.HdfsServerConstants.NodeType;
import org.apache.hadoop.hdfs.server.common.HdfsServerConstants.StartupOption;
import org.apache.hadoop.hdfs.server.namenode.FSImageTestUtil;
import org.apache.hadoop.util.StringUtils;
import com.google.common.base.Charsets;
import com.google.common.collect.Lists;
/**
* This test ensures the appropriate response (successful or failure) from
* the system when the system is rolled back under various storage state and
* version conditions.
*/
public class TestDFSRollback extends TestCase {
private static final Log LOG = LogFactory.getLog(
"org.apache.hadoop.hdfs.TestDFSRollback");
private Configuration conf;
private int testCounter = 0;
private MiniDFSCluster cluster = null;
/**
* Writes an INFO log message containing the parameters.
*/
void log(String label, int numDirs) {
LOG.info("============================================================");
LOG.info("***TEST " + (testCounter++) + "*** "
+ label + ":"
+ " numDirs="+numDirs);
}
/**
* Verify that the new current directory is the old previous.
* It is assumed that the server has recovered and rolled back.
*/
void checkResult(NodeType nodeType, String[] baseDirs) throws Exception {
List<File> curDirs = Lists.newArrayList();
for (String baseDir : baseDirs) {
File curDir = new File(baseDir, "current");
curDirs.add(curDir);
switch (nodeType) {
case NAME_NODE:
FSImageTestUtil.assertReasonableNameCurrentDir(curDir);
break;
case DATA_NODE:
assertEquals(
UpgradeUtilities.checksumContents(nodeType, curDir),
UpgradeUtilities.checksumMasterDataNodeContents());
break;
}
}
FSImageTestUtil.assertParallelFilesAreIdentical(
curDirs, Collections.<String>emptySet());
for (int i = 0; i < baseDirs.length; i++) {
assertFalse(new File(baseDirs[i],"previous").isDirectory());
}
}
/**
* Attempts to start a NameNode with the given operation. Starting
* the NameNode should throw an exception.
*/
void startNameNodeShouldFail(StartupOption operation, String searchString) {
try {
cluster = new MiniDFSCluster.Builder(conf).numDataNodes(0)
.startupOption(operation)
.format(false)
.manageDataDfsDirs(false)
.manageNameDfsDirs(false)
.build(); // should fail
throw new AssertionError("NameNode should have failed to start");
} catch (Exception expected) {
if (!expected.getMessage().contains(searchString)) {
fail("Expected substring '" + searchString + "' in exception " +
"but got: " + StringUtils.stringifyException(expected));
}
// expected
}
}
/**
* Attempts to start a DataNode with the given operation. Starting
* the given block pool should fail.
* @param operation startup option
* @param bpid block pool Id that should fail to start
* @throws IOException
*/
void startBlockPoolShouldFail(StartupOption operation, String bpid)
throws IOException {
cluster.startDataNodes(conf, 1, false, operation, null); // should fail
assertFalse("Block pool " + bpid + " should have failed to start",
cluster.getDataNodes().get(0).isBPServiceAlive(bpid));
}
/**
* This test attempts to rollback the NameNode and DataNode under
* a number of valid and invalid conditions.
*/
public void testRollback() throws Exception {
File[] baseDirs;
UpgradeUtilities.initialize();
StorageInfo storageInfo = null;
for (int numDirs = 1; numDirs <= 2; numDirs++) {
conf = new HdfsConfiguration();
conf.setInt(DFSConfigKeys.DFS_DATANODE_SCAN_PERIOD_HOURS_KEY, -1);
conf = UpgradeUtilities.initializeStorageStateConf(numDirs, conf);
String[] nameNodeDirs = conf.getStrings(DFSConfigKeys.DFS_NAMENODE_NAME_DIR_KEY);
String[] dataNodeDirs = conf.getStrings(DFSConfigKeys.DFS_DATANODE_DATA_DIR_KEY);
log("Normal NameNode rollback", numDirs);
UpgradeUtilities.createNameNodeStorageDirs(nameNodeDirs, "current");
UpgradeUtilities.createNameNodeStorageDirs(nameNodeDirs, "previous");
cluster = new MiniDFSCluster.Builder(conf).numDataNodes(0)
.format(false)
.manageDataDfsDirs(false)
.manageNameDfsDirs(false)
.startupOption(StartupOption.ROLLBACK)
.build();
checkResult(NAME_NODE, nameNodeDirs);
cluster.shutdown();
UpgradeUtilities.createEmptyDirs(nameNodeDirs);
log("Normal DataNode rollback", numDirs);
UpgradeUtilities.createNameNodeStorageDirs(nameNodeDirs, "current");
UpgradeUtilities.createNameNodeStorageDirs(nameNodeDirs, "previous");
cluster = new MiniDFSCluster.Builder(conf).numDataNodes(0)
.format(false)
.manageDataDfsDirs(false)
.manageNameDfsDirs(false)
.startupOption(StartupOption.ROLLBACK)
.build();
UpgradeUtilities.createDataNodeStorageDirs(dataNodeDirs, "current");
UpgradeUtilities.createDataNodeStorageDirs(dataNodeDirs, "previous");
cluster.startDataNodes(conf, 1, false, StartupOption.ROLLBACK, null);
checkResult(DATA_NODE, dataNodeDirs);
cluster.shutdown();
UpgradeUtilities.createEmptyDirs(nameNodeDirs);
UpgradeUtilities.createEmptyDirs(dataNodeDirs);
log("NameNode rollback without existing previous dir", numDirs);
UpgradeUtilities.createNameNodeStorageDirs(nameNodeDirs, "current");
startNameNodeShouldFail(StartupOption.ROLLBACK,
"None of the storage directories contain previous fs state");
UpgradeUtilities.createEmptyDirs(nameNodeDirs);
log("DataNode rollback without existing previous dir", numDirs);
UpgradeUtilities.createNameNodeStorageDirs(nameNodeDirs, "current");
cluster = new MiniDFSCluster.Builder(conf).numDataNodes(0)
.format(false)
.manageDataDfsDirs(false)
.manageNameDfsDirs(false)
.startupOption(StartupOption.UPGRADE)
.build();
UpgradeUtilities.createDataNodeStorageDirs(dataNodeDirs, "current");
cluster.startDataNodes(conf, 1, false, StartupOption.ROLLBACK, null);
cluster.shutdown();
UpgradeUtilities.createEmptyDirs(nameNodeDirs);
UpgradeUtilities.createEmptyDirs(dataNodeDirs);
log("DataNode rollback with future stored layout version in previous", numDirs);
UpgradeUtilities.createNameNodeStorageDirs(nameNodeDirs, "current");
UpgradeUtilities.createNameNodeStorageDirs(nameNodeDirs, "previous");
cluster = new MiniDFSCluster.Builder(conf).numDataNodes(0)
.format(false)
.manageDataDfsDirs(false)
.manageNameDfsDirs(false)
.startupOption(StartupOption.ROLLBACK)
.build();
UpgradeUtilities.createDataNodeStorageDirs(dataNodeDirs, "current");
baseDirs = UpgradeUtilities.createDataNodeStorageDirs(dataNodeDirs, "previous");
storageInfo = new StorageInfo(Integer.MIN_VALUE,
UpgradeUtilities.getCurrentNamespaceID(cluster),
UpgradeUtilities.getCurrentClusterID(cluster),
UpgradeUtilities.getCurrentFsscTime(cluster));
UpgradeUtilities.createDataNodeVersionFile(baseDirs, storageInfo,
UpgradeUtilities.getCurrentBlockPoolID(cluster));
startBlockPoolShouldFail(StartupOption.ROLLBACK,
cluster.getNamesystem().getBlockPoolId());
cluster.shutdown();
UpgradeUtilities.createEmptyDirs(nameNodeDirs);
UpgradeUtilities.createEmptyDirs(dataNodeDirs);
log("DataNode rollback with newer fsscTime in previous", numDirs);
UpgradeUtilities.createNameNodeStorageDirs(nameNodeDirs, "current");
UpgradeUtilities.createNameNodeStorageDirs(nameNodeDirs, "previous");
cluster = new MiniDFSCluster.Builder(conf).numDataNodes(0)
.format(false)
.manageDataDfsDirs(false)
.manageNameDfsDirs(false)
.startupOption(StartupOption.ROLLBACK)
.build();
UpgradeUtilities.createDataNodeStorageDirs(dataNodeDirs, "current");
baseDirs = UpgradeUtilities.createDataNodeStorageDirs(dataNodeDirs, "previous");
storageInfo = new StorageInfo(UpgradeUtilities.getCurrentLayoutVersion(),
UpgradeUtilities.getCurrentNamespaceID(cluster),
UpgradeUtilities.getCurrentClusterID(cluster), Long.MAX_VALUE);
UpgradeUtilities.createDataNodeVersionFile(baseDirs, storageInfo,
UpgradeUtilities.getCurrentBlockPoolID(cluster));
startBlockPoolShouldFail(StartupOption.ROLLBACK,
cluster.getNamesystem().getBlockPoolId());
cluster.shutdown();
UpgradeUtilities.createEmptyDirs(nameNodeDirs);
UpgradeUtilities.createEmptyDirs(dataNodeDirs);
log("NameNode rollback with no edits file", numDirs);
UpgradeUtilities.createNameNodeStorageDirs(nameNodeDirs, "current");
baseDirs = UpgradeUtilities.createNameNodeStorageDirs(nameNodeDirs, "previous");
deleteMatchingFiles(baseDirs, "edits.*");
startNameNodeShouldFail(StartupOption.ROLLBACK,
- "No non-corrupt logs for txid ");
+ "Gap in transactions. Expected to be able to read up until at least txid ");
UpgradeUtilities.createEmptyDirs(nameNodeDirs);
log("NameNode rollback with no image file", numDirs);
UpgradeUtilities.createNameNodeStorageDirs(nameNodeDirs, "current");
baseDirs = UpgradeUtilities.createNameNodeStorageDirs(nameNodeDirs, "previous");
deleteMatchingFiles(baseDirs, "fsimage_.*");
startNameNodeShouldFail(StartupOption.ROLLBACK,
"No valid image files found");
UpgradeUtilities.createEmptyDirs(nameNodeDirs);
log("NameNode rollback with corrupt version file", numDirs);
UpgradeUtilities.createNameNodeStorageDirs(nameNodeDirs, "current");
baseDirs = UpgradeUtilities.createNameNodeStorageDirs(nameNodeDirs, "previous");
for (File f : baseDirs) {
UpgradeUtilities.corruptFile(
new File(f,"VERSION"),
"layoutVersion".getBytes(Charsets.UTF_8),
"xxxxxxxxxxxxx".getBytes(Charsets.UTF_8));
}
startNameNodeShouldFail(StartupOption.ROLLBACK,
"file VERSION has layoutVersion missing");
UpgradeUtilities.createEmptyDirs(nameNodeDirs);
log("NameNode rollback with old layout version in previous", numDirs);
UpgradeUtilities.createNameNodeStorageDirs(nameNodeDirs, "current");
baseDirs = UpgradeUtilities.createNameNodeStorageDirs(nameNodeDirs, "previous");
storageInfo = new StorageInfo(1,
UpgradeUtilities.getCurrentNamespaceID(null),
UpgradeUtilities.getCurrentClusterID(null),
UpgradeUtilities.getCurrentFsscTime(null));
UpgradeUtilities.createNameNodeVersionFile(conf, baseDirs,
storageInfo, UpgradeUtilities.getCurrentBlockPoolID(cluster));
startNameNodeShouldFail(StartupOption.ROLLBACK,
"Cannot rollback to storage version 1 using this version");
UpgradeUtilities.createEmptyDirs(nameNodeDirs);
} // end numDir loop
}
private void deleteMatchingFiles(File[] baseDirs, String regex) {
for (File baseDir : baseDirs) {
for (File f : baseDir.listFiles()) {
if (f.getName().matches(regex)) {
f.delete();
}
}
}
}
protected void tearDown() throws Exception {
LOG.info("Shutting down MiniDFSCluster");
if (cluster != null) cluster.shutdown();
}
public static void main(String[] args) throws Exception {
new TestDFSRollback().testRollback();
}
}
| true | true | public void testRollback() throws Exception {
File[] baseDirs;
UpgradeUtilities.initialize();
StorageInfo storageInfo = null;
for (int numDirs = 1; numDirs <= 2; numDirs++) {
conf = new HdfsConfiguration();
conf.setInt(DFSConfigKeys.DFS_DATANODE_SCAN_PERIOD_HOURS_KEY, -1);
conf = UpgradeUtilities.initializeStorageStateConf(numDirs, conf);
String[] nameNodeDirs = conf.getStrings(DFSConfigKeys.DFS_NAMENODE_NAME_DIR_KEY);
String[] dataNodeDirs = conf.getStrings(DFSConfigKeys.DFS_DATANODE_DATA_DIR_KEY);
log("Normal NameNode rollback", numDirs);
UpgradeUtilities.createNameNodeStorageDirs(nameNodeDirs, "current");
UpgradeUtilities.createNameNodeStorageDirs(nameNodeDirs, "previous");
cluster = new MiniDFSCluster.Builder(conf).numDataNodes(0)
.format(false)
.manageDataDfsDirs(false)
.manageNameDfsDirs(false)
.startupOption(StartupOption.ROLLBACK)
.build();
checkResult(NAME_NODE, nameNodeDirs);
cluster.shutdown();
UpgradeUtilities.createEmptyDirs(nameNodeDirs);
log("Normal DataNode rollback", numDirs);
UpgradeUtilities.createNameNodeStorageDirs(nameNodeDirs, "current");
UpgradeUtilities.createNameNodeStorageDirs(nameNodeDirs, "previous");
cluster = new MiniDFSCluster.Builder(conf).numDataNodes(0)
.format(false)
.manageDataDfsDirs(false)
.manageNameDfsDirs(false)
.startupOption(StartupOption.ROLLBACK)
.build();
UpgradeUtilities.createDataNodeStorageDirs(dataNodeDirs, "current");
UpgradeUtilities.createDataNodeStorageDirs(dataNodeDirs, "previous");
cluster.startDataNodes(conf, 1, false, StartupOption.ROLLBACK, null);
checkResult(DATA_NODE, dataNodeDirs);
cluster.shutdown();
UpgradeUtilities.createEmptyDirs(nameNodeDirs);
UpgradeUtilities.createEmptyDirs(dataNodeDirs);
log("NameNode rollback without existing previous dir", numDirs);
UpgradeUtilities.createNameNodeStorageDirs(nameNodeDirs, "current");
startNameNodeShouldFail(StartupOption.ROLLBACK,
"None of the storage directories contain previous fs state");
UpgradeUtilities.createEmptyDirs(nameNodeDirs);
log("DataNode rollback without existing previous dir", numDirs);
UpgradeUtilities.createNameNodeStorageDirs(nameNodeDirs, "current");
cluster = new MiniDFSCluster.Builder(conf).numDataNodes(0)
.format(false)
.manageDataDfsDirs(false)
.manageNameDfsDirs(false)
.startupOption(StartupOption.UPGRADE)
.build();
UpgradeUtilities.createDataNodeStorageDirs(dataNodeDirs, "current");
cluster.startDataNodes(conf, 1, false, StartupOption.ROLLBACK, null);
cluster.shutdown();
UpgradeUtilities.createEmptyDirs(nameNodeDirs);
UpgradeUtilities.createEmptyDirs(dataNodeDirs);
log("DataNode rollback with future stored layout version in previous", numDirs);
UpgradeUtilities.createNameNodeStorageDirs(nameNodeDirs, "current");
UpgradeUtilities.createNameNodeStorageDirs(nameNodeDirs, "previous");
cluster = new MiniDFSCluster.Builder(conf).numDataNodes(0)
.format(false)
.manageDataDfsDirs(false)
.manageNameDfsDirs(false)
.startupOption(StartupOption.ROLLBACK)
.build();
UpgradeUtilities.createDataNodeStorageDirs(dataNodeDirs, "current");
baseDirs = UpgradeUtilities.createDataNodeStorageDirs(dataNodeDirs, "previous");
storageInfo = new StorageInfo(Integer.MIN_VALUE,
UpgradeUtilities.getCurrentNamespaceID(cluster),
UpgradeUtilities.getCurrentClusterID(cluster),
UpgradeUtilities.getCurrentFsscTime(cluster));
UpgradeUtilities.createDataNodeVersionFile(baseDirs, storageInfo,
UpgradeUtilities.getCurrentBlockPoolID(cluster));
startBlockPoolShouldFail(StartupOption.ROLLBACK,
cluster.getNamesystem().getBlockPoolId());
cluster.shutdown();
UpgradeUtilities.createEmptyDirs(nameNodeDirs);
UpgradeUtilities.createEmptyDirs(dataNodeDirs);
log("DataNode rollback with newer fsscTime in previous", numDirs);
UpgradeUtilities.createNameNodeStorageDirs(nameNodeDirs, "current");
UpgradeUtilities.createNameNodeStorageDirs(nameNodeDirs, "previous");
cluster = new MiniDFSCluster.Builder(conf).numDataNodes(0)
.format(false)
.manageDataDfsDirs(false)
.manageNameDfsDirs(false)
.startupOption(StartupOption.ROLLBACK)
.build();
UpgradeUtilities.createDataNodeStorageDirs(dataNodeDirs, "current");
baseDirs = UpgradeUtilities.createDataNodeStorageDirs(dataNodeDirs, "previous");
storageInfo = new StorageInfo(UpgradeUtilities.getCurrentLayoutVersion(),
UpgradeUtilities.getCurrentNamespaceID(cluster),
UpgradeUtilities.getCurrentClusterID(cluster), Long.MAX_VALUE);
UpgradeUtilities.createDataNodeVersionFile(baseDirs, storageInfo,
UpgradeUtilities.getCurrentBlockPoolID(cluster));
startBlockPoolShouldFail(StartupOption.ROLLBACK,
cluster.getNamesystem().getBlockPoolId());
cluster.shutdown();
UpgradeUtilities.createEmptyDirs(nameNodeDirs);
UpgradeUtilities.createEmptyDirs(dataNodeDirs);
log("NameNode rollback with no edits file", numDirs);
UpgradeUtilities.createNameNodeStorageDirs(nameNodeDirs, "current");
baseDirs = UpgradeUtilities.createNameNodeStorageDirs(nameNodeDirs, "previous");
deleteMatchingFiles(baseDirs, "edits.*");
startNameNodeShouldFail(StartupOption.ROLLBACK,
"No non-corrupt logs for txid ");
UpgradeUtilities.createEmptyDirs(nameNodeDirs);
log("NameNode rollback with no image file", numDirs);
UpgradeUtilities.createNameNodeStorageDirs(nameNodeDirs, "current");
baseDirs = UpgradeUtilities.createNameNodeStorageDirs(nameNodeDirs, "previous");
deleteMatchingFiles(baseDirs, "fsimage_.*");
startNameNodeShouldFail(StartupOption.ROLLBACK,
"No valid image files found");
UpgradeUtilities.createEmptyDirs(nameNodeDirs);
log("NameNode rollback with corrupt version file", numDirs);
UpgradeUtilities.createNameNodeStorageDirs(nameNodeDirs, "current");
baseDirs = UpgradeUtilities.createNameNodeStorageDirs(nameNodeDirs, "previous");
for (File f : baseDirs) {
UpgradeUtilities.corruptFile(
new File(f,"VERSION"),
"layoutVersion".getBytes(Charsets.UTF_8),
"xxxxxxxxxxxxx".getBytes(Charsets.UTF_8));
}
startNameNodeShouldFail(StartupOption.ROLLBACK,
"file VERSION has layoutVersion missing");
UpgradeUtilities.createEmptyDirs(nameNodeDirs);
log("NameNode rollback with old layout version in previous", numDirs);
UpgradeUtilities.createNameNodeStorageDirs(nameNodeDirs, "current");
baseDirs = UpgradeUtilities.createNameNodeStorageDirs(nameNodeDirs, "previous");
storageInfo = new StorageInfo(1,
UpgradeUtilities.getCurrentNamespaceID(null),
UpgradeUtilities.getCurrentClusterID(null),
UpgradeUtilities.getCurrentFsscTime(null));
UpgradeUtilities.createNameNodeVersionFile(conf, baseDirs,
storageInfo, UpgradeUtilities.getCurrentBlockPoolID(cluster));
startNameNodeShouldFail(StartupOption.ROLLBACK,
"Cannot rollback to storage version 1 using this version");
UpgradeUtilities.createEmptyDirs(nameNodeDirs);
} // end numDir loop
}
| public void testRollback() throws Exception {
File[] baseDirs;
UpgradeUtilities.initialize();
StorageInfo storageInfo = null;
for (int numDirs = 1; numDirs <= 2; numDirs++) {
conf = new HdfsConfiguration();
conf.setInt(DFSConfigKeys.DFS_DATANODE_SCAN_PERIOD_HOURS_KEY, -1);
conf = UpgradeUtilities.initializeStorageStateConf(numDirs, conf);
String[] nameNodeDirs = conf.getStrings(DFSConfigKeys.DFS_NAMENODE_NAME_DIR_KEY);
String[] dataNodeDirs = conf.getStrings(DFSConfigKeys.DFS_DATANODE_DATA_DIR_KEY);
log("Normal NameNode rollback", numDirs);
UpgradeUtilities.createNameNodeStorageDirs(nameNodeDirs, "current");
UpgradeUtilities.createNameNodeStorageDirs(nameNodeDirs, "previous");
cluster = new MiniDFSCluster.Builder(conf).numDataNodes(0)
.format(false)
.manageDataDfsDirs(false)
.manageNameDfsDirs(false)
.startupOption(StartupOption.ROLLBACK)
.build();
checkResult(NAME_NODE, nameNodeDirs);
cluster.shutdown();
UpgradeUtilities.createEmptyDirs(nameNodeDirs);
log("Normal DataNode rollback", numDirs);
UpgradeUtilities.createNameNodeStorageDirs(nameNodeDirs, "current");
UpgradeUtilities.createNameNodeStorageDirs(nameNodeDirs, "previous");
cluster = new MiniDFSCluster.Builder(conf).numDataNodes(0)
.format(false)
.manageDataDfsDirs(false)
.manageNameDfsDirs(false)
.startupOption(StartupOption.ROLLBACK)
.build();
UpgradeUtilities.createDataNodeStorageDirs(dataNodeDirs, "current");
UpgradeUtilities.createDataNodeStorageDirs(dataNodeDirs, "previous");
cluster.startDataNodes(conf, 1, false, StartupOption.ROLLBACK, null);
checkResult(DATA_NODE, dataNodeDirs);
cluster.shutdown();
UpgradeUtilities.createEmptyDirs(nameNodeDirs);
UpgradeUtilities.createEmptyDirs(dataNodeDirs);
log("NameNode rollback without existing previous dir", numDirs);
UpgradeUtilities.createNameNodeStorageDirs(nameNodeDirs, "current");
startNameNodeShouldFail(StartupOption.ROLLBACK,
"None of the storage directories contain previous fs state");
UpgradeUtilities.createEmptyDirs(nameNodeDirs);
log("DataNode rollback without existing previous dir", numDirs);
UpgradeUtilities.createNameNodeStorageDirs(nameNodeDirs, "current");
cluster = new MiniDFSCluster.Builder(conf).numDataNodes(0)
.format(false)
.manageDataDfsDirs(false)
.manageNameDfsDirs(false)
.startupOption(StartupOption.UPGRADE)
.build();
UpgradeUtilities.createDataNodeStorageDirs(dataNodeDirs, "current");
cluster.startDataNodes(conf, 1, false, StartupOption.ROLLBACK, null);
cluster.shutdown();
UpgradeUtilities.createEmptyDirs(nameNodeDirs);
UpgradeUtilities.createEmptyDirs(dataNodeDirs);
log("DataNode rollback with future stored layout version in previous", numDirs);
UpgradeUtilities.createNameNodeStorageDirs(nameNodeDirs, "current");
UpgradeUtilities.createNameNodeStorageDirs(nameNodeDirs, "previous");
cluster = new MiniDFSCluster.Builder(conf).numDataNodes(0)
.format(false)
.manageDataDfsDirs(false)
.manageNameDfsDirs(false)
.startupOption(StartupOption.ROLLBACK)
.build();
UpgradeUtilities.createDataNodeStorageDirs(dataNodeDirs, "current");
baseDirs = UpgradeUtilities.createDataNodeStorageDirs(dataNodeDirs, "previous");
storageInfo = new StorageInfo(Integer.MIN_VALUE,
UpgradeUtilities.getCurrentNamespaceID(cluster),
UpgradeUtilities.getCurrentClusterID(cluster),
UpgradeUtilities.getCurrentFsscTime(cluster));
UpgradeUtilities.createDataNodeVersionFile(baseDirs, storageInfo,
UpgradeUtilities.getCurrentBlockPoolID(cluster));
startBlockPoolShouldFail(StartupOption.ROLLBACK,
cluster.getNamesystem().getBlockPoolId());
cluster.shutdown();
UpgradeUtilities.createEmptyDirs(nameNodeDirs);
UpgradeUtilities.createEmptyDirs(dataNodeDirs);
log("DataNode rollback with newer fsscTime in previous", numDirs);
UpgradeUtilities.createNameNodeStorageDirs(nameNodeDirs, "current");
UpgradeUtilities.createNameNodeStorageDirs(nameNodeDirs, "previous");
cluster = new MiniDFSCluster.Builder(conf).numDataNodes(0)
.format(false)
.manageDataDfsDirs(false)
.manageNameDfsDirs(false)
.startupOption(StartupOption.ROLLBACK)
.build();
UpgradeUtilities.createDataNodeStorageDirs(dataNodeDirs, "current");
baseDirs = UpgradeUtilities.createDataNodeStorageDirs(dataNodeDirs, "previous");
storageInfo = new StorageInfo(UpgradeUtilities.getCurrentLayoutVersion(),
UpgradeUtilities.getCurrentNamespaceID(cluster),
UpgradeUtilities.getCurrentClusterID(cluster), Long.MAX_VALUE);
UpgradeUtilities.createDataNodeVersionFile(baseDirs, storageInfo,
UpgradeUtilities.getCurrentBlockPoolID(cluster));
startBlockPoolShouldFail(StartupOption.ROLLBACK,
cluster.getNamesystem().getBlockPoolId());
cluster.shutdown();
UpgradeUtilities.createEmptyDirs(nameNodeDirs);
UpgradeUtilities.createEmptyDirs(dataNodeDirs);
log("NameNode rollback with no edits file", numDirs);
UpgradeUtilities.createNameNodeStorageDirs(nameNodeDirs, "current");
baseDirs = UpgradeUtilities.createNameNodeStorageDirs(nameNodeDirs, "previous");
deleteMatchingFiles(baseDirs, "edits.*");
startNameNodeShouldFail(StartupOption.ROLLBACK,
"Gap in transactions. Expected to be able to read up until at least txid ");
UpgradeUtilities.createEmptyDirs(nameNodeDirs);
log("NameNode rollback with no image file", numDirs);
UpgradeUtilities.createNameNodeStorageDirs(nameNodeDirs, "current");
baseDirs = UpgradeUtilities.createNameNodeStorageDirs(nameNodeDirs, "previous");
deleteMatchingFiles(baseDirs, "fsimage_.*");
startNameNodeShouldFail(StartupOption.ROLLBACK,
"No valid image files found");
UpgradeUtilities.createEmptyDirs(nameNodeDirs);
log("NameNode rollback with corrupt version file", numDirs);
UpgradeUtilities.createNameNodeStorageDirs(nameNodeDirs, "current");
baseDirs = UpgradeUtilities.createNameNodeStorageDirs(nameNodeDirs, "previous");
for (File f : baseDirs) {
UpgradeUtilities.corruptFile(
new File(f,"VERSION"),
"layoutVersion".getBytes(Charsets.UTF_8),
"xxxxxxxxxxxxx".getBytes(Charsets.UTF_8));
}
startNameNodeShouldFail(StartupOption.ROLLBACK,
"file VERSION has layoutVersion missing");
UpgradeUtilities.createEmptyDirs(nameNodeDirs);
log("NameNode rollback with old layout version in previous", numDirs);
UpgradeUtilities.createNameNodeStorageDirs(nameNodeDirs, "current");
baseDirs = UpgradeUtilities.createNameNodeStorageDirs(nameNodeDirs, "previous");
storageInfo = new StorageInfo(1,
UpgradeUtilities.getCurrentNamespaceID(null),
UpgradeUtilities.getCurrentClusterID(null),
UpgradeUtilities.getCurrentFsscTime(null));
UpgradeUtilities.createNameNodeVersionFile(conf, baseDirs,
storageInfo, UpgradeUtilities.getCurrentBlockPoolID(cluster));
startNameNodeShouldFail(StartupOption.ROLLBACK,
"Cannot rollback to storage version 1 using this version");
UpgradeUtilities.createEmptyDirs(nameNodeDirs);
} // end numDir loop
}
|
diff --git a/UselessUtility/src/pw/svn/util/MessageManipulator.java b/UselessUtility/src/pw/svn/util/MessageManipulator.java
index 98882cd..7de7d52 100644
--- a/UselessUtility/src/pw/svn/util/MessageManipulator.java
+++ b/UselessUtility/src/pw/svn/util/MessageManipulator.java
@@ -1,76 +1,76 @@
package pw.svn.util;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Random;
public class MessageManipulator {
private static MessageDigest digest;
static String[] emoticons = { "o_o", ":D", ":I", "xD", ":|", ":O", ":P",
"._.", ">.<", "(o_o)", ":L", ":c)", ">:/", "�.�" };
private static Random rand = new Random();
public static void main(String[] args) {
System.out.println(manipulate("alo"));
}
public static String manipulate(String message) {
boolean done = false;
String tmp = message;
StringBuilder sb = new StringBuilder();
int i = 0;
while (!done) {
tmp = tmp.replaceFirst(" ?:-?[a-zA-Z\\(\\)\\[\\]]{1,1} ", (char) 0x4 + " "
+ emoticons[rand.nextInt(emoticons.length)] + " " + (char) 0x3);
if (tmp.contains((char) 0x3 + "")) {
- sb.append(hash(tmp.substring(0, tmp.indexOf((char) 0x4)).trim()) + tmp.substring(tmp.indexOf((char) 0x4) + 1, tmp.indexOf((char) 0x3)));
+ sb.append(hash(tmp.substring(0, tmp.indexOf((char) 0x4) - 1).trim()) + tmp.substring(tmp.indexOf((char) 0x4) + 1, tmp.indexOf((char) 0x3)));
tmp = tmp.substring(tmp.indexOf((char) 0x3) + 1);
i++;
} else {
done = true;
if (i == 0) {
sb.append(hash(tmp).trim());
}
}
}
message = sb.toString();
return message;
}
/**
* Converts the bytes in the MessageDigest into hex
* @return sb.toString() - the bytes in the MessageDigest in hex
*/
public static String hash(String message){
StringBuilder messageBuilder = new StringBuilder();
messageBuilder.append(message);
messageBuilder.append(getSalt());
try {
digest = MessageDigest.getInstance("MD5");
digest.update(messageBuilder.toString().getBytes());
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
StringBuffer sb = new StringBuffer();
byte[] byteData = digest.digest();
for (int i = 0; i < byteData.length; i++) {
sb.append(Integer.toString((byteData[i] & 0xff) + 0x100, 16).substring(1));
}
return sb.toString();
}
public static String getSalt(){
StringBuilder sb = new StringBuilder();
for(int i = 0; i < 30; i++){
sb.append(Integer.toHexString(rand.nextInt(16)));
}
return sb.toString();
}
}
| true | true | public static String manipulate(String message) {
boolean done = false;
String tmp = message;
StringBuilder sb = new StringBuilder();
int i = 0;
while (!done) {
tmp = tmp.replaceFirst(" ?:-?[a-zA-Z\\(\\)\\[\\]]{1,1} ", (char) 0x4 + " "
+ emoticons[rand.nextInt(emoticons.length)] + " " + (char) 0x3);
if (tmp.contains((char) 0x3 + "")) {
sb.append(hash(tmp.substring(0, tmp.indexOf((char) 0x4)).trim()) + tmp.substring(tmp.indexOf((char) 0x4) + 1, tmp.indexOf((char) 0x3)));
tmp = tmp.substring(tmp.indexOf((char) 0x3) + 1);
i++;
} else {
done = true;
if (i == 0) {
sb.append(hash(tmp).trim());
}
}
}
message = sb.toString();
return message;
}
| public static String manipulate(String message) {
boolean done = false;
String tmp = message;
StringBuilder sb = new StringBuilder();
int i = 0;
while (!done) {
tmp = tmp.replaceFirst(" ?:-?[a-zA-Z\\(\\)\\[\\]]{1,1} ", (char) 0x4 + " "
+ emoticons[rand.nextInt(emoticons.length)] + " " + (char) 0x3);
if (tmp.contains((char) 0x3 + "")) {
sb.append(hash(tmp.substring(0, tmp.indexOf((char) 0x4) - 1).trim()) + tmp.substring(tmp.indexOf((char) 0x4) + 1, tmp.indexOf((char) 0x3)));
tmp = tmp.substring(tmp.indexOf((char) 0x3) + 1);
i++;
} else {
done = true;
if (i == 0) {
sb.append(hash(tmp).trim());
}
}
}
message = sb.toString();
return message;
}
|
diff --git a/public/java/src/org/broadinstitute/sting/gatk/walkers/annotator/MVLikelihoodRatio.java b/public/java/src/org/broadinstitute/sting/gatk/walkers/annotator/MVLikelihoodRatio.java
index 8da64608f..bd0d4e3fb 100755
--- a/public/java/src/org/broadinstitute/sting/gatk/walkers/annotator/MVLikelihoodRatio.java
+++ b/public/java/src/org/broadinstitute/sting/gatk/walkers/annotator/MVLikelihoodRatio.java
@@ -1,58 +1,58 @@
package org.broadinstitute.sting.gatk.walkers.annotator;
import org.broadinstitute.sting.gatk.contexts.AlignmentContext;
import org.broadinstitute.sting.gatk.contexts.ReferenceContext;
import org.broadinstitute.sting.gatk.refdata.RefMetaDataTracker;
import org.broadinstitute.sting.gatk.walkers.annotator.interfaces.AnnotatorCompatibleWalker;
import org.broadinstitute.sting.gatk.walkers.annotator.interfaces.ExperimentalAnnotation;
import org.broadinstitute.sting.gatk.walkers.annotator.interfaces.InfoFieldAnnotation;
import org.broadinstitute.sting.utils.BaseUtils;
import org.broadinstitute.sting.utils.MendelianViolation;
import org.broadinstitute.sting.utils.codecs.vcf.VCFFilterHeaderLine;
import org.broadinstitute.sting.utils.codecs.vcf.VCFHeaderLineType;
import org.broadinstitute.sting.utils.codecs.vcf.VCFInfoHeaderLine;
import org.broadinstitute.sting.utils.exceptions.UserException;
import org.broadinstitute.sting.utils.pileup.PileupElement;
import org.broadinstitute.sting.utils.variantcontext.VariantContext;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Created by IntelliJ IDEA.
* User: chartl
* Date: 9/14/11
* Time: 12:24 PM
* To change this template use File | Settings | File Templates.
*/
public class MVLikelihoodRatio extends InfoFieldAnnotation implements ExperimentalAnnotation {
private MendelianViolation mendelianViolation = null;
public Map<String, Object> annotate(RefMetaDataTracker tracker, AnnotatorCompatibleWalker walker, ReferenceContext ref, Map<String, AlignmentContext> stratifiedContexts, VariantContext vc) {
if ( mendelianViolation == null ) {
if ( walker instanceof VariantAnnotator && ((VariantAnnotator) walker).familyStr != null) {
mendelianViolation = new MendelianViolation(((VariantAnnotator)walker).familyStr, ((VariantAnnotator)walker).minGenotypeQualityP );
}
else {
- throw new UserException("Mendelian violation annotation can only be used from the Variant Annotator");
+ throw new UserException("Mendelian violation annotation can only be used from the Variant Annotator, and must be provided a valid Family String file (-family) on the command line.");
}
}
Map<String,Object> toRet = new HashMap<String,Object>(1);
boolean hasAppropriateGenotypes = vc.hasGenotype(mendelianViolation.getSampleChild()) && vc.getGenotype(mendelianViolation.getSampleChild()).hasLikelihoods() &&
vc.hasGenotype(mendelianViolation.getSampleDad()) && vc.getGenotype(mendelianViolation.getSampleDad()).hasLikelihoods() &&
vc.hasGenotype(mendelianViolation.getSampleMom()) && vc.getGenotype(mendelianViolation.getSampleMom()).hasLikelihoods();
if ( hasAppropriateGenotypes )
toRet.put("MVLR",mendelianViolation.violationLikelihoodRatio(vc));
return toRet;
}
// return the descriptions used for the VCF INFO meta field
public List<String> getKeyNames() { return Arrays.asList("MVLR"); }
public List<VCFInfoHeaderLine> getDescriptions() { return Arrays.asList(new VCFInfoHeaderLine("MVLR", 1, VCFHeaderLineType.Float, "Mendelian violation likelihood ratio: L[MV] - L[No MV]")); }
}
| true | true | public Map<String, Object> annotate(RefMetaDataTracker tracker, AnnotatorCompatibleWalker walker, ReferenceContext ref, Map<String, AlignmentContext> stratifiedContexts, VariantContext vc) {
if ( mendelianViolation == null ) {
if ( walker instanceof VariantAnnotator && ((VariantAnnotator) walker).familyStr != null) {
mendelianViolation = new MendelianViolation(((VariantAnnotator)walker).familyStr, ((VariantAnnotator)walker).minGenotypeQualityP );
}
else {
throw new UserException("Mendelian violation annotation can only be used from the Variant Annotator");
}
}
Map<String,Object> toRet = new HashMap<String,Object>(1);
boolean hasAppropriateGenotypes = vc.hasGenotype(mendelianViolation.getSampleChild()) && vc.getGenotype(mendelianViolation.getSampleChild()).hasLikelihoods() &&
vc.hasGenotype(mendelianViolation.getSampleDad()) && vc.getGenotype(mendelianViolation.getSampleDad()).hasLikelihoods() &&
vc.hasGenotype(mendelianViolation.getSampleMom()) && vc.getGenotype(mendelianViolation.getSampleMom()).hasLikelihoods();
if ( hasAppropriateGenotypes )
toRet.put("MVLR",mendelianViolation.violationLikelihoodRatio(vc));
return toRet;
}
| public Map<String, Object> annotate(RefMetaDataTracker tracker, AnnotatorCompatibleWalker walker, ReferenceContext ref, Map<String, AlignmentContext> stratifiedContexts, VariantContext vc) {
if ( mendelianViolation == null ) {
if ( walker instanceof VariantAnnotator && ((VariantAnnotator) walker).familyStr != null) {
mendelianViolation = new MendelianViolation(((VariantAnnotator)walker).familyStr, ((VariantAnnotator)walker).minGenotypeQualityP );
}
else {
throw new UserException("Mendelian violation annotation can only be used from the Variant Annotator, and must be provided a valid Family String file (-family) on the command line.");
}
}
Map<String,Object> toRet = new HashMap<String,Object>(1);
boolean hasAppropriateGenotypes = vc.hasGenotype(mendelianViolation.getSampleChild()) && vc.getGenotype(mendelianViolation.getSampleChild()).hasLikelihoods() &&
vc.hasGenotype(mendelianViolation.getSampleDad()) && vc.getGenotype(mendelianViolation.getSampleDad()).hasLikelihoods() &&
vc.hasGenotype(mendelianViolation.getSampleMom()) && vc.getGenotype(mendelianViolation.getSampleMom()).hasLikelihoods();
if ( hasAppropriateGenotypes )
toRet.put("MVLR",mendelianViolation.violationLikelihoodRatio(vc));
return toRet;
}
|
diff --git a/rultor-spi/src/test/java/com/rultor/tools/ExceptionsTest.java b/rultor-spi/src/test/java/com/rultor/tools/ExceptionsTest.java
index 5ed5ad265..685f009ac 100644
--- a/rultor-spi/src/test/java/com/rultor/tools/ExceptionsTest.java
+++ b/rultor-spi/src/test/java/com/rultor/tools/ExceptionsTest.java
@@ -1,83 +1,86 @@
/**
* Copyright (c) 2009-2013, rultor.com
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met: 1) Redistributions of source code must retain the above
* copyright notice, this list of conditions and the following
* disclaimer. 2) Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution. 3) Neither the name of the rultor.com nor
* the names of its contributors may be used to endorse or promote
* products derived from this software without specific prior written
* permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT
* NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
* THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.rultor.tools;
import java.io.IOException;
import org.hamcrest.MatcherAssert;
import org.hamcrest.Matchers;
import org.junit.Test;
/**
* Test case for {@link Exceptions}.
* @author Krzysztof Krason ([email protected])
* @author Yegor Bugayenko ([email protected])
* @version $Id$
*/
public final class ExceptionsTest {
/**
* Handling of null exception.
*/
@Test
public void nullExceptionMessage() {
MatcherAssert.assertThat(
Exceptions.message(null), Matchers.equalTo("")
);
}
/**
* Single exception with no cause.
*/
@Test
public void singleExceptionMessage() {
MatcherAssert.assertThat(
Exceptions.message(new IOException("hello, world!")),
Matchers.equalTo("IOException: hello, world!")
);
}
/**
* Exception with a cause.
*/
@Test
public void twoExceptionMessage() {
MatcherAssert.assertThat(
Exceptions.message(
new IllegalArgumentException(
"hey",
- new IOException("file not found")
+ new IOException("not found")
)
),
Matchers.equalTo(
- "IllegalArgumentException: hey\nIOException: file not found"
+ String.format(
+ "IllegalArgumentException: hey%sIOException: not found",
+ System.getProperty("line.separator")
+ )
)
);
}
}
| false | true | public void twoExceptionMessage() {
MatcherAssert.assertThat(
Exceptions.message(
new IllegalArgumentException(
"hey",
new IOException("file not found")
)
),
Matchers.equalTo(
"IllegalArgumentException: hey\nIOException: file not found"
)
);
}
| public void twoExceptionMessage() {
MatcherAssert.assertThat(
Exceptions.message(
new IllegalArgumentException(
"hey",
new IOException("not found")
)
),
Matchers.equalTo(
String.format(
"IllegalArgumentException: hey%sIOException: not found",
System.getProperty("line.separator")
)
)
);
}
|
diff --git a/DJBDD/src/djbdd/BDDApply.java b/DJBDD/src/djbdd/BDDApply.java
index 4c90747..0248ef4 100644
--- a/DJBDD/src/djbdd/BDDApply.java
+++ b/DJBDD/src/djbdd/BDDApply.java
@@ -1,263 +1,263 @@
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package djbdd;
import djbdd.timemeasurer.TimeMeasurer;
import java.util.*;
/**
* Apply operation for BDDs
* Contains the apply computation.
* @author diegoj
*/
public class BDDApply {
/** First bdd */
private final BDD bdd1;
/** Second bdd */
private final BDD bdd2;
/** Resulting bdd */
BDD bdd;
/** Operation index */
private final int operation;
/** Cache table **/
HashMap<String,Vertex> G;
/** AND logic operation key */
public final static int OP_AND = 1;
/** OR logic operation key */
public final static int OP_OR = 2;
/** IF logic operation key */
public final static int OP_IF = 3;
/** IFF logic operation key */
public final static int OP_IFF = 4;
/** NAND logic operation key */
public final static int OP_NAND = 5;
/** NOR logic operation key */
public final static int OP_NOR = 6;
/** Not implication operation key */
public final static int OP_NOTIF = 7;
/** Is different operation key */
public final static int OP_ISDIFFERENT = 8;
/**
* Gets the operation from a human-readable string.
* @param operation String that contains the operation in human-readable form.
* @return int Integer key of the operation.
*/
private static int getOperation(String operation)throws Exception{
if(operation.equals("&&") || operation.equalsIgnoreCase("and") || operation.equalsIgnoreCase(".") || operation.equalsIgnoreCase("·"))
return OP_AND;
if(operation.equals("||") || operation.equalsIgnoreCase("or") || operation.equalsIgnoreCase("+"))
return OP_OR;
if(operation.equalsIgnoreCase("nor"))
return OP_NOR;
if(operation.equalsIgnoreCase("nand"))
return OP_NAND;
if(operation.equalsIgnoreCase("<=>") || operation.equalsIgnoreCase("iff") || operation.equalsIgnoreCase("<->"))
return OP_IFF;
if(operation.equalsIgnoreCase("!="))
return OP_ISDIFFERENT;
if(operation.equalsIgnoreCase("=>") || operation.equalsIgnoreCase("if") || operation.equalsIgnoreCase("->"))
return OP_IF;
if(operation.equalsIgnoreCase("!=>") || operation.equalsIgnoreCase("notif") || operation.equalsIgnoreCase("!->"))
return OP_NOTIF;
throw new Exception("Operator "+operation+" undefined");
}
/**
* Construct the function string for the resulting BDD.
* @return String Formula for the resulting BDD obtained of operating the other BDDs.
*/
private String getFunction(){
String function1 = bdd1.function.trim();
String function2 = bdd2.function.trim();
// Get the function based on the operation
if (operation == OP_AND) {
return function1 + " && " + function2;
}
if (operation == OP_OR) {
return function1 + " || " + function2;
}
if (operation == OP_IFF) {
return "(" + function1 + " || !(" + function2 + ")) && (!(" + function1 + ") || " + function2 + ")";
}
if (operation == OP_IF) {
return "(!(" + function1 + ") || (" + function2 + "))";
}
if (operation == OP_NOR) {
return "!(" + function1 + " || " + function2 + ")";
}
if (operation == OP_NAND) {
return "!(" + function1 + " &&" + function2 + ")";
}
if (operation == OP_NOTIF) {
return "(("+function1+ ") && !("+function2+"))";
}
if (operation == OP_ISDIFFERENT) {
return "((" + function1 + ") && !(" + function2 + ")) || (!(" + function1 + ") && (" + function2 + "))";
}
// I don't want exceptions, only FATAL ERRORS
System.err.println("BDDApply.getOperation: Operation '" + this.operation + "' not recognized");
System.err.flush();
System.exit(-1);
return "Operator '" + operation + "' undefined in BDDApply.getFunction";
}
/**
* Constructs an BDDApply object, container of the Andersen design of apply function.
* @param operation Operation in human-readable form.
* @param bdd1 First bdd operand.
* @param bdd2 Second bdd operand.
*/
public BDDApply(String operation, BDD bdd1, BDD bdd2)throws Exception{
this.bdd1 = bdd1;
this.bdd2 = bdd2;
this.operation = BDDApply.getOperation(operation);
}
/**
* Computes the operation between two leaf vertices.
* @param v1 A leaf vertex.
* @param v2 Another leaf vertex.
* @return boolean Result of compute the operation between the vertex values.
*/
private boolean op(Vertex v1, Vertex v2){
boolean v1Value = v1.value();
boolean v2Value = v2.value();
if (this.operation == OP_AND) {
return v1Value && v2Value;
}
if (this.operation == OP_OR) {
return v1Value || v2Value;
}
if (this.operation == OP_IF) {
return (!v1Value || v2Value);
}
if (this.operation == OP_IFF) {
return (v1Value == v2Value);
}
if (this.operation == OP_NOR) {
return !(v1Value || v2Value);
}
if (this.operation == OP_NAND) {
return !(v1Value && v2Value);
}
if (this.operation == OP_NOTIF) {
return (v1Value && !v2Value);
}
if (this.operation == OP_ISDIFFERENT) {
return (v1Value != v2Value);
}
// I don't want exceptions, only FATAL ERRORS
System.err.println("BDDApply.op: Operation '"+this.operation+"' not recognized");
System.err.flush();
System.exit(-1);
return false;
}
/**
* Core of the apply algorithm.
* Computes recursively a operation between two BDDs.
* @param v1 Vertex of BDD1.
* @param v2 Vertex of BDD2.
* @return Vertex Result of doing a recursive call to app.
*/
private Vertex app(Vertex v1, Vertex v2){
// Hash key of the computation of the subtree of these two vertices
String key = "1-"+v1.index+"+2-"+v2.index;
if( G.containsKey(key) ){
return G.get(key);
}
if(v1.isLeaf() && v2.isLeaf())
{
if(this.op(v1,v2)){
return BDD.T.True;
}
return BDD.T.False;
}
int var = -1;
Vertex low = null;
Vertex high = null;
// v1.index < v2.index
if (!v1.isLeaf() && (v2.isLeaf() || v1.variable < v2.variable)) {
var = v1.variable;
low = this.app(v1.low(), v2);
high = this.app(v1.high(), v2);
} else if (v1.isLeaf() || v1.variable > v2.variable) {
var = v2.variable;
low = this.app(v1, v2.low());
high = this.app(v1, v2.high());
} else {
var = v1.variable;
low = this.app(v1.low(), v2.low());
high = this.app(v1.high(), v2.high());
}
- // Respect the non-redundant propierty:
+ // Respect the non-redundant property:
// "No vertex shall be one whose low and high indices are the same."
if(low.index == high.index){
return low;
}
- // Respect the uniqueness propierty:
+ // Respect the uniqueness property:
// "No vertex shall be one that contains same variable, low, high indices as other."
Vertex u = BDD.T.add(var, low, high);
this.G.put(key, u);
return u;
}
/**
* Public call to execute the apply algorithm.
* Note: the first BDD1 is MODIFIED.
* The returned BDD is the same as BDD1, it is keept to don't break anything.
* @return BDD BDD Tree with the operatian computed for bdd1 and bdd2.
*/
public BDD run(){
TimeMeasurer t = new TimeMeasurer("========= apply =========");
// Cache to avoid repeated computations
this.G = new HashMap<String,Vertex>();
String function = this.getFunction();
// Fill this.T with vertices of bdd1 and bdd2
Vertex root = this.app(bdd1.root(), bdd2.root());
// We get the variable indices present in both BDDs as fast as we can
/*
HashSet<Integer> presentIndicesSet = new HashSet<Integer>(bdd1.variable_ordering.size()+bdd2.variable_ordering.size());
presentIndicesSet.addAll(bdd1.variable_ordering);
presentIndicesSet.addAll(bdd2.variable_ordering);
ArrayList<Integer> presentVariableIndices = new ArrayList<Integer>(presentIndicesSet);
*/
// Construction of new BDD
this.bdd = new BDD(function, root);
t.end().show();
// Return the new BDD computed
return this.bdd;
}
}
| false | true | private Vertex app(Vertex v1, Vertex v2){
// Hash key of the computation of the subtree of these two vertices
String key = "1-"+v1.index+"+2-"+v2.index;
if( G.containsKey(key) ){
return G.get(key);
}
if(v1.isLeaf() && v2.isLeaf())
{
if(this.op(v1,v2)){
return BDD.T.True;
}
return BDD.T.False;
}
int var = -1;
Vertex low = null;
Vertex high = null;
// v1.index < v2.index
if (!v1.isLeaf() && (v2.isLeaf() || v1.variable < v2.variable)) {
var = v1.variable;
low = this.app(v1.low(), v2);
high = this.app(v1.high(), v2);
} else if (v1.isLeaf() || v1.variable > v2.variable) {
var = v2.variable;
low = this.app(v1, v2.low());
high = this.app(v1, v2.high());
} else {
var = v1.variable;
low = this.app(v1.low(), v2.low());
high = this.app(v1.high(), v2.high());
}
// Respect the non-redundant propierty:
// "No vertex shall be one whose low and high indices are the same."
if(low.index == high.index){
return low;
}
// Respect the uniqueness propierty:
// "No vertex shall be one that contains same variable, low, high indices as other."
Vertex u = BDD.T.add(var, low, high);
this.G.put(key, u);
return u;
}
| private Vertex app(Vertex v1, Vertex v2){
// Hash key of the computation of the subtree of these two vertices
String key = "1-"+v1.index+"+2-"+v2.index;
if( G.containsKey(key) ){
return G.get(key);
}
if(v1.isLeaf() && v2.isLeaf())
{
if(this.op(v1,v2)){
return BDD.T.True;
}
return BDD.T.False;
}
int var = -1;
Vertex low = null;
Vertex high = null;
// v1.index < v2.index
if (!v1.isLeaf() && (v2.isLeaf() || v1.variable < v2.variable)) {
var = v1.variable;
low = this.app(v1.low(), v2);
high = this.app(v1.high(), v2);
} else if (v1.isLeaf() || v1.variable > v2.variable) {
var = v2.variable;
low = this.app(v1, v2.low());
high = this.app(v1, v2.high());
} else {
var = v1.variable;
low = this.app(v1.low(), v2.low());
high = this.app(v1.high(), v2.high());
}
// Respect the non-redundant property:
// "No vertex shall be one whose low and high indices are the same."
if(low.index == high.index){
return low;
}
// Respect the uniqueness property:
// "No vertex shall be one that contains same variable, low, high indices as other."
Vertex u = BDD.T.add(var, low, high);
this.G.put(key, u);
return u;
}
|
diff --git a/src/com/android/mms/transaction/MessagingNotification.java b/src/com/android/mms/transaction/MessagingNotification.java
index 3042b7fd..64cddc29 100644
--- a/src/com/android/mms/transaction/MessagingNotification.java
+++ b/src/com/android/mms/transaction/MessagingNotification.java
@@ -1,1554 +1,1554 @@
/*
* Copyright (C) 2008 Esmertec AG.
* Copyright (C) 2008 The Android Open Source Project
* QuickMessage Copyright (C) 2012 The CyanogenMod Project (DvTonder)
*
* 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.mms.transaction;
import static com.google.android.mms.pdu.PduHeaders.MESSAGE_TYPE_NOTIFICATION_IND;
import static com.google.android.mms.pdu.PduHeaders.MESSAGE_TYPE_RETRIEVE_CONF;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.TaskStackBuilder;
import android.content.BroadcastReceiver;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.database.Cursor;
import android.database.sqlite.SqliteWrapper;
import android.graphics.Bitmap;
import android.graphics.Typeface;
import android.graphics.drawable.BitmapDrawable;
import android.media.AudioManager;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.Parcel;
import android.os.Parcelable;
import android.preference.PreferenceManager;
import android.provider.Telephony.Mms;
import android.provider.Telephony.Sms;
import android.telephony.TelephonyManager;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.SpannableStringBuilder;
import android.text.TextUtils;
import android.text.style.StyleSpan;
import android.text.style.TextAppearanceSpan;
import android.util.Log;
import android.widget.Toast;
import com.android.mms.LogTag;
import com.android.mms.R;
import com.android.mms.data.Contact;
import com.android.mms.data.Conversation;
import com.android.mms.data.WorkingMessage;
import com.android.mms.model.SlideModel;
import com.android.mms.model.SlideshowModel;
import com.android.mms.quickmessage.QmMarkRead;
import com.android.mms.quickmessage.QuickMessagePopup;
import com.android.mms.ui.ComposeMessageActivity;
import com.android.mms.ui.ConversationList;
import com.android.mms.ui.MessageUtils;
import com.android.mms.ui.MessagingPreferenceActivity;
import com.android.mms.util.AddressUtils;
import com.android.mms.util.DownloadManager;
import com.android.mms.widget.MmsWidgetProvider;
import com.google.android.mms.MmsException;
import android.provider.Settings;
import com.google.android.mms.pdu.EncodedStringValue;
import com.google.android.mms.pdu.GenericPdu;
import com.google.android.mms.pdu.MultimediaMessagePdu;
import com.google.android.mms.pdu.PduHeaders;
import com.google.android.mms.pdu.PduPersister;
/**
* This class is used to update the notification indicator. It will check whether
* there are unread messages. If yes, it would show the notification indicator,
* otherwise, hide the indicator.
*/
public class MessagingNotification {
private static final String TAG = LogTag.APP;
private static final boolean DEBUG = false;
public static final int NOTIFICATION_ID = 123;
public static final int MESSAGE_FAILED_NOTIFICATION_ID = 789;
public static final int DOWNLOAD_FAILED_NOTIFICATION_ID = 531;
/**
* This is the volume at which to play the in-conversation notification sound,
* expressed as a fraction of the system notification volume.
*/
private static final float IN_CONVERSATION_NOTIFICATION_VOLUME = 0.25f;
// This must be consistent with the column constants below.
private static final String[] MMS_STATUS_PROJECTION = new String[] {
Mms.THREAD_ID, Mms.DATE, Mms._ID, Mms.SUBJECT, Mms.SUBJECT_CHARSET };
// This must be consistent with the column constants below.
private static final String[] SMS_STATUS_PROJECTION = new String[] {
Sms.THREAD_ID, Sms.DATE, Sms.ADDRESS, Sms.SUBJECT, Sms.BODY };
// These must be consistent with MMS_STATUS_PROJECTION and
// SMS_STATUS_PROJECTION.
private static final int COLUMN_THREAD_ID = 0;
private static final int COLUMN_DATE = 1;
private static final int COLUMN_MMS_ID = 2;
private static final int COLUMN_SMS_ADDRESS = 2;
private static final int COLUMN_SUBJECT = 3;
private static final int COLUMN_SUBJECT_CS = 4;
private static final int COLUMN_SMS_BODY = 4;
private static final String[] SMS_THREAD_ID_PROJECTION = new String[] { Sms.THREAD_ID };
private static final String[] MMS_THREAD_ID_PROJECTION = new String[] { Mms.THREAD_ID };
private static final String NEW_INCOMING_SM_CONSTRAINT =
"(" + Sms.TYPE + " = " + Sms.MESSAGE_TYPE_INBOX
+ " AND " + Sms.SEEN + " = 0)";
private static final String NEW_DELIVERY_SM_CONSTRAINT =
"(" + Sms.TYPE + " = " + Sms.MESSAGE_TYPE_SENT
+ " AND " + Sms.STATUS + " = "+ Sms.STATUS_COMPLETE +")";
private static final String NEW_INCOMING_MM_CONSTRAINT =
"(" + Mms.MESSAGE_BOX + "=" + Mms.MESSAGE_BOX_INBOX
+ " AND " + Mms.SEEN + "=0"
+ " AND (" + Mms.MESSAGE_TYPE + "=" + MESSAGE_TYPE_NOTIFICATION_IND
+ " OR " + Mms.MESSAGE_TYPE + "=" + MESSAGE_TYPE_RETRIEVE_CONF + "))";
private static final NotificationInfoComparator INFO_COMPARATOR =
new NotificationInfoComparator();
private static final Uri UNDELIVERED_URI = Uri.parse("content://mms-sms/undelivered");
private final static String NOTIFICATION_DELETED_ACTION =
"com.android.mms.NOTIFICATION_DELETED_ACTION";
public static class OnDeletedReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if (Log.isLoggable(LogTag.APP, Log.VERBOSE)) {
Log.d(TAG, "[MessagingNotification] clear notification: mark all msgs seen");
}
Conversation.markAllConversationsAsSeen(context);
}
}
public static final long THREAD_ALL = -1;
public static final long THREAD_NONE = -2;
/**
* Keeps track of the thread ID of the conversation that's currently displayed to the user
*/
private static long sCurrentlyDisplayedThreadId;
private static final Object sCurrentlyDisplayedThreadLock = new Object();
private static OnDeletedReceiver sNotificationDeletedReceiver = new OnDeletedReceiver();
private static Intent sNotificationOnDeleteIntent;
private static Handler sHandler = new Handler();
private static PduPersister sPduPersister;
private static final int MAX_BITMAP_DIMEN_DP = 360;
private static float sScreenDensity;
private static final int MAX_MESSAGES_TO_SHOW = 8; // the maximum number of new messages to
// show in a single notification.
private MessagingNotification() {
}
public static void init(Context context) {
// set up the intent filter for notification deleted action
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(NOTIFICATION_DELETED_ACTION);
// TODO: should we unregister when the app gets killed?
context.registerReceiver(sNotificationDeletedReceiver, intentFilter);
sPduPersister = PduPersister.getPduPersister(context);
// initialize the notification deleted action
sNotificationOnDeleteIntent = new Intent(NOTIFICATION_DELETED_ACTION);
sScreenDensity = context.getResources().getDisplayMetrics().density;
}
/**
* Specifies which message thread is currently being viewed by the user. New messages in that
* thread will not generate a notification icon and will play the notification sound at a lower
* volume. Make sure you set this to THREAD_NONE when the UI component that shows the thread is
* no longer visible to the user (e.g. Activity.onPause(), etc.)
* @param threadId The ID of the thread that the user is currently viewing. Pass THREAD_NONE
* if the user is not viewing a thread, or THREAD_ALL if the user is viewing the conversation
* list (note: that latter one has no effect as of this implementation)
*/
public static void setCurrentlyDisplayedThreadId(long threadId) {
synchronized (sCurrentlyDisplayedThreadLock) {
sCurrentlyDisplayedThreadId = threadId;
if (DEBUG) {
Log.d(TAG, "setCurrentlyDisplayedThreadId: " + sCurrentlyDisplayedThreadId);
}
}
}
/**
* Checks to see if there are any "unseen" messages or delivery
* reports. Shows the most recent notification if there is one.
* Does its work and query in a worker thread.
*
* @param context the context to use
*/
public static void nonBlockingUpdateNewMessageIndicator(final Context context,
final long newMsgThreadId,
final boolean isStatusMessage) {
if (DEBUG) {
Log.d(TAG, "nonBlockingUpdateNewMessageIndicator: newMsgThreadId: " +
newMsgThreadId +
" sCurrentlyDisplayedThreadId: " + sCurrentlyDisplayedThreadId);
}
new Thread(new Runnable() {
@Override
public void run() {
blockingUpdateNewMessageIndicator(context, newMsgThreadId, isStatusMessage);
}
}, "MessagingNotification.nonBlockingUpdateNewMessageIndicator").start();
}
/**
* Checks to see if there are any "unseen" messages or delivery
* reports and builds a sorted (by delivery date) list of unread notifications.
*
* @param context the context to use
* @param newMsgThreadId The thread ID of a new message that we're to notify about; if there's
* no new message, use THREAD_NONE. If we should notify about multiple or unknown thread IDs,
* use THREAD_ALL.
* @param isStatusMessage
*/
public static void blockingUpdateNewMessageIndicator(Context context, long newMsgThreadId,
boolean isStatusMessage) {
if (DEBUG) {
Contact.logWithTrace(TAG, "blockingUpdateNewMessageIndicator: newMsgThreadId: " +
newMsgThreadId);
}
// notificationSet is kept sorted by the incoming message delivery time, with the
// most recent message first.
SortedSet<NotificationInfo> notificationSet =
new TreeSet<NotificationInfo>(INFO_COMPARATOR);
Set<Long> threads = new HashSet<Long>(4);
addMmsNotificationInfos(context, threads, notificationSet);
addSmsNotificationInfos(context, threads, notificationSet);
if (notificationSet.isEmpty()) {
if (DEBUG) {
Log.d(TAG, "blockingUpdateNewMessageIndicator: notificationSet is empty, " +
"canceling existing notifications");
}
cancelNotification(context, NOTIFICATION_ID);
} else {
if (DEBUG || Log.isLoggable(LogTag.APP, Log.VERBOSE)) {
Log.d(TAG, "blockingUpdateNewMessageIndicator: count=" + notificationSet.size() +
", newMsgThreadId=" + newMsgThreadId);
}
synchronized (sCurrentlyDisplayedThreadLock) {
if (newMsgThreadId > 0 && newMsgThreadId == sCurrentlyDisplayedThreadId &&
threads.contains(newMsgThreadId)) {
if (DEBUG) {
Log.d(TAG, "blockingUpdateNewMessageIndicator: newMsgThreadId == " +
"sCurrentlyDisplayedThreadId so NOT showing notification," +
" but playing soft sound. threadId: " + newMsgThreadId);
}
playInConversationNotificationSound(context);
return;
}
}
updateNotification(context, newMsgThreadId != THREAD_NONE, threads.size(),
notificationSet);
}
// And deals with delivery reports (which use Toasts). It's safe to call in a worker
// thread because the toast will eventually get posted to a handler.
MmsSmsDeliveryInfo delivery = getSmsNewDeliveryInfo(context);
if (delivery != null) {
delivery.deliver(context, isStatusMessage);
}
notificationSet.clear();
threads.clear();
}
/**
* Play the in-conversation notification sound (it's the regular notification sound, but
* played at half-volume
*/
private static void playInConversationNotificationSound(Context context) {
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);
String ringtoneStr = sp.getString(MessagingPreferenceActivity.NOTIFICATION_RINGTONE,
null);
if (TextUtils.isEmpty(ringtoneStr)) {
// Nothing to play
return;
}
Uri ringtoneUri = Uri.parse(ringtoneStr);
final NotificationPlayer player = new NotificationPlayer(LogTag.APP);
player.play(context, ringtoneUri, false, AudioManager.STREAM_NOTIFICATION,
IN_CONVERSATION_NOTIFICATION_VOLUME);
// Stop the sound after five seconds to handle continuous ringtones
sHandler.postDelayed(new Runnable() {
@Override
public void run() {
player.stop();
}
}, 5000);
}
/**
* Updates all pending notifications, clearing or updating them as
* necessary.
*/
public static void blockingUpdateAllNotifications(final Context context, long threadId) {
if (DEBUG) {
Contact.logWithTrace(TAG, "blockingUpdateAllNotifications: newMsgThreadId: " +
threadId);
}
nonBlockingUpdateNewMessageIndicator(context, threadId, false);
nonBlockingUpdateSendFailedNotification(context);
updateDownloadFailedNotification(context);
MmsWidgetProvider.notifyDatasetChanged(context);
}
private static final class MmsSmsDeliveryInfo {
public CharSequence mTicker;
public long mTimeMillis;
public MmsSmsDeliveryInfo(CharSequence ticker, long timeMillis) {
mTicker = ticker;
mTimeMillis = timeMillis;
}
public void deliver(Context context, boolean isStatusMessage) {
updateDeliveryNotification(
context, isStatusMessage, mTicker, mTimeMillis);
}
}
public static final class NotificationInfo implements Parcelable {
public final Intent mClickIntent;
public final String mMessage;
public final CharSequence mTicker;
public final long mTimeMillis;
public final String mTitle;
public final Bitmap mAttachmentBitmap;
public final Contact mSender;
public final boolean mIsSms;
public final int mAttachmentType;
public final String mSubject;
public final long mThreadId;
/**
* @param isSms true if sms, false if mms
* @param clickIntent where to go when the user taps the notification
* @param message for a single message, this is the message text
* @param subject text of mms subject
* @param ticker text displayed ticker-style across the notification, typically formatted
* as sender: message
* @param timeMillis date the message was received
* @param title for a single message, this is the sender
* @param attachmentBitmap a bitmap of an attachment, such as a picture or video
* @param sender contact of the sender
* @param attachmentType of the mms attachment
* @param threadId thread this message belongs to
*/
public NotificationInfo(boolean isSms,
Intent clickIntent, String message, String subject,
CharSequence ticker, long timeMillis, String title,
Bitmap attachmentBitmap, Contact sender,
int attachmentType, long threadId) {
mIsSms = isSms;
mClickIntent = clickIntent;
mMessage = message;
mSubject = subject;
mTicker = ticker;
mTimeMillis = timeMillis;
mTitle = title;
mAttachmentBitmap = attachmentBitmap;
mSender = sender;
mAttachmentType = attachmentType;
mThreadId = threadId;
}
public long getTime() {
return mTimeMillis;
}
// This is the message string used in bigText and bigPicture notifications.
public CharSequence formatBigMessage(Context context) {
final TextAppearanceSpan notificationSubjectSpan = new TextAppearanceSpan(
context, R.style.NotificationPrimaryText);
// Change multiple newlines (with potential white space between), into a single new line
final String message =
!TextUtils.isEmpty(mMessage) ? mMessage.replaceAll("\\n\\s+", "\n") : "";
SpannableStringBuilder spannableStringBuilder = new SpannableStringBuilder();
if (!TextUtils.isEmpty(mSubject)) {
spannableStringBuilder.append(mSubject);
spannableStringBuilder.setSpan(notificationSubjectSpan, 0, mSubject.length(), 0);
}
if (mAttachmentType > WorkingMessage.TEXT) {
if (spannableStringBuilder.length() > 0) {
spannableStringBuilder.append('\n');
}
spannableStringBuilder.append(getAttachmentTypeString(context, mAttachmentType));
}
if (mMessage != null) {
if (spannableStringBuilder.length() > 0) {
spannableStringBuilder.append('\n');
}
spannableStringBuilder.append(mMessage);
}
return spannableStringBuilder;
}
// This is the message string used in each line of an inboxStyle notification.
public CharSequence formatInboxMessage(Context context) {
final TextAppearanceSpan notificationSenderSpan = new TextAppearanceSpan(
context, R.style.NotificationPrimaryText);
final TextAppearanceSpan notificationSubjectSpan = new TextAppearanceSpan(
context, R.style.NotificationSubjectText);
// Change multiple newlines (with potential white space between), into a single new line
final String message =
!TextUtils.isEmpty(mMessage) ? mMessage.replaceAll("\\n\\s+", "\n") : "";
SpannableStringBuilder spannableStringBuilder = new SpannableStringBuilder();
final String sender = mSender.getName();
if (!TextUtils.isEmpty(sender)) {
spannableStringBuilder.append(sender);
spannableStringBuilder.setSpan(notificationSenderSpan, 0, sender.length(), 0);
}
String separator = context.getString(R.string.notification_separator);
if (!mIsSms) {
if (!TextUtils.isEmpty(mSubject)) {
if (spannableStringBuilder.length() > 0) {
spannableStringBuilder.append(separator);
}
int start = spannableStringBuilder.length();
spannableStringBuilder.append(mSubject);
spannableStringBuilder.setSpan(notificationSubjectSpan, start,
start + mSubject.length(), 0);
}
if (mAttachmentType > WorkingMessage.TEXT) {
if (spannableStringBuilder.length() > 0) {
spannableStringBuilder.append(separator);
}
spannableStringBuilder.append(getAttachmentTypeString(context, mAttachmentType));
}
}
if (message.length() > 0) {
if (spannableStringBuilder.length() > 0) {
spannableStringBuilder.append(separator);
}
int start = spannableStringBuilder.length();
spannableStringBuilder.append(message);
spannableStringBuilder.setSpan(notificationSubjectSpan, start,
start + message.length(), 0);
}
return spannableStringBuilder;
}
// This is the summary string used in bigPicture notifications.
public CharSequence formatPictureMessage(Context context) {
final TextAppearanceSpan notificationSubjectSpan = new TextAppearanceSpan(
context, R.style.NotificationPrimaryText);
// Change multiple newlines (with potential white space between), into a single new line
final String message =
!TextUtils.isEmpty(mMessage) ? mMessage.replaceAll("\\n\\s+", "\n") : "";
// Show the subject or the message (if no subject)
SpannableStringBuilder spannableStringBuilder = new SpannableStringBuilder();
if (!TextUtils.isEmpty(mSubject)) {
spannableStringBuilder.append(mSubject);
spannableStringBuilder.setSpan(notificationSubjectSpan, 0, mSubject.length(), 0);
}
if (message.length() > 0 && spannableStringBuilder.length() == 0) {
spannableStringBuilder.append(message);
spannableStringBuilder.setSpan(notificationSubjectSpan, 0, message.length(), 0);
}
return spannableStringBuilder;
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel arg0, int arg1) {
arg0.writeByte((byte) (mIsSms ? 1 : 0));
arg0.writeParcelable(mClickIntent, 0);
arg0.writeString(mMessage);
arg0.writeString(mSubject);
arg0.writeCharSequence(mTicker);
arg0.writeLong(mTimeMillis);
arg0.writeString(mTitle);
arg0.writeParcelable(mAttachmentBitmap, 0);
arg0.writeInt(mAttachmentType);
arg0.writeLong(mThreadId);
}
public NotificationInfo(Parcel in) {
mIsSms = in.readByte() == 1;
mClickIntent = in.readParcelable(Intent.class.getClassLoader());
mMessage = in.readString();
mSubject = in.readString();
mTicker = in.readCharSequence();
mTimeMillis = in.readLong();
mTitle = in.readString();
mAttachmentBitmap = in.readParcelable(Bitmap.class.getClassLoader());
mSender = null;
mAttachmentType = in.readInt();
mThreadId = in.readLong();
}
public static final Parcelable.Creator<NotificationInfo> CREATOR = new Parcelable.Creator<NotificationInfo>() {
public NotificationInfo createFromParcel(Parcel in) {
return new NotificationInfo(in);
}
public NotificationInfo[] newArray(int size) {
return new NotificationInfo[size];
}
};
}
// Return a formatted string with all the sender names separated by commas.
private static CharSequence formatSenders(Context context,
ArrayList<NotificationInfo> senders) {
final TextAppearanceSpan notificationSenderSpan = new TextAppearanceSpan(
context, R.style.NotificationPrimaryText);
String separator = context.getString(R.string.enumeration_comma); // ", "
SpannableStringBuilder spannableStringBuilder = new SpannableStringBuilder();
int len = senders.size();
for (int i = 0; i < len; i++) {
if (i > 0) {
spannableStringBuilder.append(separator);
}
spannableStringBuilder.append(senders.get(i).mSender.getName());
}
spannableStringBuilder.setSpan(notificationSenderSpan, 0,
spannableStringBuilder.length(), 0);
return spannableStringBuilder;
}
// Return a formatted string with the attachmentType spelled out as a string. For
// no attachment (or just text), return null.
private static CharSequence getAttachmentTypeString(Context context, int attachmentType) {
final TextAppearanceSpan notificationAttachmentSpan = new TextAppearanceSpan(
context, R.style.NotificationSecondaryText);
int id = 0;
switch (attachmentType) {
case WorkingMessage.AUDIO: id = R.string.attachment_audio; break;
case WorkingMessage.VIDEO: id = R.string.attachment_video; break;
case WorkingMessage.SLIDESHOW: id = R.string.attachment_slideshow; break;
case WorkingMessage.IMAGE: id = R.string.attachment_picture; break;
}
if (id > 0) {
final SpannableString spannableString = new SpannableString(context.getString(id));
spannableString.setSpan(notificationAttachmentSpan,
0, spannableString.length(), 0);
return spannableString;
}
return null;
}
/**
*
* Sorts by the time a notification was received in descending order -- newer first.
*
*/
private static final class NotificationInfoComparator
implements Comparator<NotificationInfo> {
@Override
public int compare(
NotificationInfo info1, NotificationInfo info2) {
return Long.signum(info2.getTime() - info1.getTime());
}
}
private static final void addMmsNotificationInfos(
Context context, Set<Long> threads, SortedSet<NotificationInfo> notificationSet) {
ContentResolver resolver = context.getContentResolver();
// This query looks like this when logged:
// I/Database( 147): elapsedTime4Sql|/data/data/com.android.providers.telephony/databases/
// mmssms.db|0.362 ms|SELECT thread_id, date, _id, sub, sub_cs FROM pdu WHERE ((msg_box=1
// AND seen=0 AND (m_type=130 OR m_type=132))) ORDER BY date desc
Cursor cursor = SqliteWrapper.query(context, resolver, Mms.CONTENT_URI,
MMS_STATUS_PROJECTION, NEW_INCOMING_MM_CONSTRAINT,
null, Mms.DATE + " desc");
if (cursor == null) {
return;
}
try {
while (cursor.moveToNext()) {
long msgId = cursor.getLong(COLUMN_MMS_ID);
Uri msgUri = Mms.CONTENT_URI.buildUpon().appendPath(
Long.toString(msgId)).build();
String address = AddressUtils.getFrom(context, msgUri);
Contact contact = Contact.get(address, false);
if (contact.getSendToVoicemail()) {
// don't notify, skip this one
continue;
}
String subject = getMmsSubject(
cursor.getString(COLUMN_SUBJECT), cursor.getInt(COLUMN_SUBJECT_CS));
subject = MessageUtils.cleanseMmsSubject(context, subject);
long threadId = cursor.getLong(COLUMN_THREAD_ID);
long timeMillis = cursor.getLong(COLUMN_DATE) * 1000;
if (Log.isLoggable(LogTag.APP, Log.VERBOSE)) {
Log.d(TAG, "addMmsNotificationInfos: count=" + cursor.getCount() +
", addr = " + address + ", thread_id=" + threadId);
}
// Extract the message and/or an attached picture from the first slide
Bitmap attachedPicture = null;
String messageBody = null;
int attachmentType = WorkingMessage.TEXT;
try {
GenericPdu pdu = sPduPersister.load(msgUri);
if (pdu != null && pdu instanceof MultimediaMessagePdu) {
SlideshowModel slideshow = SlideshowModel.createFromPduBody(context,
((MultimediaMessagePdu)pdu).getBody());
attachmentType = getAttachmentType(slideshow);
SlideModel firstSlide = slideshow.get(0);
if (firstSlide != null) {
if (firstSlide.hasImage()) {
int maxDim = dp2Pixels(MAX_BITMAP_DIMEN_DP);
attachedPicture = firstSlide.getImage().getBitmap(maxDim, maxDim);
}
if (firstSlide.hasText()) {
messageBody = firstSlide.getText().getText();
}
}
}
} catch (final MmsException e) {
Log.e(TAG, "MmsException loading uri: " + msgUri, e);
continue; // skip this bad boy -- don't generate an empty notification
}
NotificationInfo info = getNewMessageNotificationInfo(context,
false /* isSms */,
address,
messageBody, subject,
threadId,
timeMillis,
attachedPicture,
contact,
attachmentType);
notificationSet.add(info);
threads.add(threadId);
}
} finally {
cursor.close();
}
}
// Look at the passed in slideshow and determine what type of attachment it is.
private static int getAttachmentType(SlideshowModel slideshow) {
int slideCount = slideshow.size();
if (slideCount == 0) {
return WorkingMessage.TEXT;
} else if (slideCount > 1) {
return WorkingMessage.SLIDESHOW;
} else {
SlideModel slide = slideshow.get(0);
if (slide.hasImage()) {
return WorkingMessage.IMAGE;
} else if (slide.hasVideo()) {
return WorkingMessage.VIDEO;
} else if (slide.hasAudio()) {
return WorkingMessage.AUDIO;
}
}
return WorkingMessage.TEXT;
}
private static final int dp2Pixels(int dip) {
return (int) (dip * sScreenDensity + 0.5f);
}
private static final MmsSmsDeliveryInfo getSmsNewDeliveryInfo(Context context) {
ContentResolver resolver = context.getContentResolver();
Cursor cursor = SqliteWrapper.query(context, resolver, Sms.CONTENT_URI,
SMS_STATUS_PROJECTION, NEW_DELIVERY_SM_CONSTRAINT,
null, Sms.DATE);
if (cursor == null) {
return null;
}
try {
if (!cursor.moveToLast()) {
return null;
}
String address = cursor.getString(COLUMN_SMS_ADDRESS);
long timeMillis = 3000;
Contact contact = Contact.get(address, false);
String name = contact.getNameAndNumber();
return new MmsSmsDeliveryInfo(context.getString(R.string.delivery_toast_body, name),
timeMillis);
} finally {
cursor.close();
}
}
private static final void addSmsNotificationInfos(
Context context, Set<Long> threads, SortedSet<NotificationInfo> notificationSet) {
ContentResolver resolver = context.getContentResolver();
Cursor cursor = SqliteWrapper.query(context, resolver, Sms.CONTENT_URI,
SMS_STATUS_PROJECTION, NEW_INCOMING_SM_CONSTRAINT,
null, Sms.DATE + " desc");
if (cursor == null) {
return;
}
try {
while (cursor.moveToNext()) {
String address = cursor.getString(COLUMN_SMS_ADDRESS);
Contact contact = Contact.get(address, false);
if (contact.getSendToVoicemail()) {
// don't notify, skip this one
continue;
}
String message = cursor.getString(COLUMN_SMS_BODY);
long threadId = cursor.getLong(COLUMN_THREAD_ID);
long timeMillis = cursor.getLong(COLUMN_DATE);
if (Log.isLoggable(LogTag.APP, Log.VERBOSE))
{
Log.d(TAG, "addSmsNotificationInfos: count=" + cursor.getCount() +
", addr=" + address + ", thread_id=" + threadId);
}
NotificationInfo info = getNewMessageNotificationInfo(context, true /* isSms */,
address, message, null /* subject */,
threadId, timeMillis, null /* attachmentBitmap */,
contact, WorkingMessage.TEXT);
notificationSet.add(info);
threads.add(threadId);
threads.add(cursor.getLong(COLUMN_THREAD_ID));
}
} finally {
cursor.close();
}
}
private static final NotificationInfo getNewMessageNotificationInfo(
Context context,
boolean isSms,
String address,
String message,
String subject,
long threadId,
long timeMillis,
Bitmap attachmentBitmap,
Contact contact,
int attachmentType) {
Intent clickIntent = ComposeMessageActivity.createIntent(context, threadId);
clickIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
| Intent.FLAG_ACTIVITY_SINGLE_TOP
| Intent.FLAG_ACTIVITY_CLEAR_TOP);
String senderInfo = buildTickerMessage(
context, address, null, null).toString();
String senderInfoName = senderInfo.substring(
0, senderInfo.length() - 2);
CharSequence ticker = buildTickerMessage(
context, address, subject, message);
return new NotificationInfo(isSms,
clickIntent, message, subject, ticker, timeMillis,
senderInfoName, attachmentBitmap, contact, attachmentType, threadId);
}
public static void cancelNotification(Context context, int notificationId) {
NotificationManager nm = (NotificationManager) context.getSystemService(
Context.NOTIFICATION_SERVICE);
Log.d(TAG, "cancelNotification");
nm.cancel(notificationId);
}
private static void updateDeliveryNotification(final Context context,
boolean isStatusMessage,
final CharSequence message,
final long timeMillis) {
if (!isStatusMessage) {
return;
}
if (!MessagingPreferenceActivity.getNotificationEnabled(context)) {
return;
}
sHandler.post(new Runnable() {
@Override
public void run() {
Toast.makeText(context, message, (int)timeMillis).show();
}
});
}
/**
* updateNotification is *the* main function for building the actual notification handed to
* the NotificationManager
* @param context
* @param isNew if we've got a new message, show the ticker
* @param uniqueThreadCount
* @param notificationSet the set of notifications to display
*/
private static void updateNotification(
Context context,
boolean isNew,
int uniqueThreadCount,
SortedSet<NotificationInfo> notificationSet) {
// If the user has turned off notifications in settings, don't do any notifying.
if (!MessagingPreferenceActivity.getNotificationEnabled(context)) {
if (DEBUG) {
Log.d(TAG, "updateNotification: notifications turned off in prefs, bailing");
}
return;
}
// Figure out what we've got -- whether all sms's, mms's, or a mixture of both.
final int messageCount = notificationSet.size();
NotificationInfo mostRecentNotification = notificationSet.first();
final Notification.Builder noti = new Notification.Builder(context)
.setWhen(mostRecentNotification.mTimeMillis);
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);
boolean privacyMode = sp.getBoolean(MessagingPreferenceActivity.PRIVACY_MODE_ENABLED, false);
if (isNew) {
if (!privacyMode) {
noti.setTicker(mostRecentNotification.mTicker);
} else {
noti.setTicker(context.getString(R.string.notification_ticker_privacy_mode));
}
}
TaskStackBuilder taskStackBuilder = TaskStackBuilder.create(context);
// If we have more than one unique thread, change the title (which would
// normally be the contact who sent the message) to a generic one that
// makes sense for multiple senders, and change the Intent to take the
// user to the conversation list instead of the specific thread.
// Cases:
// 1) single message from single thread - intent goes to ComposeMessageActivity
// 2) multiple messages from single thread - intent goes to ComposeMessageActivity
// 3) messages from multiple threads - intent goes to ConversationList
final Resources res = context.getResources();
String title = null;
String privateModeContentText = null;
Bitmap avatar = null;
if (uniqueThreadCount > 1) { // messages from multiple threads
Intent mainActivityIntent = new Intent(Intent.ACTION_MAIN);
mainActivityIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
| Intent.FLAG_ACTIVITY_SINGLE_TOP
| Intent.FLAG_ACTIVITY_CLEAR_TOP);
mainActivityIntent.setType("vnd.android-dir/mms-sms");
taskStackBuilder.addNextIntent(mainActivityIntent);
if (!privacyMode) {
title = context.getString(R.string.message_count_notification, messageCount);
} else {
title = context.getString(R.string.notification_multiple_title_privacy_mode);
privateModeContentText = context.getString(R.string.notification_multiple_text_privacy_mode, messageCount);
}
} else { // same thread, single or multiple messages
if (!privacyMode) {
title = mostRecentNotification.mTitle;
BitmapDrawable contactDrawable = (BitmapDrawable)mostRecentNotification.mSender
.getAvatar(context, null);
if (contactDrawable != null) {
// Show the sender's avatar as the big icon. Contact bitmaps are 96x96 so we
// have to scale 'em up to 128x128 to fill the whole notification large icon.
avatar = contactDrawable.getBitmap();
if (avatar != null) {
final int idealIconHeight =
res.getDimensionPixelSize(android.R.dimen.notification_large_icon_height);
final int idealIconWidth =
res.getDimensionPixelSize(android.R.dimen.notification_large_icon_width);
if (avatar.getHeight() < idealIconHeight) {
// Scale this image to fit the intended size
avatar = Bitmap.createScaledBitmap(
avatar, idealIconWidth, idealIconHeight, true);
}
if (avatar != null) {
noti.setLargeIcon(avatar);
}
}
}
} else {
if (messageCount > 1) {
title = context.getString(R.string.notification_multiple_title_privacy_mode);
privateModeContentText = context.getString(R.string.notification_multiple_text_privacy_mode, messageCount);
} else {
title = context.getString(R.string.notification_single_title_privacy_mode);
privateModeContentText = context.getString(R.string.notification_single_text_privacy_mode);
}
}
taskStackBuilder.addParentStack(ComposeMessageActivity.class);
taskStackBuilder.addNextIntent(mostRecentNotification.mClickIntent);
}
// Always have to set the small icon or the notification is ignored
if (Settings.System.getInt(context.getContentResolver(),
- Settings.System.MMS_BREATH, 0) == 1) {
+ Settings.System.KEY_SMS_BREATH, 0) == 1) {
noti.setSmallIcon(R.drawable.stat_notify_sms_breath);
} else {
noti.setSmallIcon(R.drawable.stat_notify_sms);
}
NotificationManager nm = (NotificationManager)
context.getSystemService(Context.NOTIFICATION_SERVICE);
// Update the notification.
noti.setContentTitle(title)
.setContentIntent(
taskStackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT))
.addKind(Notification.KIND_MESSAGE)
.setPriority(Notification.PRIORITY_DEFAULT); // TODO: set based on contact coming
// from a favorite.
int defaults = 0;
if (isNew) {
boolean vibrate = false;
if (sp.contains(MessagingPreferenceActivity.NOTIFICATION_VIBRATE)) {
// The most recent change to the vibrate preference is to store a boolean
// value in NOTIFICATION_VIBRATE. If prefs contain that preference, use that
// first.
vibrate = sp.getBoolean(MessagingPreferenceActivity.NOTIFICATION_VIBRATE,
false);
} else if (sp.contains(MessagingPreferenceActivity.NOTIFICATION_VIBRATE_WHEN)) {
// This is to support the pre-JellyBean MR1.1 version of vibrate preferences
// when vibrate was a tri-state setting. As soon as the user opens the Messaging
// app's settings, it will migrate this setting from NOTIFICATION_VIBRATE_WHEN
// to the boolean value stored in NOTIFICATION_VIBRATE.
String vibrateWhen =
sp.getString(MessagingPreferenceActivity.NOTIFICATION_VIBRATE_WHEN, null);
vibrate = "always".equals(vibrateWhen);
}
if (vibrate) {
String pattern = sp.getString(
MessagingPreferenceActivity.NOTIFICATION_VIBRATE_PATTERN, "0,1200");
if (!TextUtils.isEmpty(pattern)) {
noti.setVibrate(parseVibratePattern(pattern));
} else {
defaults |= Notification.DEFAULT_VIBRATE;
}
}
String ringtoneStr = sp.getString(MessagingPreferenceActivity.NOTIFICATION_RINGTONE,
null);
noti.setSound(TextUtils.isEmpty(ringtoneStr) ? null : Uri.parse(ringtoneStr));
if (DEBUG) {
Log.d(TAG, "updateNotification: new message, adding sound to the notification");
}
}
// Set light defaults
defaults |= Notification.DEFAULT_LIGHTS;
noti.setDefaults(defaults);
// set up delete intent
noti.setDeleteIntent(PendingIntent.getBroadcast(context, 0,
sNotificationOnDeleteIntent, 0));
// See if QuickMessage pop-up support is enabled in preferences
boolean qmPopupEnabled = MessagingPreferenceActivity.getQuickMessageEnabled(context);
// Set up the QuickMessage intent
Intent qmIntent = null;
if (mostRecentNotification.mIsSms && !privacyMode) {
// QuickMessage support is only for SMS when privacy mode is disabled
qmIntent = new Intent();
qmIntent.setClass(context, QuickMessagePopup.class);
qmIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP |
Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
qmIntent.putExtra(QuickMessagePopup.SMS_FROM_NAME_EXTRA, mostRecentNotification.mSender.getName());
qmIntent.putExtra(QuickMessagePopup.SMS_FROM_NUMBER_EXTRA, mostRecentNotification.mSender.getNumber());
qmIntent.putExtra(QuickMessagePopup.SMS_NOTIFICATION_OBJECT_EXTRA, mostRecentNotification);
}
// Start getting the notification ready
final Notification notification;
if (!privacyMode) {
if (messageCount == 1 || uniqueThreadCount == 1) {
// Add the Quick Reply action only if the pop-up won't be shown already
if (!qmPopupEnabled && qmIntent != null) {
// This is a QR, we should show the keyboard when the user taps to reply
qmIntent.putExtra(QuickMessagePopup.QR_SHOW_KEYBOARD_EXTRA, true);
// Create the Quick reply pending intent and add it to the notification
CharSequence qmText = context.getText(R.string.qm_quick_reply);
PendingIntent qmPendingIntent = PendingIntent.getActivity(context, 0, qmIntent,
PendingIntent.FLAG_UPDATE_CURRENT);
noti.addAction(R.drawable.ic_reply, qmText, qmPendingIntent);
}
// Add the 'Mark as read' action
CharSequence markReadText = context.getText(R.string.qm_mark_read);
Intent mrIntent = new Intent();
mrIntent.setClass(context, QmMarkRead.class);
mrIntent.putExtra(QmMarkRead.SMS_THREAD_ID, mostRecentNotification.mThreadId);
PendingIntent mrPendingIntent = PendingIntent.getBroadcast(context, 0, mrIntent,
PendingIntent.FLAG_UPDATE_CURRENT);
noti.addAction(R.drawable.ic_mark_read_holo_dark, markReadText, mrPendingIntent);
// Add the Call action
CharSequence callText = context.getText(R.string.menu_call);
Intent callIntent = new Intent(Intent.ACTION_CALL);
callIntent.setData(mostRecentNotification.mSender.getPhoneUri(true));
PendingIntent callPendingIntent = PendingIntent.getActivity(context, 0, callIntent,
PendingIntent.FLAG_UPDATE_CURRENT);
noti.addAction(R.drawable.ic_menu_call, callText, callPendingIntent);
}
if (messageCount == 1) {
// We've got a single message
// This sets the text for the collapsed form:
noti.setContentText(mostRecentNotification.formatBigMessage(context));
if (mostRecentNotification.mAttachmentBitmap != null) {
// The message has a picture, show that
notification = new Notification.BigPictureStyle(noti)
.bigPicture(mostRecentNotification.mAttachmentBitmap)
// This sets the text for the expanded picture form:
.setSummaryText(mostRecentNotification.formatPictureMessage(context))
.build();
} else {
// Show a single notification -- big style with the text of the whole message
notification = new Notification.BigTextStyle(noti)
.bigText(mostRecentNotification.formatBigMessage(context))
.build();
}
if (DEBUG) {
Log.d(TAG, "updateNotification: single message notification");
}
} else {
// We've got multiple messages
if (uniqueThreadCount == 1) {
// We've got multiple messages for the same thread.
// Starting with the oldest new message, display the full text of each message.
// Begin a line for each subsequent message.
SpannableStringBuilder buf = new SpannableStringBuilder();
NotificationInfo infos[] =
notificationSet.toArray(new NotificationInfo[messageCount]);
int len = infos.length;
for (int i = len - 1; i >= 0; i--) {
NotificationInfo info = infos[i];
buf.append(info.formatBigMessage(context));
if (i != 0) {
buf.append('\n');
}
}
noti.setContentText(context.getString(R.string.message_count_notification,
messageCount));
// Show a single notification -- big style with the text of all the messages
notification = new Notification.BigTextStyle(noti)
.bigText(buf)
// Forcibly show the last line, with the app's smallIcon in it, if we
// kicked the smallIcon out with an avatar bitmap
.setSummaryText((avatar == null) ? null : " ")
.build();
if (DEBUG) {
Log.d(TAG, "updateNotification: multi messages for single thread");
}
} else {
// Build a set of the most recent notification per threadId.
HashSet<Long> uniqueThreads = new HashSet<Long>(messageCount);
ArrayList<NotificationInfo> mostRecentNotifPerThread =
new ArrayList<NotificationInfo>();
Iterator<NotificationInfo> notifications = notificationSet.iterator();
while (notifications.hasNext()) {
NotificationInfo notificationInfo = notifications.next();
if (!uniqueThreads.contains(notificationInfo.mThreadId)) {
uniqueThreads.add(notificationInfo.mThreadId);
mostRecentNotifPerThread.add(notificationInfo);
}
}
// When collapsed, show all the senders like this:
// Fred Flinstone, Barry Manilow, Pete...
noti.setContentText(formatSenders(context, mostRecentNotifPerThread));
Notification.InboxStyle inboxStyle = new Notification.InboxStyle(noti);
// We have to set the summary text to non-empty so the content text doesn't show
// up when expanded.
inboxStyle.setSummaryText(" ");
// At this point we've got multiple messages in multiple threads. We only
// want to show the most recent message per thread, which are in
// mostRecentNotifPerThread.
int uniqueThreadMessageCount = mostRecentNotifPerThread.size();
int maxMessages = Math.min(MAX_MESSAGES_TO_SHOW, uniqueThreadMessageCount);
for (int i = 0; i < maxMessages; i++) {
NotificationInfo info = mostRecentNotifPerThread.get(i);
inboxStyle.addLine(info.formatInboxMessage(context));
}
notification = inboxStyle.build();
uniqueThreads.clear();
mostRecentNotifPerThread.clear();
if (DEBUG) {
Log.d(TAG, "updateNotification: multi messages," +
" showing inboxStyle notification");
}
}
}
// Trigger the QuickMessage pop-up activity if enabled
// But don't show the QuickMessage if the user is in a call or the phone is ringing
if (qmPopupEnabled && qmIntent != null) {
final TelephonyManager tm =
(TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
boolean callIsActive = tm.getCallState() != TelephonyManager.CALL_STATE_IDLE;
if (!callIsActive && !ConversationList.mIsRunning && !ComposeMessageActivity.mIsRunning) {
// Show the popup
context.startActivity(qmIntent);
}
}
} else {
// Show a standard notification in privacy mode
noti.setContentText(privateModeContentText);
notification = noti.build();
}
// Post the notification
nm.notify(NOTIFICATION_ID, notification);
}
protected static CharSequence buildTickerMessage(
Context context, String address, String subject, String body) {
String displayAddress = Contact.get(address, true).getName();
StringBuilder buf = new StringBuilder(
displayAddress == null
? ""
: displayAddress.replace('\n', ' ').replace('\r', ' '));
buf.append(':').append(' ');
int offset = buf.length();
if (!TextUtils.isEmpty(subject)) {
subject = subject.replace('\n', ' ').replace('\r', ' ');
buf.append(subject);
buf.append(' ');
}
if (!TextUtils.isEmpty(body)) {
body = body.replace('\n', ' ').replace('\r', ' ');
buf.append(body);
}
SpannableString spanText = new SpannableString(buf.toString());
spanText.setSpan(new StyleSpan(Typeface.BOLD), 0, offset,
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
return spanText;
}
private static String getMmsSubject(String sub, int charset) {
return TextUtils.isEmpty(sub) ? ""
: new EncodedStringValue(charset, PduPersister.getBytes(sub)).getString();
}
public static void notifyDownloadFailed(Context context, long threadId) {
notifyFailed(context, true, threadId, false);
}
public static void notifySendFailed(Context context) {
notifyFailed(context, false, 0, false);
}
public static void notifySendFailed(Context context, boolean noisy) {
notifyFailed(context, false, 0, noisy);
}
private static void notifyFailed(Context context, boolean isDownload, long threadId,
boolean noisy) {
// TODO factor out common code for creating notifications
boolean enabled = MessagingPreferenceActivity.getNotificationEnabled(context);
if (!enabled) {
return;
}
// Strategy:
// a. If there is a single failure notification, tapping on the notification goes
// to the compose view.
// b. If there are two failure it stays in the thread view. Selecting one undelivered
// thread will dismiss one undelivered notification but will still display the
// notification.If you select the 2nd undelivered one it will dismiss the notification.
long[] msgThreadId = {0, 1}; // Dummy initial values, just to initialize the memory
int totalFailedCount = getUndeliveredMessageCount(context, msgThreadId);
if (totalFailedCount == 0 && !isDownload) {
return;
}
// The getUndeliveredMessageCount method puts a non-zero value in msgThreadId[1] if all
// failures are from the same thread.
// If isDownload is true, we're dealing with 1 specific failure; therefore "all failed" are
// indeed in the same thread since there's only 1.
boolean allFailedInSameThread = (msgThreadId[1] != 0) || isDownload;
Intent failedIntent;
Notification notification = new Notification();
String title;
String description;
if (totalFailedCount > 1) {
description = context.getString(R.string.notification_failed_multiple,
Integer.toString(totalFailedCount));
title = context.getString(R.string.notification_failed_multiple_title);
} else {
title = isDownload ?
context.getString(R.string.message_download_failed_title) :
context.getString(R.string.message_send_failed_title);
description = context.getString(R.string.message_failed_body);
}
TaskStackBuilder taskStackBuilder = TaskStackBuilder.create(context);
if (allFailedInSameThread) {
failedIntent = new Intent(context, ComposeMessageActivity.class);
if (isDownload) {
// When isDownload is true, the valid threadId is passed into this function.
failedIntent.putExtra("failed_download_flag", true);
} else {
threadId = msgThreadId[0];
failedIntent.putExtra("undelivered_flag", true);
}
failedIntent.putExtra("thread_id", threadId);
taskStackBuilder.addParentStack(ComposeMessageActivity.class);
} else {
failedIntent = new Intent(context, ConversationList.class);
}
taskStackBuilder.addNextIntent(failedIntent);
notification.icon = R.drawable.stat_notify_sms_failed;
notification.tickerText = title;
notification.setLatestEventInfo(context, title, description,
taskStackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT));
if (noisy) {
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);
boolean vibrate = sp.getBoolean(MessagingPreferenceActivity.NOTIFICATION_VIBRATE,
false /* don't vibrate by default */);
if (vibrate) {
notification.defaults |= Notification.DEFAULT_VIBRATE;
}
String ringtoneStr = sp.getString(MessagingPreferenceActivity.NOTIFICATION_RINGTONE,
null);
notification.sound = TextUtils.isEmpty(ringtoneStr) ? null : Uri.parse(ringtoneStr);
}
NotificationManager notificationMgr = (NotificationManager)
context.getSystemService(Context.NOTIFICATION_SERVICE);
if (isDownload) {
notificationMgr.notify(DOWNLOAD_FAILED_NOTIFICATION_ID, notification);
} else {
notificationMgr.notify(MESSAGE_FAILED_NOTIFICATION_ID, notification);
}
}
/**
* Query the DB and return the number of undelivered messages (total for both SMS and MMS)
* @param context The context
* @param threadIdResult A container to put the result in, according to the following rules:
* threadIdResult[0] contains the thread id of the first message.
* threadIdResult[1] is nonzero if the thread ids of all the messages are the same.
* You can pass in null for threadIdResult.
* You can pass in a threadIdResult of size 1 to avoid the comparison of each thread id.
*/
private static int getUndeliveredMessageCount(Context context, long[] threadIdResult) {
Cursor undeliveredCursor = SqliteWrapper.query(context, context.getContentResolver(),
UNDELIVERED_URI, MMS_THREAD_ID_PROJECTION, "read=0", null, null);
if (undeliveredCursor == null) {
return 0;
}
int count = undeliveredCursor.getCount();
try {
if (threadIdResult != null && undeliveredCursor.moveToFirst()) {
threadIdResult[0] = undeliveredCursor.getLong(0);
if (threadIdResult.length >= 2) {
// Test to see if all the undelivered messages belong to the same thread.
long firstId = threadIdResult[0];
while (undeliveredCursor.moveToNext()) {
if (undeliveredCursor.getLong(0) != firstId) {
firstId = 0;
break;
}
}
threadIdResult[1] = firstId; // non-zero if all ids are the same
}
}
} finally {
undeliveredCursor.close();
}
return count;
}
public static void nonBlockingUpdateSendFailedNotification(final Context context) {
new AsyncTask<Void, Void, Integer>() {
protected Integer doInBackground(Void... none) {
return getUndeliveredMessageCount(context, null);
}
protected void onPostExecute(Integer result) {
if (result < 1) {
cancelNotification(context, MESSAGE_FAILED_NOTIFICATION_ID);
} else {
// rebuild and adjust the message count if necessary.
notifySendFailed(context);
}
}
}.execute();
}
/**
* If all the undelivered messages belong to "threadId", cancel the notification.
*/
public static void updateSendFailedNotificationForThread(Context context, long threadId) {
long[] msgThreadId = {0, 0};
if (getUndeliveredMessageCount(context, msgThreadId) > 0
&& msgThreadId[0] == threadId
&& msgThreadId[1] != 0) {
cancelNotification(context, MESSAGE_FAILED_NOTIFICATION_ID);
}
}
private static int getDownloadFailedMessageCount(Context context) {
// Look for any messages in the MMS Inbox that are of the type
// NOTIFICATION_IND (i.e. not already downloaded) and in the
// permanent failure state. If there are none, cancel any
// failed download notification.
Cursor c = SqliteWrapper.query(context, context.getContentResolver(),
Mms.Inbox.CONTENT_URI, null,
Mms.MESSAGE_TYPE + "=" +
String.valueOf(PduHeaders.MESSAGE_TYPE_NOTIFICATION_IND) +
" AND " + Mms.STATUS + "=" +
String.valueOf(DownloadManager.STATE_PERMANENT_FAILURE),
null, null);
if (c == null) {
return 0;
}
int count = c.getCount();
c.close();
return count;
}
public static void updateDownloadFailedNotification(Context context) {
if (getDownloadFailedMessageCount(context) < 1) {
cancelNotification(context, DOWNLOAD_FAILED_NOTIFICATION_ID);
}
}
public static boolean isFailedToDeliver(Intent intent) {
return (intent != null) && intent.getBooleanExtra("undelivered_flag", false);
}
public static boolean isFailedToDownload(Intent intent) {
return (intent != null) && intent.getBooleanExtra("failed_download_flag", false);
}
/**
* Get the thread ID of the SMS message with the given URI
* @param context The context
* @param uri The URI of the SMS message
* @return The thread ID, or THREAD_NONE if the URI contains no entries
*/
public static long getSmsThreadId(Context context, Uri uri) {
Cursor cursor = SqliteWrapper.query(
context,
context.getContentResolver(),
uri,
SMS_THREAD_ID_PROJECTION,
null,
null,
null);
if (cursor == null) {
if (DEBUG) {
Log.d(TAG, "getSmsThreadId uri: " + uri + " NULL cursor! returning THREAD_NONE");
}
return THREAD_NONE;
}
try {
if (cursor.moveToFirst()) {
int columnIndex = cursor.getColumnIndex(Sms.THREAD_ID);
if (columnIndex < 0) {
if (DEBUG) {
Log.d(TAG, "getSmsThreadId uri: " + uri +
" Couldn't read row 0, col -1! returning THREAD_NONE");
}
return THREAD_NONE;
}
long threadId = cursor.getLong(columnIndex);
if (DEBUG) {
Log.d(TAG, "getSmsThreadId uri: " + uri +
" returning threadId: " + threadId);
}
return threadId;
} else {
if (DEBUG) {
Log.d(TAG, "getSmsThreadId uri: " + uri +
" NULL cursor! returning THREAD_NONE");
}
return THREAD_NONE;
}
} finally {
cursor.close();
}
}
/**
* Get the thread ID of the MMS message with the given URI
* @param context The context
* @param uri The URI of the SMS message
* @return The thread ID, or THREAD_NONE if the URI contains no entries
*/
public static long getThreadId(Context context, Uri uri) {
Cursor cursor = SqliteWrapper.query(
context,
context.getContentResolver(),
uri,
MMS_THREAD_ID_PROJECTION,
null,
null,
null);
if (cursor == null) {
if (DEBUG) {
Log.d(TAG, "getThreadId uri: " + uri + " NULL cursor! returning THREAD_NONE");
}
return THREAD_NONE;
}
try {
if (cursor.moveToFirst()) {
int columnIndex = cursor.getColumnIndex(Mms.THREAD_ID);
if (columnIndex < 0) {
if (DEBUG) {
Log.d(TAG, "getThreadId uri: " + uri +
" Couldn't read row 0, col -1! returning THREAD_NONE");
}
return THREAD_NONE;
}
long threadId = cursor.getLong(columnIndex);
if (DEBUG) {
Log.d(TAG, "getThreadId uri: " + uri +
" returning threadId: " + threadId);
}
return threadId;
} else {
if (DEBUG) {
Log.d(TAG, "getThreadId uri: " + uri +
" NULL cursor! returning THREAD_NONE");
}
return THREAD_NONE;
}
} finally {
cursor.close();
}
}
// Parse the user provided custom vibrate pattern into a long[]
private static long[] parseVibratePattern(String pattern) {
String[] splitPattern = pattern.split(",");
long[] result = new long[splitPattern.length];
for (int i = 0; i < splitPattern.length; i++) {
try {
result[i] = Long.parseLong(splitPattern[i]);
} catch (NumberFormatException e) {
return null;
}
}
return result;
}
}
| true | true | private static void updateNotification(
Context context,
boolean isNew,
int uniqueThreadCount,
SortedSet<NotificationInfo> notificationSet) {
// If the user has turned off notifications in settings, don't do any notifying.
if (!MessagingPreferenceActivity.getNotificationEnabled(context)) {
if (DEBUG) {
Log.d(TAG, "updateNotification: notifications turned off in prefs, bailing");
}
return;
}
// Figure out what we've got -- whether all sms's, mms's, or a mixture of both.
final int messageCount = notificationSet.size();
NotificationInfo mostRecentNotification = notificationSet.first();
final Notification.Builder noti = new Notification.Builder(context)
.setWhen(mostRecentNotification.mTimeMillis);
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);
boolean privacyMode = sp.getBoolean(MessagingPreferenceActivity.PRIVACY_MODE_ENABLED, false);
if (isNew) {
if (!privacyMode) {
noti.setTicker(mostRecentNotification.mTicker);
} else {
noti.setTicker(context.getString(R.string.notification_ticker_privacy_mode));
}
}
TaskStackBuilder taskStackBuilder = TaskStackBuilder.create(context);
// If we have more than one unique thread, change the title (which would
// normally be the contact who sent the message) to a generic one that
// makes sense for multiple senders, and change the Intent to take the
// user to the conversation list instead of the specific thread.
// Cases:
// 1) single message from single thread - intent goes to ComposeMessageActivity
// 2) multiple messages from single thread - intent goes to ComposeMessageActivity
// 3) messages from multiple threads - intent goes to ConversationList
final Resources res = context.getResources();
String title = null;
String privateModeContentText = null;
Bitmap avatar = null;
if (uniqueThreadCount > 1) { // messages from multiple threads
Intent mainActivityIntent = new Intent(Intent.ACTION_MAIN);
mainActivityIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
| Intent.FLAG_ACTIVITY_SINGLE_TOP
| Intent.FLAG_ACTIVITY_CLEAR_TOP);
mainActivityIntent.setType("vnd.android-dir/mms-sms");
taskStackBuilder.addNextIntent(mainActivityIntent);
if (!privacyMode) {
title = context.getString(R.string.message_count_notification, messageCount);
} else {
title = context.getString(R.string.notification_multiple_title_privacy_mode);
privateModeContentText = context.getString(R.string.notification_multiple_text_privacy_mode, messageCount);
}
} else { // same thread, single or multiple messages
if (!privacyMode) {
title = mostRecentNotification.mTitle;
BitmapDrawable contactDrawable = (BitmapDrawable)mostRecentNotification.mSender
.getAvatar(context, null);
if (contactDrawable != null) {
// Show the sender's avatar as the big icon. Contact bitmaps are 96x96 so we
// have to scale 'em up to 128x128 to fill the whole notification large icon.
avatar = contactDrawable.getBitmap();
if (avatar != null) {
final int idealIconHeight =
res.getDimensionPixelSize(android.R.dimen.notification_large_icon_height);
final int idealIconWidth =
res.getDimensionPixelSize(android.R.dimen.notification_large_icon_width);
if (avatar.getHeight() < idealIconHeight) {
// Scale this image to fit the intended size
avatar = Bitmap.createScaledBitmap(
avatar, idealIconWidth, idealIconHeight, true);
}
if (avatar != null) {
noti.setLargeIcon(avatar);
}
}
}
} else {
if (messageCount > 1) {
title = context.getString(R.string.notification_multiple_title_privacy_mode);
privateModeContentText = context.getString(R.string.notification_multiple_text_privacy_mode, messageCount);
} else {
title = context.getString(R.string.notification_single_title_privacy_mode);
privateModeContentText = context.getString(R.string.notification_single_text_privacy_mode);
}
}
taskStackBuilder.addParentStack(ComposeMessageActivity.class);
taskStackBuilder.addNextIntent(mostRecentNotification.mClickIntent);
}
// Always have to set the small icon or the notification is ignored
if (Settings.System.getInt(context.getContentResolver(),
Settings.System.MMS_BREATH, 0) == 1) {
noti.setSmallIcon(R.drawable.stat_notify_sms_breath);
} else {
noti.setSmallIcon(R.drawable.stat_notify_sms);
}
NotificationManager nm = (NotificationManager)
context.getSystemService(Context.NOTIFICATION_SERVICE);
// Update the notification.
noti.setContentTitle(title)
.setContentIntent(
taskStackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT))
.addKind(Notification.KIND_MESSAGE)
.setPriority(Notification.PRIORITY_DEFAULT); // TODO: set based on contact coming
// from a favorite.
int defaults = 0;
if (isNew) {
boolean vibrate = false;
if (sp.contains(MessagingPreferenceActivity.NOTIFICATION_VIBRATE)) {
// The most recent change to the vibrate preference is to store a boolean
// value in NOTIFICATION_VIBRATE. If prefs contain that preference, use that
// first.
vibrate = sp.getBoolean(MessagingPreferenceActivity.NOTIFICATION_VIBRATE,
false);
} else if (sp.contains(MessagingPreferenceActivity.NOTIFICATION_VIBRATE_WHEN)) {
// This is to support the pre-JellyBean MR1.1 version of vibrate preferences
// when vibrate was a tri-state setting. As soon as the user opens the Messaging
// app's settings, it will migrate this setting from NOTIFICATION_VIBRATE_WHEN
// to the boolean value stored in NOTIFICATION_VIBRATE.
String vibrateWhen =
sp.getString(MessagingPreferenceActivity.NOTIFICATION_VIBRATE_WHEN, null);
vibrate = "always".equals(vibrateWhen);
}
if (vibrate) {
String pattern = sp.getString(
MessagingPreferenceActivity.NOTIFICATION_VIBRATE_PATTERN, "0,1200");
if (!TextUtils.isEmpty(pattern)) {
noti.setVibrate(parseVibratePattern(pattern));
} else {
defaults |= Notification.DEFAULT_VIBRATE;
}
}
String ringtoneStr = sp.getString(MessagingPreferenceActivity.NOTIFICATION_RINGTONE,
null);
noti.setSound(TextUtils.isEmpty(ringtoneStr) ? null : Uri.parse(ringtoneStr));
if (DEBUG) {
Log.d(TAG, "updateNotification: new message, adding sound to the notification");
}
}
// Set light defaults
defaults |= Notification.DEFAULT_LIGHTS;
noti.setDefaults(defaults);
// set up delete intent
noti.setDeleteIntent(PendingIntent.getBroadcast(context, 0,
sNotificationOnDeleteIntent, 0));
// See if QuickMessage pop-up support is enabled in preferences
boolean qmPopupEnabled = MessagingPreferenceActivity.getQuickMessageEnabled(context);
// Set up the QuickMessage intent
Intent qmIntent = null;
if (mostRecentNotification.mIsSms && !privacyMode) {
// QuickMessage support is only for SMS when privacy mode is disabled
qmIntent = new Intent();
qmIntent.setClass(context, QuickMessagePopup.class);
qmIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP |
Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
qmIntent.putExtra(QuickMessagePopup.SMS_FROM_NAME_EXTRA, mostRecentNotification.mSender.getName());
qmIntent.putExtra(QuickMessagePopup.SMS_FROM_NUMBER_EXTRA, mostRecentNotification.mSender.getNumber());
qmIntent.putExtra(QuickMessagePopup.SMS_NOTIFICATION_OBJECT_EXTRA, mostRecentNotification);
}
// Start getting the notification ready
final Notification notification;
if (!privacyMode) {
if (messageCount == 1 || uniqueThreadCount == 1) {
// Add the Quick Reply action only if the pop-up won't be shown already
if (!qmPopupEnabled && qmIntent != null) {
// This is a QR, we should show the keyboard when the user taps to reply
qmIntent.putExtra(QuickMessagePopup.QR_SHOW_KEYBOARD_EXTRA, true);
// Create the Quick reply pending intent and add it to the notification
CharSequence qmText = context.getText(R.string.qm_quick_reply);
PendingIntent qmPendingIntent = PendingIntent.getActivity(context, 0, qmIntent,
PendingIntent.FLAG_UPDATE_CURRENT);
noti.addAction(R.drawable.ic_reply, qmText, qmPendingIntent);
}
// Add the 'Mark as read' action
CharSequence markReadText = context.getText(R.string.qm_mark_read);
Intent mrIntent = new Intent();
mrIntent.setClass(context, QmMarkRead.class);
mrIntent.putExtra(QmMarkRead.SMS_THREAD_ID, mostRecentNotification.mThreadId);
PendingIntent mrPendingIntent = PendingIntent.getBroadcast(context, 0, mrIntent,
PendingIntent.FLAG_UPDATE_CURRENT);
noti.addAction(R.drawable.ic_mark_read_holo_dark, markReadText, mrPendingIntent);
// Add the Call action
CharSequence callText = context.getText(R.string.menu_call);
Intent callIntent = new Intent(Intent.ACTION_CALL);
callIntent.setData(mostRecentNotification.mSender.getPhoneUri(true));
PendingIntent callPendingIntent = PendingIntent.getActivity(context, 0, callIntent,
PendingIntent.FLAG_UPDATE_CURRENT);
noti.addAction(R.drawable.ic_menu_call, callText, callPendingIntent);
}
if (messageCount == 1) {
// We've got a single message
// This sets the text for the collapsed form:
noti.setContentText(mostRecentNotification.formatBigMessage(context));
if (mostRecentNotification.mAttachmentBitmap != null) {
// The message has a picture, show that
notification = new Notification.BigPictureStyle(noti)
.bigPicture(mostRecentNotification.mAttachmentBitmap)
// This sets the text for the expanded picture form:
.setSummaryText(mostRecentNotification.formatPictureMessage(context))
.build();
} else {
// Show a single notification -- big style with the text of the whole message
notification = new Notification.BigTextStyle(noti)
.bigText(mostRecentNotification.formatBigMessage(context))
.build();
}
if (DEBUG) {
Log.d(TAG, "updateNotification: single message notification");
}
} else {
// We've got multiple messages
if (uniqueThreadCount == 1) {
// We've got multiple messages for the same thread.
// Starting with the oldest new message, display the full text of each message.
// Begin a line for each subsequent message.
SpannableStringBuilder buf = new SpannableStringBuilder();
NotificationInfo infos[] =
notificationSet.toArray(new NotificationInfo[messageCount]);
int len = infos.length;
for (int i = len - 1; i >= 0; i--) {
NotificationInfo info = infos[i];
buf.append(info.formatBigMessage(context));
if (i != 0) {
buf.append('\n');
}
}
noti.setContentText(context.getString(R.string.message_count_notification,
messageCount));
// Show a single notification -- big style with the text of all the messages
notification = new Notification.BigTextStyle(noti)
.bigText(buf)
// Forcibly show the last line, with the app's smallIcon in it, if we
// kicked the smallIcon out with an avatar bitmap
.setSummaryText((avatar == null) ? null : " ")
.build();
if (DEBUG) {
Log.d(TAG, "updateNotification: multi messages for single thread");
}
} else {
// Build a set of the most recent notification per threadId.
HashSet<Long> uniqueThreads = new HashSet<Long>(messageCount);
ArrayList<NotificationInfo> mostRecentNotifPerThread =
new ArrayList<NotificationInfo>();
Iterator<NotificationInfo> notifications = notificationSet.iterator();
while (notifications.hasNext()) {
NotificationInfo notificationInfo = notifications.next();
if (!uniqueThreads.contains(notificationInfo.mThreadId)) {
uniqueThreads.add(notificationInfo.mThreadId);
mostRecentNotifPerThread.add(notificationInfo);
}
}
// When collapsed, show all the senders like this:
// Fred Flinstone, Barry Manilow, Pete...
noti.setContentText(formatSenders(context, mostRecentNotifPerThread));
Notification.InboxStyle inboxStyle = new Notification.InboxStyle(noti);
// We have to set the summary text to non-empty so the content text doesn't show
// up when expanded.
inboxStyle.setSummaryText(" ");
// At this point we've got multiple messages in multiple threads. We only
// want to show the most recent message per thread, which are in
// mostRecentNotifPerThread.
int uniqueThreadMessageCount = mostRecentNotifPerThread.size();
int maxMessages = Math.min(MAX_MESSAGES_TO_SHOW, uniqueThreadMessageCount);
for (int i = 0; i < maxMessages; i++) {
NotificationInfo info = mostRecentNotifPerThread.get(i);
inboxStyle.addLine(info.formatInboxMessage(context));
}
notification = inboxStyle.build();
uniqueThreads.clear();
mostRecentNotifPerThread.clear();
if (DEBUG) {
Log.d(TAG, "updateNotification: multi messages," +
" showing inboxStyle notification");
}
}
}
// Trigger the QuickMessage pop-up activity if enabled
// But don't show the QuickMessage if the user is in a call or the phone is ringing
if (qmPopupEnabled && qmIntent != null) {
final TelephonyManager tm =
(TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
boolean callIsActive = tm.getCallState() != TelephonyManager.CALL_STATE_IDLE;
if (!callIsActive && !ConversationList.mIsRunning && !ComposeMessageActivity.mIsRunning) {
// Show the popup
context.startActivity(qmIntent);
}
}
} else {
// Show a standard notification in privacy mode
noti.setContentText(privateModeContentText);
notification = noti.build();
}
// Post the notification
nm.notify(NOTIFICATION_ID, notification);
}
| private static void updateNotification(
Context context,
boolean isNew,
int uniqueThreadCount,
SortedSet<NotificationInfo> notificationSet) {
// If the user has turned off notifications in settings, don't do any notifying.
if (!MessagingPreferenceActivity.getNotificationEnabled(context)) {
if (DEBUG) {
Log.d(TAG, "updateNotification: notifications turned off in prefs, bailing");
}
return;
}
// Figure out what we've got -- whether all sms's, mms's, or a mixture of both.
final int messageCount = notificationSet.size();
NotificationInfo mostRecentNotification = notificationSet.first();
final Notification.Builder noti = new Notification.Builder(context)
.setWhen(mostRecentNotification.mTimeMillis);
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);
boolean privacyMode = sp.getBoolean(MessagingPreferenceActivity.PRIVACY_MODE_ENABLED, false);
if (isNew) {
if (!privacyMode) {
noti.setTicker(mostRecentNotification.mTicker);
} else {
noti.setTicker(context.getString(R.string.notification_ticker_privacy_mode));
}
}
TaskStackBuilder taskStackBuilder = TaskStackBuilder.create(context);
// If we have more than one unique thread, change the title (which would
// normally be the contact who sent the message) to a generic one that
// makes sense for multiple senders, and change the Intent to take the
// user to the conversation list instead of the specific thread.
// Cases:
// 1) single message from single thread - intent goes to ComposeMessageActivity
// 2) multiple messages from single thread - intent goes to ComposeMessageActivity
// 3) messages from multiple threads - intent goes to ConversationList
final Resources res = context.getResources();
String title = null;
String privateModeContentText = null;
Bitmap avatar = null;
if (uniqueThreadCount > 1) { // messages from multiple threads
Intent mainActivityIntent = new Intent(Intent.ACTION_MAIN);
mainActivityIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
| Intent.FLAG_ACTIVITY_SINGLE_TOP
| Intent.FLAG_ACTIVITY_CLEAR_TOP);
mainActivityIntent.setType("vnd.android-dir/mms-sms");
taskStackBuilder.addNextIntent(mainActivityIntent);
if (!privacyMode) {
title = context.getString(R.string.message_count_notification, messageCount);
} else {
title = context.getString(R.string.notification_multiple_title_privacy_mode);
privateModeContentText = context.getString(R.string.notification_multiple_text_privacy_mode, messageCount);
}
} else { // same thread, single or multiple messages
if (!privacyMode) {
title = mostRecentNotification.mTitle;
BitmapDrawable contactDrawable = (BitmapDrawable)mostRecentNotification.mSender
.getAvatar(context, null);
if (contactDrawable != null) {
// Show the sender's avatar as the big icon. Contact bitmaps are 96x96 so we
// have to scale 'em up to 128x128 to fill the whole notification large icon.
avatar = contactDrawable.getBitmap();
if (avatar != null) {
final int idealIconHeight =
res.getDimensionPixelSize(android.R.dimen.notification_large_icon_height);
final int idealIconWidth =
res.getDimensionPixelSize(android.R.dimen.notification_large_icon_width);
if (avatar.getHeight() < idealIconHeight) {
// Scale this image to fit the intended size
avatar = Bitmap.createScaledBitmap(
avatar, idealIconWidth, idealIconHeight, true);
}
if (avatar != null) {
noti.setLargeIcon(avatar);
}
}
}
} else {
if (messageCount > 1) {
title = context.getString(R.string.notification_multiple_title_privacy_mode);
privateModeContentText = context.getString(R.string.notification_multiple_text_privacy_mode, messageCount);
} else {
title = context.getString(R.string.notification_single_title_privacy_mode);
privateModeContentText = context.getString(R.string.notification_single_text_privacy_mode);
}
}
taskStackBuilder.addParentStack(ComposeMessageActivity.class);
taskStackBuilder.addNextIntent(mostRecentNotification.mClickIntent);
}
// Always have to set the small icon or the notification is ignored
if (Settings.System.getInt(context.getContentResolver(),
Settings.System.KEY_SMS_BREATH, 0) == 1) {
noti.setSmallIcon(R.drawable.stat_notify_sms_breath);
} else {
noti.setSmallIcon(R.drawable.stat_notify_sms);
}
NotificationManager nm = (NotificationManager)
context.getSystemService(Context.NOTIFICATION_SERVICE);
// Update the notification.
noti.setContentTitle(title)
.setContentIntent(
taskStackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT))
.addKind(Notification.KIND_MESSAGE)
.setPriority(Notification.PRIORITY_DEFAULT); // TODO: set based on contact coming
// from a favorite.
int defaults = 0;
if (isNew) {
boolean vibrate = false;
if (sp.contains(MessagingPreferenceActivity.NOTIFICATION_VIBRATE)) {
// The most recent change to the vibrate preference is to store a boolean
// value in NOTIFICATION_VIBRATE. If prefs contain that preference, use that
// first.
vibrate = sp.getBoolean(MessagingPreferenceActivity.NOTIFICATION_VIBRATE,
false);
} else if (sp.contains(MessagingPreferenceActivity.NOTIFICATION_VIBRATE_WHEN)) {
// This is to support the pre-JellyBean MR1.1 version of vibrate preferences
// when vibrate was a tri-state setting. As soon as the user opens the Messaging
// app's settings, it will migrate this setting from NOTIFICATION_VIBRATE_WHEN
// to the boolean value stored in NOTIFICATION_VIBRATE.
String vibrateWhen =
sp.getString(MessagingPreferenceActivity.NOTIFICATION_VIBRATE_WHEN, null);
vibrate = "always".equals(vibrateWhen);
}
if (vibrate) {
String pattern = sp.getString(
MessagingPreferenceActivity.NOTIFICATION_VIBRATE_PATTERN, "0,1200");
if (!TextUtils.isEmpty(pattern)) {
noti.setVibrate(parseVibratePattern(pattern));
} else {
defaults |= Notification.DEFAULT_VIBRATE;
}
}
String ringtoneStr = sp.getString(MessagingPreferenceActivity.NOTIFICATION_RINGTONE,
null);
noti.setSound(TextUtils.isEmpty(ringtoneStr) ? null : Uri.parse(ringtoneStr));
if (DEBUG) {
Log.d(TAG, "updateNotification: new message, adding sound to the notification");
}
}
// Set light defaults
defaults |= Notification.DEFAULT_LIGHTS;
noti.setDefaults(defaults);
// set up delete intent
noti.setDeleteIntent(PendingIntent.getBroadcast(context, 0,
sNotificationOnDeleteIntent, 0));
// See if QuickMessage pop-up support is enabled in preferences
boolean qmPopupEnabled = MessagingPreferenceActivity.getQuickMessageEnabled(context);
// Set up the QuickMessage intent
Intent qmIntent = null;
if (mostRecentNotification.mIsSms && !privacyMode) {
// QuickMessage support is only for SMS when privacy mode is disabled
qmIntent = new Intent();
qmIntent.setClass(context, QuickMessagePopup.class);
qmIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP |
Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
qmIntent.putExtra(QuickMessagePopup.SMS_FROM_NAME_EXTRA, mostRecentNotification.mSender.getName());
qmIntent.putExtra(QuickMessagePopup.SMS_FROM_NUMBER_EXTRA, mostRecentNotification.mSender.getNumber());
qmIntent.putExtra(QuickMessagePopup.SMS_NOTIFICATION_OBJECT_EXTRA, mostRecentNotification);
}
// Start getting the notification ready
final Notification notification;
if (!privacyMode) {
if (messageCount == 1 || uniqueThreadCount == 1) {
// Add the Quick Reply action only if the pop-up won't be shown already
if (!qmPopupEnabled && qmIntent != null) {
// This is a QR, we should show the keyboard when the user taps to reply
qmIntent.putExtra(QuickMessagePopup.QR_SHOW_KEYBOARD_EXTRA, true);
// Create the Quick reply pending intent and add it to the notification
CharSequence qmText = context.getText(R.string.qm_quick_reply);
PendingIntent qmPendingIntent = PendingIntent.getActivity(context, 0, qmIntent,
PendingIntent.FLAG_UPDATE_CURRENT);
noti.addAction(R.drawable.ic_reply, qmText, qmPendingIntent);
}
// Add the 'Mark as read' action
CharSequence markReadText = context.getText(R.string.qm_mark_read);
Intent mrIntent = new Intent();
mrIntent.setClass(context, QmMarkRead.class);
mrIntent.putExtra(QmMarkRead.SMS_THREAD_ID, mostRecentNotification.mThreadId);
PendingIntent mrPendingIntent = PendingIntent.getBroadcast(context, 0, mrIntent,
PendingIntent.FLAG_UPDATE_CURRENT);
noti.addAction(R.drawable.ic_mark_read_holo_dark, markReadText, mrPendingIntent);
// Add the Call action
CharSequence callText = context.getText(R.string.menu_call);
Intent callIntent = new Intent(Intent.ACTION_CALL);
callIntent.setData(mostRecentNotification.mSender.getPhoneUri(true));
PendingIntent callPendingIntent = PendingIntent.getActivity(context, 0, callIntent,
PendingIntent.FLAG_UPDATE_CURRENT);
noti.addAction(R.drawable.ic_menu_call, callText, callPendingIntent);
}
if (messageCount == 1) {
// We've got a single message
// This sets the text for the collapsed form:
noti.setContentText(mostRecentNotification.formatBigMessage(context));
if (mostRecentNotification.mAttachmentBitmap != null) {
// The message has a picture, show that
notification = new Notification.BigPictureStyle(noti)
.bigPicture(mostRecentNotification.mAttachmentBitmap)
// This sets the text for the expanded picture form:
.setSummaryText(mostRecentNotification.formatPictureMessage(context))
.build();
} else {
// Show a single notification -- big style with the text of the whole message
notification = new Notification.BigTextStyle(noti)
.bigText(mostRecentNotification.formatBigMessage(context))
.build();
}
if (DEBUG) {
Log.d(TAG, "updateNotification: single message notification");
}
} else {
// We've got multiple messages
if (uniqueThreadCount == 1) {
// We've got multiple messages for the same thread.
// Starting with the oldest new message, display the full text of each message.
// Begin a line for each subsequent message.
SpannableStringBuilder buf = new SpannableStringBuilder();
NotificationInfo infos[] =
notificationSet.toArray(new NotificationInfo[messageCount]);
int len = infos.length;
for (int i = len - 1; i >= 0; i--) {
NotificationInfo info = infos[i];
buf.append(info.formatBigMessage(context));
if (i != 0) {
buf.append('\n');
}
}
noti.setContentText(context.getString(R.string.message_count_notification,
messageCount));
// Show a single notification -- big style with the text of all the messages
notification = new Notification.BigTextStyle(noti)
.bigText(buf)
// Forcibly show the last line, with the app's smallIcon in it, if we
// kicked the smallIcon out with an avatar bitmap
.setSummaryText((avatar == null) ? null : " ")
.build();
if (DEBUG) {
Log.d(TAG, "updateNotification: multi messages for single thread");
}
} else {
// Build a set of the most recent notification per threadId.
HashSet<Long> uniqueThreads = new HashSet<Long>(messageCount);
ArrayList<NotificationInfo> mostRecentNotifPerThread =
new ArrayList<NotificationInfo>();
Iterator<NotificationInfo> notifications = notificationSet.iterator();
while (notifications.hasNext()) {
NotificationInfo notificationInfo = notifications.next();
if (!uniqueThreads.contains(notificationInfo.mThreadId)) {
uniqueThreads.add(notificationInfo.mThreadId);
mostRecentNotifPerThread.add(notificationInfo);
}
}
// When collapsed, show all the senders like this:
// Fred Flinstone, Barry Manilow, Pete...
noti.setContentText(formatSenders(context, mostRecentNotifPerThread));
Notification.InboxStyle inboxStyle = new Notification.InboxStyle(noti);
// We have to set the summary text to non-empty so the content text doesn't show
// up when expanded.
inboxStyle.setSummaryText(" ");
// At this point we've got multiple messages in multiple threads. We only
// want to show the most recent message per thread, which are in
// mostRecentNotifPerThread.
int uniqueThreadMessageCount = mostRecentNotifPerThread.size();
int maxMessages = Math.min(MAX_MESSAGES_TO_SHOW, uniqueThreadMessageCount);
for (int i = 0; i < maxMessages; i++) {
NotificationInfo info = mostRecentNotifPerThread.get(i);
inboxStyle.addLine(info.formatInboxMessage(context));
}
notification = inboxStyle.build();
uniqueThreads.clear();
mostRecentNotifPerThread.clear();
if (DEBUG) {
Log.d(TAG, "updateNotification: multi messages," +
" showing inboxStyle notification");
}
}
}
// Trigger the QuickMessage pop-up activity if enabled
// But don't show the QuickMessage if the user is in a call or the phone is ringing
if (qmPopupEnabled && qmIntent != null) {
final TelephonyManager tm =
(TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
boolean callIsActive = tm.getCallState() != TelephonyManager.CALL_STATE_IDLE;
if (!callIsActive && !ConversationList.mIsRunning && !ComposeMessageActivity.mIsRunning) {
// Show the popup
context.startActivity(qmIntent);
}
}
} else {
// Show a standard notification in privacy mode
noti.setContentText(privateModeContentText);
notification = noti.build();
}
// Post the notification
nm.notify(NOTIFICATION_ID, notification);
}
|
diff --git a/src/Board.java b/src/Board.java
index dbd4187..4348ed3 100644
--- a/src/Board.java
+++ b/src/Board.java
@@ -1,284 +1,282 @@
import javax.imageio.ImageIO;
import javax.swing.JPanel;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.event.ActionEvent;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import javax.swing.Timer;
public class Board extends JPanel implements ActionListener, FileLink{
//instantiates classes
final static MenuIngame ingameMenu = new MenuIngame();
final static MenuMain mainMenu = new MenuMain();
final static OverWorldMap overWorldMap = new OverWorldMap();
final static Player player = new Player();
final static Enemy enemy = new Enemy(0,0);
final static Camera camera = new Camera();
final static DungeonNavigator dungeonNavigator = new DungeonNavigator();
final static CollisionDetection collisionDetection = new CollisionDetection();
final static DungeonBuilder dungeonBuilder = new DungeonBuilder();
final static PlayerInterface playerInterface = new PlayerInterface();
//threads
static int ingameThreadCounter = 5;
static int menuThreadCounter = 5;
final static ScheduledThreadPoolExecutor ingameScheduler = new ScheduledThreadPoolExecutor(ingameThreadCounter);
final static ScheduledThreadPoolExecutor menuScheduler = new ScheduledThreadPoolExecutor(menuThreadCounter);
final static Thread ingameMenuThread = new Thread(ingameMenu);
final static Thread mainMenuThread = new Thread(mainMenu);
final static Thread mapThread = new Thread(overWorldMap);
final static Thread dungeonBuilderThread = new Thread(dungeonBuilder);
final static Thread dungeonNavigatorThread = new Thread(dungeonNavigator);
final static Thread playerThread = new Thread(player);
final static Thread enemyThread = new Thread(enemy);
final static Thread playerInterfaceThread = new Thread(playerInterface);
final static Thread cameraThread = new Thread(camera);
final static Thread collisionDetectionThread = new Thread(collisionDetection);
//instance variables
static boolean repaintNow = false;
static boolean menuThread = false, ingameThread = false;
static int clickCount = 0;
/*switch menu/ingame with M*/ static boolean ingame = true;
static boolean menu = false;
static boolean gameOver = false;
static boolean win = false;
/*sound/music volume*/ static int musicVolume = 50;
static int soundVolume = 50;
/*Debug tmpVaribles*/ static boolean paintBounds = false;
static boolean printMsg = false;
private Timer repaintTimer;
private Graphics2D g2d;
public Board(){
setDoubleBuffered(true);
setFocusable(true);
setBackground(Color.DARK_GRAY);
//Listeners
this.addMouseListener(new MAdapter());
this.addKeyListener(new KAdapter());
//Timer
repaintTimer = new Timer(5, this);
repaintTimer.start();
//initiate Threads
if (ingame){
ingameThread = true;
menuThread = false;
} else {
ingameThread = false;
menuThread = true;
}
//initiate overWorld/dungeon
OverWorldMap.overWorld = false;
DungeonNavigator.dungeon = true;
//start point
Player.x = 230; Player.y = 500;
Player.lastDirection = 1;
//Player.absoluteX = Player.x = 405-20*3;
//Player.absoluteY = Player.y = 315-15*3;
//Camera.cameraX = Player.absoluteX;
//Camera.cameraY = Player.absoluteY;
System.out.println("->Board");
start();
}
public void paint(Graphics g) {
super.paint(g);
g2d = (Graphics2D) g;
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
if (!ingame){
//paint MenuMain
mainMenu.paintComponents(g2d);
}
if(ingame && menu){
ingameMenu.paintComponents(g2d);
}
if(gameOver){
ingame = false; menu = true;
- System.err.println("Game Over");
g2d.setColor(Color.red);
Font textFont = new Font("Arial", Font.BOLD, 75);
g.setFont(textFont);
g2d.drawString("Game Over",220,300);
}
if(win){
ingame = false; menu = true;
- System.err.println("Win");
g2d.setColor(Color.yellow);
Font textFont = new Font("Arial", Font.BOLD, 75);
g.setFont(textFont);
g2d.drawString("Win",330,330);
}
if (ingame && !menu && !gameOver && !win){
if(OverWorldMap.overWorld)
overWorldMap.paintComponents(g2d);
if(DungeonNavigator.dungeon)
dungeonBuilder.paintComponents(g2d);
player.paintComponents(g2d);
playerInterface.paintComponents(g2d);
//paint player interface
if(paintBounds){
g2d.setColor(Color.red); //PlayerBounds
g2d.drawRect(Player.x+10,Player.y+10,60,10);g2d.drawRect(Player.x+10,Player.y+90,60,10);g2d.drawRect(Player.x+10,Player.y+10,10,90);g2d.drawRect(Player.x+60,Player.y+10,10,90);
g2d.setColor(Color.blue); //Map Bounds
g2d.draw(OverWorldMap.BoundN);g2d.draw(OverWorldMap.BoundE);g2d.draw(OverWorldMap.BoundS);g2d.draw(OverWorldMap.BoundW);
g2d.setColor(Color.yellow); //Attack Bounds
Player.setAttackBounds();
g2d.draw(Player.attackBound);
g2d.setColor(Color.orange); //Navigation Bounds
OverWorldMap.setBounds();
if(OverWorldMap.overWorld){
g2d.draw(OverWorldMap.Over1Dungeon1);
}
if(DungeonNavigator.dungeon){
g2d.draw(DungeonNavigator.toExit);
g2d.draw(DungeonNavigator.toNorth);g2d.draw(DungeonNavigator.toEast);g2d.draw(DungeonNavigator.toSouth);g2d.draw(DungeonNavigator.toWest);
g2d.draw(DungeonNavigator.toNorth2);g2d.draw(DungeonNavigator.toEast2);g2d.draw(DungeonNavigator.toSouth2);g2d.draw(DungeonNavigator.toWest2);
}
for(int yTile = 0; yTile < 7; yTile++){
for(int xTile = 0; xTile < 9; xTile++){
g2d.draw(DungeonCollision.wallN[xTile][yTile]);g2d.draw(DungeonCollision.wallE[xTile][yTile]);g2d.draw(DungeonCollision.wallS[xTile][yTile]);g2d.draw(DungeonCollision.wallW[xTile][yTile]);
g2d.draw(DungeonCollision.wallNE[xTile][yTile]);g2d.draw(DungeonCollision.wallSE[xTile][yTile]);g2d.draw(DungeonCollision.wallSW[xTile][yTile]);g2d.draw(DungeonCollision.wallNW[xTile][yTile]);
}
}
//DungeonCollison.readWalls();
//g2d.draw(DungeonCollision.wall1[0][0]);
}
}
g.dispose();
}
public void start(){
}
//Timer loop
public void actionPerformed (ActionEvent aE){
start();
//repaint(Player.x-150, Player.y-200,600,800);
repaint();
if (repaintNow == true){
//System.out.println("repaintNow:" +repaintNow);
repaintNow = false;
repaint();
}
if(ingameThread && ingame && !menu){
System.out.println("ingame Threads start:"+ingameThread);
menuThread = false;
ingameThread = false;
ingameScheduler.scheduleWithFixedDelay(dungeonBuilderThread, 500, 50,TimeUnit.MILLISECONDS);
ingameScheduler.scheduleWithFixedDelay(mapThread, 50, 50,TimeUnit.MILLISECONDS);
ingameScheduler.scheduleWithFixedDelay(playerThread, 400, 10,TimeUnit.MILLISECONDS);
ingameScheduler.scheduleWithFixedDelay(cameraThread, 300, 5,TimeUnit.MILLISECONDS);
ingameScheduler.scheduleWithFixedDelay(collisionDetectionThread, 450, 10, TimeUnit.MILLISECONDS);
//ingameScheduler.scheduleWithFixedDelay(enemyThread,600,10,TimeUnit.MILLISECONDS);
ingameScheduler.scheduleWithFixedDelay(dungeonNavigatorThread, 600, 50, TimeUnit.MILLISECONDS);
ingameScheduler.scheduleWithFixedDelay(playerInterface, 600, 50, TimeUnit.MILLISECONDS);
//shutdown menuThreads
if(!menuScheduler.isShutdown())
System.out.println("menu shuts down:"+!menuScheduler.isShutdown());
//menuScheduler.shutdownNow();
}
if(menuThread && menu){
System.out.println("menu Threads start:"+menuThread);
menuThread = false;
ingameThread = false;
if(ingame){
System.out.println("ingameMenu Threads start");
menuScheduler.scheduleWithFixedDelay(ingameMenuThread, 10, 10,TimeUnit.MILLISECONDS);
}
if(!ingame){
System.out.println("MainMenu Threads start");
menuScheduler.scheduleWithFixedDelay(mainMenuThread, 10, 10,TimeUnit.MILLISECONDS);
}
}
if(!menu && !ingame){
System.out.println("Game shutdown");
System.exit(0);
}
}
private class KAdapter extends KeyAdapter {
public void keyReleased(KeyEvent kE){
player.keyReleased(kE);
}
public void keyPressed(KeyEvent kE){
player.keyPressed(kE);
}
}
private class MAdapter extends MouseAdapter{
public void mouseClicked( MouseEvent e ) {
clickCount++;
System.out.println(clickCount);
}
}
}
| false | true | public void paint(Graphics g) {
super.paint(g);
g2d = (Graphics2D) g;
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
if (!ingame){
//paint MenuMain
mainMenu.paintComponents(g2d);
}
if(ingame && menu){
ingameMenu.paintComponents(g2d);
}
if(gameOver){
ingame = false; menu = true;
System.err.println("Game Over");
g2d.setColor(Color.red);
Font textFont = new Font("Arial", Font.BOLD, 75);
g.setFont(textFont);
g2d.drawString("Game Over",220,300);
}
if(win){
ingame = false; menu = true;
System.err.println("Win");
g2d.setColor(Color.yellow);
Font textFont = new Font("Arial", Font.BOLD, 75);
g.setFont(textFont);
g2d.drawString("Win",330,330);
}
if (ingame && !menu && !gameOver && !win){
if(OverWorldMap.overWorld)
overWorldMap.paintComponents(g2d);
if(DungeonNavigator.dungeon)
dungeonBuilder.paintComponents(g2d);
player.paintComponents(g2d);
playerInterface.paintComponents(g2d);
//paint player interface
if(paintBounds){
g2d.setColor(Color.red); //PlayerBounds
g2d.drawRect(Player.x+10,Player.y+10,60,10);g2d.drawRect(Player.x+10,Player.y+90,60,10);g2d.drawRect(Player.x+10,Player.y+10,10,90);g2d.drawRect(Player.x+60,Player.y+10,10,90);
g2d.setColor(Color.blue); //Map Bounds
g2d.draw(OverWorldMap.BoundN);g2d.draw(OverWorldMap.BoundE);g2d.draw(OverWorldMap.BoundS);g2d.draw(OverWorldMap.BoundW);
g2d.setColor(Color.yellow); //Attack Bounds
Player.setAttackBounds();
g2d.draw(Player.attackBound);
g2d.setColor(Color.orange); //Navigation Bounds
OverWorldMap.setBounds();
if(OverWorldMap.overWorld){
g2d.draw(OverWorldMap.Over1Dungeon1);
}
if(DungeonNavigator.dungeon){
g2d.draw(DungeonNavigator.toExit);
g2d.draw(DungeonNavigator.toNorth);g2d.draw(DungeonNavigator.toEast);g2d.draw(DungeonNavigator.toSouth);g2d.draw(DungeonNavigator.toWest);
g2d.draw(DungeonNavigator.toNorth2);g2d.draw(DungeonNavigator.toEast2);g2d.draw(DungeonNavigator.toSouth2);g2d.draw(DungeonNavigator.toWest2);
}
for(int yTile = 0; yTile < 7; yTile++){
for(int xTile = 0; xTile < 9; xTile++){
g2d.draw(DungeonCollision.wallN[xTile][yTile]);g2d.draw(DungeonCollision.wallE[xTile][yTile]);g2d.draw(DungeonCollision.wallS[xTile][yTile]);g2d.draw(DungeonCollision.wallW[xTile][yTile]);
g2d.draw(DungeonCollision.wallNE[xTile][yTile]);g2d.draw(DungeonCollision.wallSE[xTile][yTile]);g2d.draw(DungeonCollision.wallSW[xTile][yTile]);g2d.draw(DungeonCollision.wallNW[xTile][yTile]);
}
}
//DungeonCollison.readWalls();
//g2d.draw(DungeonCollision.wall1[0][0]);
}
}
g.dispose();
}
| public void paint(Graphics g) {
super.paint(g);
g2d = (Graphics2D) g;
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
if (!ingame){
//paint MenuMain
mainMenu.paintComponents(g2d);
}
if(ingame && menu){
ingameMenu.paintComponents(g2d);
}
if(gameOver){
ingame = false; menu = true;
g2d.setColor(Color.red);
Font textFont = new Font("Arial", Font.BOLD, 75);
g.setFont(textFont);
g2d.drawString("Game Over",220,300);
}
if(win){
ingame = false; menu = true;
g2d.setColor(Color.yellow);
Font textFont = new Font("Arial", Font.BOLD, 75);
g.setFont(textFont);
g2d.drawString("Win",330,330);
}
if (ingame && !menu && !gameOver && !win){
if(OverWorldMap.overWorld)
overWorldMap.paintComponents(g2d);
if(DungeonNavigator.dungeon)
dungeonBuilder.paintComponents(g2d);
player.paintComponents(g2d);
playerInterface.paintComponents(g2d);
//paint player interface
if(paintBounds){
g2d.setColor(Color.red); //PlayerBounds
g2d.drawRect(Player.x+10,Player.y+10,60,10);g2d.drawRect(Player.x+10,Player.y+90,60,10);g2d.drawRect(Player.x+10,Player.y+10,10,90);g2d.drawRect(Player.x+60,Player.y+10,10,90);
g2d.setColor(Color.blue); //Map Bounds
g2d.draw(OverWorldMap.BoundN);g2d.draw(OverWorldMap.BoundE);g2d.draw(OverWorldMap.BoundS);g2d.draw(OverWorldMap.BoundW);
g2d.setColor(Color.yellow); //Attack Bounds
Player.setAttackBounds();
g2d.draw(Player.attackBound);
g2d.setColor(Color.orange); //Navigation Bounds
OverWorldMap.setBounds();
if(OverWorldMap.overWorld){
g2d.draw(OverWorldMap.Over1Dungeon1);
}
if(DungeonNavigator.dungeon){
g2d.draw(DungeonNavigator.toExit);
g2d.draw(DungeonNavigator.toNorth);g2d.draw(DungeonNavigator.toEast);g2d.draw(DungeonNavigator.toSouth);g2d.draw(DungeonNavigator.toWest);
g2d.draw(DungeonNavigator.toNorth2);g2d.draw(DungeonNavigator.toEast2);g2d.draw(DungeonNavigator.toSouth2);g2d.draw(DungeonNavigator.toWest2);
}
for(int yTile = 0; yTile < 7; yTile++){
for(int xTile = 0; xTile < 9; xTile++){
g2d.draw(DungeonCollision.wallN[xTile][yTile]);g2d.draw(DungeonCollision.wallE[xTile][yTile]);g2d.draw(DungeonCollision.wallS[xTile][yTile]);g2d.draw(DungeonCollision.wallW[xTile][yTile]);
g2d.draw(DungeonCollision.wallNE[xTile][yTile]);g2d.draw(DungeonCollision.wallSE[xTile][yTile]);g2d.draw(DungeonCollision.wallSW[xTile][yTile]);g2d.draw(DungeonCollision.wallNW[xTile][yTile]);
}
}
//DungeonCollison.readWalls();
//g2d.draw(DungeonCollision.wall1[0][0]);
}
}
g.dispose();
}
|
diff --git a/src/benchmark/BenchmarkDecisions.java b/src/benchmark/BenchmarkDecisions.java
index 0dd53c4..903f2b2 100644
--- a/src/benchmark/BenchmarkDecisions.java
+++ b/src/benchmark/BenchmarkDecisions.java
@@ -1,169 +1,169 @@
package benchmark;
import aeminium.gpu.collections.lazyness.Range;
import aeminium.gpu.collections.lists.FloatList;
import aeminium.gpu.collections.lists.PList;
import aeminium.gpu.operations.functions.LambdaMapper;
import aeminium.gpu.operations.functions.LambdaReducer;
public class BenchmarkDecisions {
public static int MAX_LEVEL=10000000;
public static int MAX_TIMES=1;
public static void main(String[] args) {
int size = 10;
int inc = 10;
while (size < MAX_LEVEL) {
runForNTimes(size);
size += inc;
if (size >= 10*inc) {
inc *= 10;
}
}
}
private static void runForNTimes(int N) {
System.out.println("Testing GPU vs GPU for N="+N);
for (int i = 0;i<MAX_TIMES; i++) {
runForN(N);
}
}
private static void runForN(int N) {
PList<Float> output;
PList<Float> input = new FloatList();
for (int i = 0; i < N; i++) {
input.add((float) i);
}
/* UNIT */
System.out.println("> GPU op: unit");
output = input.map(new LambdaMapper<Float, Float>() {
@Override
public Float map(Float input) {
return input + 1;
}
});
output.get(0);
sleep();
/* SIN */
System.out.println("> GPU op: sin " + input.size());
output = input.map(new LambdaMapper<Float, Float>() {
@Override
public Float map(Float input) {
return (float) Math.sin(input);
}
});
output.get(0);
sleep();
/* SIN and COS */
System.out.println("> GPU op: sin+cos " + input.size());
output = input.map(new LambdaMapper<Float, Float>() {
@Override
public Float map(Float input) {
return (float) (Math.sin(input) + Math.cos(input));
}
});
output.get(0);
sleep();
/* Factorial */
System.out.println("> GPU op: factorial " + input.size());
output = input.map(new LambdaMapper<Float, Float>() {
@Override
public Float map(Float input) {
int r = 1;
for (int i=1;i<=10000; i++) {
r *= i;
}
return (float) r;
}
});
output.get(0);
sleep();
/* Integral */
System.out.println("> GPU op: factorial " + input.size());
PList<Integer> li = new Range(input.size());
PList<Double> li2 = li.map(new LambdaMapper<Integer, Double>() {
@Override
public Double map(Integer input) {
double n = 10000000.0;
double b = Math.pow(Math.E, Math.sin(input / n));
double B = Math.pow(Math.E, Math.sin((input+1) / n));
return ((b+B) / 2 ) * (1/n);
}
});
@SuppressWarnings("unused")
double output2 = li2.reduce(new LambdaReducer<Double>(){
@Override
public Double combine(Double input, Double other) {
return input + other;
}
@Override
public Double getSeed() {
return 0.0;
}
});
sleep();
/* Integral */
System.out.println("> GPU op: fminimum " + input.size());
- final double RESOLUTION = (double) input.size();
+ final double RESOLUTION = 100000;
output2 = new Range(input.size()).map(new LambdaMapper<Integer, Double>() {
@Override
public Double map(Integer input) {
double x = 2*input/(double)(RESOLUTION) - 1;
return 10 * Math.pow(x, 6) + Math.pow(x, 5) + 2 * Math.pow(x, 4) + 3 * x * x * x + 2/5*x*x +Math.PI * x;
}
}).reduce(new LambdaReducer<Double>(){
@Override
public Double combine(Double input, Double other) {
return Math.min(input,other);
}
@Override
public Double getSeed() {
return Double.MAX_VALUE;
}
});
sleep();
}
private static void sleep() {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
| true | true | private static void runForN(int N) {
PList<Float> output;
PList<Float> input = new FloatList();
for (int i = 0; i < N; i++) {
input.add((float) i);
}
/* UNIT */
System.out.println("> GPU op: unit");
output = input.map(new LambdaMapper<Float, Float>() {
@Override
public Float map(Float input) {
return input + 1;
}
});
output.get(0);
sleep();
/* SIN */
System.out.println("> GPU op: sin " + input.size());
output = input.map(new LambdaMapper<Float, Float>() {
@Override
public Float map(Float input) {
return (float) Math.sin(input);
}
});
output.get(0);
sleep();
/* SIN and COS */
System.out.println("> GPU op: sin+cos " + input.size());
output = input.map(new LambdaMapper<Float, Float>() {
@Override
public Float map(Float input) {
return (float) (Math.sin(input) + Math.cos(input));
}
});
output.get(0);
sleep();
/* Factorial */
System.out.println("> GPU op: factorial " + input.size());
output = input.map(new LambdaMapper<Float, Float>() {
@Override
public Float map(Float input) {
int r = 1;
for (int i=1;i<=10000; i++) {
r *= i;
}
return (float) r;
}
});
output.get(0);
sleep();
/* Integral */
System.out.println("> GPU op: factorial " + input.size());
PList<Integer> li = new Range(input.size());
PList<Double> li2 = li.map(new LambdaMapper<Integer, Double>() {
@Override
public Double map(Integer input) {
double n = 10000000.0;
double b = Math.pow(Math.E, Math.sin(input / n));
double B = Math.pow(Math.E, Math.sin((input+1) / n));
return ((b+B) / 2 ) * (1/n);
}
});
@SuppressWarnings("unused")
double output2 = li2.reduce(new LambdaReducer<Double>(){
@Override
public Double combine(Double input, Double other) {
return input + other;
}
@Override
public Double getSeed() {
return 0.0;
}
});
sleep();
/* Integral */
System.out.println("> GPU op: fminimum " + input.size());
final double RESOLUTION = (double) input.size();
output2 = new Range(input.size()).map(new LambdaMapper<Integer, Double>() {
@Override
public Double map(Integer input) {
double x = 2*input/(double)(RESOLUTION) - 1;
return 10 * Math.pow(x, 6) + Math.pow(x, 5) + 2 * Math.pow(x, 4) + 3 * x * x * x + 2/5*x*x +Math.PI * x;
}
}).reduce(new LambdaReducer<Double>(){
@Override
public Double combine(Double input, Double other) {
return Math.min(input,other);
}
@Override
public Double getSeed() {
return Double.MAX_VALUE;
}
});
sleep();
}
| private static void runForN(int N) {
PList<Float> output;
PList<Float> input = new FloatList();
for (int i = 0; i < N; i++) {
input.add((float) i);
}
/* UNIT */
System.out.println("> GPU op: unit");
output = input.map(new LambdaMapper<Float, Float>() {
@Override
public Float map(Float input) {
return input + 1;
}
});
output.get(0);
sleep();
/* SIN */
System.out.println("> GPU op: sin " + input.size());
output = input.map(new LambdaMapper<Float, Float>() {
@Override
public Float map(Float input) {
return (float) Math.sin(input);
}
});
output.get(0);
sleep();
/* SIN and COS */
System.out.println("> GPU op: sin+cos " + input.size());
output = input.map(new LambdaMapper<Float, Float>() {
@Override
public Float map(Float input) {
return (float) (Math.sin(input) + Math.cos(input));
}
});
output.get(0);
sleep();
/* Factorial */
System.out.println("> GPU op: factorial " + input.size());
output = input.map(new LambdaMapper<Float, Float>() {
@Override
public Float map(Float input) {
int r = 1;
for (int i=1;i<=10000; i++) {
r *= i;
}
return (float) r;
}
});
output.get(0);
sleep();
/* Integral */
System.out.println("> GPU op: factorial " + input.size());
PList<Integer> li = new Range(input.size());
PList<Double> li2 = li.map(new LambdaMapper<Integer, Double>() {
@Override
public Double map(Integer input) {
double n = 10000000.0;
double b = Math.pow(Math.E, Math.sin(input / n));
double B = Math.pow(Math.E, Math.sin((input+1) / n));
return ((b+B) / 2 ) * (1/n);
}
});
@SuppressWarnings("unused")
double output2 = li2.reduce(new LambdaReducer<Double>(){
@Override
public Double combine(Double input, Double other) {
return input + other;
}
@Override
public Double getSeed() {
return 0.0;
}
});
sleep();
/* Integral */
System.out.println("> GPU op: fminimum " + input.size());
final double RESOLUTION = 100000;
output2 = new Range(input.size()).map(new LambdaMapper<Integer, Double>() {
@Override
public Double map(Integer input) {
double x = 2*input/(double)(RESOLUTION) - 1;
return 10 * Math.pow(x, 6) + Math.pow(x, 5) + 2 * Math.pow(x, 4) + 3 * x * x * x + 2/5*x*x +Math.PI * x;
}
}).reduce(new LambdaReducer<Double>(){
@Override
public Double combine(Double input, Double other) {
return Math.min(input,other);
}
@Override
public Double getSeed() {
return Double.MAX_VALUE;
}
});
sleep();
}
|
diff --git a/patientview-parent/patientview/src/main/java/org/patientview/patientview/feedback/FeedbackInputAction.java b/patientview-parent/patientview/src/main/java/org/patientview/patientview/feedback/FeedbackInputAction.java
index 39494e2f..ca354c8a 100644
--- a/patientview-parent/patientview/src/main/java/org/patientview/patientview/feedback/FeedbackInputAction.java
+++ b/patientview-parent/patientview/src/main/java/org/patientview/patientview/feedback/FeedbackInputAction.java
@@ -1,71 +1,71 @@
/*
* PatientView
*
* Copyright (c) Worth Solutions Limited 2004-2013
*
* This file is part of PatientView.
*
* PatientView 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.
* PatientView 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 PatientView in a file
* titled COPYING. If not, see <http://www.gnu.org/licenses/>.
*
* @package PatientView
* @link http://www.patientview.org
* @author PatientView <[email protected]>
* @copyright Copyright (c) 2004-2013, Worth Solutions Limited
* @license http://www.gnu.org/licenses/gpl-3.0.html The GNU General Public License V3.0
*/
package org.patientview.patientview.feedback;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.patientview.model.Unit;
import org.patientview.patientview.logon.LogonUtils;
import org.patientview.patientview.model.User;
import org.patientview.service.UnitManager;
import org.patientview.service.UserManager;
import org.patientview.utils.LegacySpringUtils;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;
public class FeedbackInputAction extends Action {
public ActionForward execute(
ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response)
throws Exception {
UserManager userManager = LegacySpringUtils.getUserManager();
UnitManager unitManager = LegacySpringUtils.getUnitManager();
User user = LegacySpringUtils.getUserManager().getLoggedInUser();
List<Unit> items = null;
final String role = userManager.getCurrentSpecialtyRole(user);
if (userManager.getCurrentSpecialtyRole(user).equals("superadmin")) {
items = unitManager.getAll(null, new String[]{"renalunit"});
} else if (role.equals("unitadmin") || role.equals("unitstaff")) {
items = unitManager.getLoggedInUsersRenalUnits();
} else {
- items = new ArrayList();
+ items = new ArrayList<Unit>();
}
request.setAttribute("units", items);
return LogonUtils.logonChecks(mapping, request);
}
}
| true | true | public ActionForward execute(
ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response)
throws Exception {
UserManager userManager = LegacySpringUtils.getUserManager();
UnitManager unitManager = LegacySpringUtils.getUnitManager();
User user = LegacySpringUtils.getUserManager().getLoggedInUser();
List<Unit> items = null;
final String role = userManager.getCurrentSpecialtyRole(user);
if (userManager.getCurrentSpecialtyRole(user).equals("superadmin")) {
items = unitManager.getAll(null, new String[]{"renalunit"});
} else if (role.equals("unitadmin") || role.equals("unitstaff")) {
items = unitManager.getLoggedInUsersRenalUnits();
} else {
items = new ArrayList();
}
request.setAttribute("units", items);
return LogonUtils.logonChecks(mapping, request);
}
| public ActionForward execute(
ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response)
throws Exception {
UserManager userManager = LegacySpringUtils.getUserManager();
UnitManager unitManager = LegacySpringUtils.getUnitManager();
User user = LegacySpringUtils.getUserManager().getLoggedInUser();
List<Unit> items = null;
final String role = userManager.getCurrentSpecialtyRole(user);
if (userManager.getCurrentSpecialtyRole(user).equals("superadmin")) {
items = unitManager.getAll(null, new String[]{"renalunit"});
} else if (role.equals("unitadmin") || role.equals("unitstaff")) {
items = unitManager.getLoggedInUsersRenalUnits();
} else {
items = new ArrayList<Unit>();
}
request.setAttribute("units", items);
return LogonUtils.logonChecks(mapping, request);
}
|
diff --git a/src/main/java/org/jbei/ice/client/common/EntryDataViewDataProvider.java b/src/main/java/org/jbei/ice/client/common/EntryDataViewDataProvider.java
index 70699ece3..5a8a70871 100755
--- a/src/main/java/org/jbei/ice/client/common/EntryDataViewDataProvider.java
+++ b/src/main/java/org/jbei/ice/client/common/EntryDataViewDataProvider.java
@@ -1,183 +1,183 @@
package org.jbei.ice.client.common;
import java.util.LinkedList;
import org.jbei.ice.client.RegistryServiceAsync;
import org.jbei.ice.client.common.table.DataTable;
import org.jbei.ice.client.common.table.column.DataTableColumn;
import org.jbei.ice.lib.shared.ColumnField;
import org.jbei.ice.lib.shared.dto.entry.PartData;
import com.google.gwt.core.client.GWT;
import com.google.gwt.user.cellview.client.ColumnSortEvent.AsyncHandler;
import com.google.gwt.user.cellview.client.ColumnSortList;
import com.google.gwt.user.cellview.client.ColumnSortList.ColumnSortInfo;
import com.google.gwt.view.client.AsyncDataProvider;
import com.google.gwt.view.client.HasData;
import com.google.gwt.view.client.Range;
// Takes care of retrieving all data page, by page
public abstract class EntryDataViewDataProvider extends AsyncDataProvider<PartData> implements IHasNavigableData {
protected int resultSize;
protected LinkedList<PartData> cachedEntries;
protected final RegistryServiceAsync service;
protected final DataTable<PartData> table;
protected ColumnField lastSortField;
protected boolean lastSortAsc = false;
public EntryDataViewDataProvider(DataTable<PartData> view, RegistryServiceAsync service) {
this.table = view;
this.service = service;
cachedEntries = new LinkedList<PartData>();
// connect sorting to async handler
AsyncHandler columnSortHandler = new AsyncHandler(table);
table.addColumnSortHandler(columnSortHandler);
DataTableColumn<PartData, ?> defaultSortField = this.table.getColumn(ColumnField.CREATED);
if (defaultSortField != null) {
ColumnSortInfo info = new ColumnSortList.ColumnSortInfo(defaultSortField, lastSortAsc);
this.table.getColumnSortList().push(info);
}
this.addDataDisplay(this.table);
}
@Override
public PartData getCachedData(long entryId, String recordId) {
for (PartData info : cachedEntries) {
if (recordId != null && info.getRecordId().equalsIgnoreCase(recordId))
return info;
if (info.getId() == entryId)
return info;
}
return null;
}
@Override
public int indexOfCached(PartData info) {
return cachedEntries.indexOf(info);
}
@Override
public PartData getNext(PartData info) {
int idx = cachedEntries.indexOf(info);
int size = cachedEntries.size();
if (size - 1 == idx + 1) {
// fetch next
cacheMore(lastSortField, lastSortAsc, size, size + 1);
}
if (size == idx + 1)
return null;
return cachedEntries.get(idx + 1);
}
@Override
public PartData getPrev(PartData info) {
int idx = cachedEntries.indexOf(info);
if (idx == -1)
return null;
return cachedEntries.get(idx - 1);
}
@Override
public int getSize() {
return resultSize;
}
@Override
protected void onRangeChanged(HasData<PartData> display) {
if (resultSize == 0) // display changed its range of interest but no data
return;
// values of range to display from view
final Range range = display.getVisibleRange();
final int rangeStart = range.getStart();
final int rangeEnd = (rangeStart + range.getLength()) > resultSize ? resultSize
: (rangeStart + range.getLength());
// last page
if (rangeEnd == resultSize && resultSize > range.getLength()) {
fetchEntryData(lastSortField, lastSortAsc, rangeStart, (resultSize - rangeStart), false);
return;
}
// user is sorting
if (sortChanged(rangeEnd)) {
fetchEntryData(lastSortField, lastSortAsc, 0, range.getLength(), true);
return;
}
// sort did not change, use data in cache
updateRowData(rangeStart, cachedEntries.subList(rangeStart, rangeEnd));
- long cacheSize = cachedEntries.size();
+ int cacheSize = cachedEntries.size();
// if range is close enough to the cache within some delta, cache more entries
if (rangeEnd + (2 * range.getLength()) >= cacheSize) {
int fetchSize = (2 * range.getLength()) + rangeEnd;
- cacheMore(lastSortField, lastSortAsc, rangeEnd, fetchSize);
+ cacheMore(lastSortField, lastSortAsc, cacheSize, fetchSize);
}
}
public void reset() {
this.cachedEntries.clear();
this.table.setVisibleRangeAndClearData(table.getVisibleRange(), false);
// reset sort
if (lastSortField == null) {
lastSortAsc = false;
lastSortField = ColumnField.CREATED;
this.table.getColumnSortList().clear();
DataTableColumn<PartData, ?> defaultSortField = this.table.getColumn(lastSortField);
if (defaultSortField != null) {
ColumnSortList.ColumnSortInfo info = new ColumnSortList.ColumnSortInfo(defaultSortField, lastSortAsc);
this.table.getColumnSortList().push(info);
}
}
}
/**
* Determines if the sort params have changed and therefore warrants a
* call to retrieve new data based on those params.
*
* @return true if the data needs to be sorted
*/
protected boolean sortChanged(int rangeEnd) {
ColumnField sortField = lastSortField;
ColumnSortList sortList = this.table.getColumnSortList();
boolean sortAsc = sortList.get(0).isAscending();
int colIndex = this.table.getColumns().indexOf(sortList.get(0).getColumn());
if (colIndex >= 0)
sortField = this.table.getColumns().get(colIndex).getField();
// check whether we need to sort in order to determine whether we can use the cache or not
if (lastSortAsc == sortAsc && lastSortField == sortField) {
// make sure there is enough data in the cache for the callee to obtain what they need based on range
if (cachedEntries.size() >= rangeEnd)
return false;
GWT.log("Not enough cached");
}
lastSortAsc = sortAsc;
lastSortField = sortField;
return true;
}
protected void cacheMore(final ColumnField field, final boolean ascending, int rangeStart, int rangeEnd) {
GWT.log("Caching [" + rangeStart + " - " + rangeEnd + "]");
int factor = (rangeEnd - rangeStart); // pages in advance
if (factor <= 0)
return;
fetchEntryData(field, ascending, rangeStart, factor, false);
}
protected abstract void fetchEntryData(ColumnField field, boolean ascending, int start, int factor, boolean reset);
}
| false | true | protected void onRangeChanged(HasData<PartData> display) {
if (resultSize == 0) // display changed its range of interest but no data
return;
// values of range to display from view
final Range range = display.getVisibleRange();
final int rangeStart = range.getStart();
final int rangeEnd = (rangeStart + range.getLength()) > resultSize ? resultSize
: (rangeStart + range.getLength());
// last page
if (rangeEnd == resultSize && resultSize > range.getLength()) {
fetchEntryData(lastSortField, lastSortAsc, rangeStart, (resultSize - rangeStart), false);
return;
}
// user is sorting
if (sortChanged(rangeEnd)) {
fetchEntryData(lastSortField, lastSortAsc, 0, range.getLength(), true);
return;
}
// sort did not change, use data in cache
updateRowData(rangeStart, cachedEntries.subList(rangeStart, rangeEnd));
long cacheSize = cachedEntries.size();
// if range is close enough to the cache within some delta, cache more entries
if (rangeEnd + (2 * range.getLength()) >= cacheSize) {
int fetchSize = (2 * range.getLength()) + rangeEnd;
cacheMore(lastSortField, lastSortAsc, rangeEnd, fetchSize);
}
}
| protected void onRangeChanged(HasData<PartData> display) {
if (resultSize == 0) // display changed its range of interest but no data
return;
// values of range to display from view
final Range range = display.getVisibleRange();
final int rangeStart = range.getStart();
final int rangeEnd = (rangeStart + range.getLength()) > resultSize ? resultSize
: (rangeStart + range.getLength());
// last page
if (rangeEnd == resultSize && resultSize > range.getLength()) {
fetchEntryData(lastSortField, lastSortAsc, rangeStart, (resultSize - rangeStart), false);
return;
}
// user is sorting
if (sortChanged(rangeEnd)) {
fetchEntryData(lastSortField, lastSortAsc, 0, range.getLength(), true);
return;
}
// sort did not change, use data in cache
updateRowData(rangeStart, cachedEntries.subList(rangeStart, rangeEnd));
int cacheSize = cachedEntries.size();
// if range is close enough to the cache within some delta, cache more entries
if (rangeEnd + (2 * range.getLength()) >= cacheSize) {
int fetchSize = (2 * range.getLength()) + rangeEnd;
cacheMore(lastSortField, lastSortAsc, cacheSize, fetchSize);
}
}
|
diff --git a/src/compress/BitPacker.java b/src/compress/BitPacker.java
index 40f8300..558f29a 100644
--- a/src/compress/BitPacker.java
+++ b/src/compress/BitPacker.java
@@ -1,227 +1,227 @@
package compress;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* @author Jake Bellamy 1130587 jrb46
* @author Michael Coleman 1144239 mjc62
*/
public class BitPacker {
IOHandler io;
/**
* Construct a new BitPacker reading from standard in.
*/
public BitPacker() {
io = new IOConsoleHandler();
}
/**
* Construct a new BitPacker reading from a file.
* @param filename The file name to read from.
*/
public BitPacker(String filename) {
io = new IOFileHandler(filename);
}
/**
* Construct a new BitPacker with a given IO Handler.
* @param io The IO Handler to use with this bit packer.
*/
public BitPacker(IOHandler io) {
this.io = io;
}
/**
* @param args
*/
public static void main(String[] args) {
BitPacker bp;
if (args.length > 0) {
bp = new BitPacker(args[0]);
System.out.println("Encoding from file " + args[0] + "...");
} else {
bp = new BitPacker();
System.out.println("Packing from standard input.\n Please " +
"enter the tuples you wish to pack followed by an " +
"empty line.");
}
bp.pack();
}
/**
* Reads tuples from the IO Handler and packs the tuples so they use
* the minimum amount of bits needed.
*/
public void pack() {
- int indexLength = 6;
+ int indexLength = 5;
String message = io.readString();
Pattern p = Pattern.compile("[^0-9]");
Matcher m = p.matcher(message);
int startindex = 0, mindex = 0, byteIndex = 0, bitIndex = 8;
int bufLength = 50;
byte[] buf = new byte[bufLength + 1];
/**
* Loop through each tuple that we find, calculate lengths and
* indices.
*/
while (m.find()) {
mindex = m.end();
String phnum = message.substring(startindex, mindex - 1);
startindex = mindex;
if (phnum.length() == 0) {
continue;
}
int phraseNum = Integer.parseInt(phnum);
int character = message.charAt(mindex - 1);
- int phraseLength = getBitLength(phraseNum) + 1;
+ int phraseLength = getBitLength(phraseNum);
/**
* With each tuple that we find we are outputting 3 things:
* The number of bits needed to represent the phrase number,
* The phrase number itself,
* And the character.
*/
for (int i = 0; i < 3; i++) {
int[] vars = setVars(i, indexLength, phraseLength,
phraseNum, character);
/**
* Set the next offset for the placement of the next bits
* that we are inserting into the byte. If the offset is
* negative that indicates that there is not enough space
* in this byte to store these bits completely so we must
* split it up and store the overflow into the next byte.
*/
bitIndex -= vars[0];
if (bitIndex < 0) {
//Calculate indices and lengths for correct placement.
int topbits = bitIndex + vars[0];
int off = Math.abs(bitIndex);
/**
* Store what we can fit into this byte, and the rest
* in the next byte.
*/
buf[byteIndex]= setBits
(buf[byteIndex], vars[1], off, topbits);
buf[++byteIndex] = setBits
(buf[byteIndex], vars[1], 8 - off);
//Fix up the bit index so it references this new byte
bitIndex += 8;
} else {
/**
* The bits we are storing fits into the space left
* in this byte so put all of them in.
*/
buf[byteIndex] = setBits
(buf[byteIndex], vars[1], bitIndex);
}
/**
* Check if we have reached the length of our buffer.
* Output the entire buffer except the last byte as there
* may be more space left in it to insert bits into.
* Swap the last byte to the first position of our new
* buffer and fix up the current byte index.
*/
if (byteIndex == bufLength) {
io.writeBytes(buf, bufLength);
byte swap = buf[byteIndex];
buf = new byte[bufLength + 1];
buf[0] = swap;
byteIndex = 0;
}
}
}
/**
* There is no more input so write out the data we collected and
* close the streams.
*/
io.writeBytes(buf, byteIndex + 1);
io.closeAllStreams();
}
/**
* Gets some bits out of a byte. For example to extract the x bits
* from a byte given as {@code 000x xx00} then call this method with
* {@code length = 3} and {@code offset = 2}.
* @param b The byte we are extracting bits from.
* @param length The number of bits to extract.
* @param offset The starting position in the byte to extract from.
* @return An integer with the extracted bits.
*/
private int getBits(byte b, int length, int offset) {
/**
* Build up a mask full of 1-bits for ANDing with the byte that
* we want the bits out of.
*/
int mask = 0;
for (int i = 0; i < length; i++) {
mask = (mask << 1) + 1;
}
return (b >> offset) & mask;
}
/**
* Sets bits in a byte.
* @param b The byte in which to store bytes into.
* @param bits The bits to store.
* @param offset The position in which to store the bits.
* @return The same byte except with the given bits set in it.
*/
private byte setBits(byte b, int bits, int offset) {
return (byte) (b | (bits << offset));
}
private byte setBits(byte b, int bits, int offset, int length) {
int mask = 0;
for (int i = 0; i < length; i++) {
mask = (mask << 1) + 1;
}
return (byte) (b | ((bits >> offset) & mask));
}
/**
* Gets the minimum number of bits needed to represent a given number.
* @param num The number to check.
* @return The number of significant bits in the number.
*/
private int getBitLength(int num) {
return (32 - Integer.numberOfLeadingZeros(num));
}
/**
* Sets up variables passed in by the packing method. This is a simple
* convenience method so the variables may be used in a for loop.
*/
private int[] setVars(int i, int indexLength, int phraseLength,
int phraseNum, int character) {
int[] vars = new int[2];
switch (i) {
case 0:
vars[0] = indexLength;
vars[1] = phraseLength;
return vars;
case 1:
vars[0] = phraseLength;
vars[1] = phraseNum;
return vars;
case 2:
vars[0] = 8;
vars[1] = character;
return vars;
default:
return vars;
}
}
}
| false | true | public void pack() {
int indexLength = 6;
String message = io.readString();
Pattern p = Pattern.compile("[^0-9]");
Matcher m = p.matcher(message);
int startindex = 0, mindex = 0, byteIndex = 0, bitIndex = 8;
int bufLength = 50;
byte[] buf = new byte[bufLength + 1];
/**
* Loop through each tuple that we find, calculate lengths and
* indices.
*/
while (m.find()) {
mindex = m.end();
String phnum = message.substring(startindex, mindex - 1);
startindex = mindex;
if (phnum.length() == 0) {
continue;
}
int phraseNum = Integer.parseInt(phnum);
int character = message.charAt(mindex - 1);
int phraseLength = getBitLength(phraseNum) + 1;
/**
* With each tuple that we find we are outputting 3 things:
* The number of bits needed to represent the phrase number,
* The phrase number itself,
* And the character.
*/
for (int i = 0; i < 3; i++) {
int[] vars = setVars(i, indexLength, phraseLength,
phraseNum, character);
/**
* Set the next offset for the placement of the next bits
* that we are inserting into the byte. If the offset is
* negative that indicates that there is not enough space
* in this byte to store these bits completely so we must
* split it up and store the overflow into the next byte.
*/
bitIndex -= vars[0];
if (bitIndex < 0) {
//Calculate indices and lengths for correct placement.
int topbits = bitIndex + vars[0];
int off = Math.abs(bitIndex);
/**
* Store what we can fit into this byte, and the rest
* in the next byte.
*/
buf[byteIndex]= setBits
(buf[byteIndex], vars[1], off, topbits);
buf[++byteIndex] = setBits
(buf[byteIndex], vars[1], 8 - off);
//Fix up the bit index so it references this new byte
bitIndex += 8;
} else {
/**
* The bits we are storing fits into the space left
* in this byte so put all of them in.
*/
buf[byteIndex] = setBits
(buf[byteIndex], vars[1], bitIndex);
}
/**
* Check if we have reached the length of our buffer.
* Output the entire buffer except the last byte as there
* may be more space left in it to insert bits into.
* Swap the last byte to the first position of our new
* buffer and fix up the current byte index.
*/
if (byteIndex == bufLength) {
io.writeBytes(buf, bufLength);
byte swap = buf[byteIndex];
buf = new byte[bufLength + 1];
buf[0] = swap;
byteIndex = 0;
}
}
}
/**
* There is no more input so write out the data we collected and
* close the streams.
*/
io.writeBytes(buf, byteIndex + 1);
io.closeAllStreams();
}
| public void pack() {
int indexLength = 5;
String message = io.readString();
Pattern p = Pattern.compile("[^0-9]");
Matcher m = p.matcher(message);
int startindex = 0, mindex = 0, byteIndex = 0, bitIndex = 8;
int bufLength = 50;
byte[] buf = new byte[bufLength + 1];
/**
* Loop through each tuple that we find, calculate lengths and
* indices.
*/
while (m.find()) {
mindex = m.end();
String phnum = message.substring(startindex, mindex - 1);
startindex = mindex;
if (phnum.length() == 0) {
continue;
}
int phraseNum = Integer.parseInt(phnum);
int character = message.charAt(mindex - 1);
int phraseLength = getBitLength(phraseNum);
/**
* With each tuple that we find we are outputting 3 things:
* The number of bits needed to represent the phrase number,
* The phrase number itself,
* And the character.
*/
for (int i = 0; i < 3; i++) {
int[] vars = setVars(i, indexLength, phraseLength,
phraseNum, character);
/**
* Set the next offset for the placement of the next bits
* that we are inserting into the byte. If the offset is
* negative that indicates that there is not enough space
* in this byte to store these bits completely so we must
* split it up and store the overflow into the next byte.
*/
bitIndex -= vars[0];
if (bitIndex < 0) {
//Calculate indices and lengths for correct placement.
int topbits = bitIndex + vars[0];
int off = Math.abs(bitIndex);
/**
* Store what we can fit into this byte, and the rest
* in the next byte.
*/
buf[byteIndex]= setBits
(buf[byteIndex], vars[1], off, topbits);
buf[++byteIndex] = setBits
(buf[byteIndex], vars[1], 8 - off);
//Fix up the bit index so it references this new byte
bitIndex += 8;
} else {
/**
* The bits we are storing fits into the space left
* in this byte so put all of them in.
*/
buf[byteIndex] = setBits
(buf[byteIndex], vars[1], bitIndex);
}
/**
* Check if we have reached the length of our buffer.
* Output the entire buffer except the last byte as there
* may be more space left in it to insert bits into.
* Swap the last byte to the first position of our new
* buffer and fix up the current byte index.
*/
if (byteIndex == bufLength) {
io.writeBytes(buf, bufLength);
byte swap = buf[byteIndex];
buf = new byte[bufLength + 1];
buf[0] = swap;
byteIndex = 0;
}
}
}
/**
* There is no more input so write out the data we collected and
* close the streams.
*/
io.writeBytes(buf, byteIndex + 1);
io.closeAllStreams();
}
|
diff --git a/src/test/java/no/arktekk/talkjdk8/Stream1MapSinkTest.java b/src/test/java/no/arktekk/talkjdk8/Stream1MapSinkTest.java
index 4f866e7..2459c5e 100644
--- a/src/test/java/no/arktekk/talkjdk8/Stream1MapSinkTest.java
+++ b/src/test/java/no/arktekk/talkjdk8/Stream1MapSinkTest.java
@@ -1,20 +1,20 @@
package no.arktekk.talkjdk8;
import org.junit.Test;
import java.util.List;
import java.util.stream.Collectors;
import static java.util.Arrays.asList;
import static org.junit.Assert.assertEquals;
public class Stream1MapSinkTest {
@Test
public void test() {
List<String> names = asList("Tom Waits", "Johnny Cash", "Stefan Sundström");
- List<String> surNames = names.stream().map((String s) -> s.substring(0, s.indexOf(' '))).collect(Collectors.<String>toList());
- assertEquals(asList("Tom", "Johnny", "Stefan"), surNames);
+ List<String> foreNames = names.stream().map((String s) -> s.substring(0, s.indexOf(' '))).collect(Collectors.<String>toList());
+ assertEquals(asList("Tom", "Johnny", "Stefan"), foreNames);
}
}
| true | true | public void test() {
List<String> names = asList("Tom Waits", "Johnny Cash", "Stefan Sundström");
List<String> surNames = names.stream().map((String s) -> s.substring(0, s.indexOf(' '))).collect(Collectors.<String>toList());
assertEquals(asList("Tom", "Johnny", "Stefan"), surNames);
}
| public void test() {
List<String> names = asList("Tom Waits", "Johnny Cash", "Stefan Sundström");
List<String> foreNames = names.stream().map((String s) -> s.substring(0, s.indexOf(' '))).collect(Collectors.<String>toList());
assertEquals(asList("Tom", "Johnny", "Stefan"), foreNames);
}
|
diff --git a/srcj/com/sun/electric/tool/io/output/Verilog.java b/srcj/com/sun/electric/tool/io/output/Verilog.java
index 0508d422b..a863469f7 100755
--- a/srcj/com/sun/electric/tool/io/output/Verilog.java
+++ b/srcj/com/sun/electric/tool/io/output/Verilog.java
@@ -1,1895 +1,1895 @@
/* -*- tab-width: 4 -*-
*
* Electric(tm) VLSI Design System
*
* File: Verilog.java
* Input/output tool: Verilog Netlist output
* Written by Steven M. Rubin, Sun Microsystems.
*
* 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.io.output;
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.network.Global;
import com.sun.electric.database.network.Netlist;
import com.sun.electric.database.network.Network;
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.text.Version;
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.CodeExpression;
import com.sun.electric.database.variable.VarContext;
import com.sun.electric.database.variable.Variable;
import com.sun.electric.technology.PrimitiveNode;
import com.sun.electric.technology.technologies.Generic;
import com.sun.electric.technology.technologies.Schematics;
import com.sun.electric.tool.generator.sclibrary.SCLibraryGen;
import com.sun.electric.tool.io.input.verilog.VerilogData;
import com.sun.electric.tool.io.input.verilog.VerilogReader;
import com.sun.electric.tool.simulation.Simulation;
import com.sun.electric.tool.user.User;
import com.sun.electric.tool.user.dialogs.BusParameters;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* This is the Simulation Interface tool.
*/
public class Verilog extends Topology
{
/** A set of keywords that are reserved in Verilog */
private static Set<String> reservedWords;
static
{
reservedWords = new HashSet<String>();
reservedWords.add("always");
reservedWords.add("and");
reservedWords.add("assign");
reservedWords.add("attribute");
reservedWords.add("begin");
reservedWords.add("buf");
reservedWords.add("bufif0");
reservedWords.add("bufif1");
reservedWords.add("case");
reservedWords.add("casex");
reservedWords.add("casez");
reservedWords.add("cmos");
reservedWords.add("deassign");
reservedWords.add("default");
reservedWords.add("defpram");
reservedWords.add("disable");
reservedWords.add("edge");
reservedWords.add("else");
reservedWords.add("end");
reservedWords.add("endattribute");
reservedWords.add("endcase");
reservedWords.add("endfunction");
reservedWords.add("endmodule");
reservedWords.add("endprimitive");
reservedWords.add("endspecify");
reservedWords.add("endtable");
reservedWords.add("endtask");
reservedWords.add("event");
reservedWords.add("for");
reservedWords.add("force");
reservedWords.add("forever");
reservedWords.add("fork");
reservedWords.add("function");
reservedWords.add("highz0");
reservedWords.add("highz1");
reservedWords.add("if");
reservedWords.add("initial");
reservedWords.add("inout");
reservedWords.add("input");
reservedWords.add("integer");
reservedWords.add("join");
reservedWords.add("large");
reservedWords.add("macromodule");
reservedWords.add("meduim");
reservedWords.add("module");
reservedWords.add("nand");
reservedWords.add("negedge");
reservedWords.add("nmos");
reservedWords.add("nor");
reservedWords.add("not");
reservedWords.add("notif0");
reservedWords.add("notif1");
reservedWords.add("or");
reservedWords.add("output");
reservedWords.add("parameter");
reservedWords.add("pmos");
reservedWords.add("posedge");
reservedWords.add("primitive");
reservedWords.add("pull0");
reservedWords.add("pull1");
reservedWords.add("pulldown");
reservedWords.add("pullup");
reservedWords.add("rcmos");
reservedWords.add("real");
reservedWords.add("realtime");
reservedWords.add("reg");
reservedWords.add("release");
reservedWords.add("repeat");
reservedWords.add("rtranif1");
reservedWords.add("scalared");
reservedWords.add("signed");
reservedWords.add("small");
reservedWords.add("specify");
reservedWords.add("specpram");
reservedWords.add("strength");
reservedWords.add("strong0");
reservedWords.add("strong1");
reservedWords.add("supply0");
reservedWords.add("supply1");
reservedWords.add("table");
reservedWords.add("task");
reservedWords.add("time");
reservedWords.add("tran");
reservedWords.add("tranif0");
reservedWords.add("tranif1");
reservedWords.add("tri");
reservedWords.add("tri0");
reservedWords.add("tri1");
reservedWords.add("triand");
reservedWords.add("trior");
reservedWords.add("trireg");
reservedWords.add("unsigned");
reservedWords.add("vectored");
reservedWords.add("wait");
reservedWords.add("wand");
reservedWords.add("weak0");
reservedWords.add("weak1");
reservedWords.add("while");
reservedWords.add("wire");
reservedWords.add("wor");
reservedWords.add("xnor");
reservedWords.add("xor");
}
/** maximum size of output line */ private static final int MAXDECLARATIONWIDTH = 80;
/** name of inverters generated from negated wires */ private static final String IMPLICITINVERTERNODENAME = "Imp";
/** name of signals generated from negated wires */ private static final String IMPLICITINVERTERSIGNAME = "ImpInv";
/** key of Variable holding verilog code. */ public static final Variable.Key VERILOG_CODE_KEY = Variable.newKey("VERILOG_code");
/** key of Variable holding verilog declarations. */ public static final Variable.Key VERILOG_DECLARATION_KEY = Variable.newKey("VERILOG_declaration");
/** key of Variable holding verilog parameters. */ public static final Variable.Key VERILOG_PARAMETER_KEY = Variable.newKey("VERILOG_parameter");
/** key of Variable holding verilog code that is
** external to the module. */ public static final Variable.Key VERILOG_EXTERNAL_CODE_KEY = Variable.newKey("VERILOG_external_code");
/** key of Variable holding verilog wire time. */ public static final Variable.Key WIRE_TYPE_KEY = Variable.newKey("SIM_verilog_wire_type");
/** key of Variable holding verilog templates. */ public static final Variable.Key VERILOG_TEMPLATE_KEY = Variable.newKey("ATTR_verilog_template");
/** key of Variable holding verilog defparams. */ public static final Variable.Key VERILOG_DEFPARAM_KEY = Variable.newKey("ATTR_verilog_defparam");
/** key of Variable holding file name with Verilog. */ public static final Variable.Key VERILOG_BEHAVE_FILE_KEY = Variable.newKey("SIM_verilog_behave_file");
/** those cells that have overridden models */ private Set<Cell> modelOverrides = new HashSet<Cell>();
/** those cells that have modules defined */ private Map<String,String> definedModules = new HashMap<String,String>(); // key: module name, value: source description
/** those cells that have primitives defined */ private Map<Cell,VerilogData.VerilogModule> definedPrimitives = new HashMap<Cell,VerilogData.VerilogModule>(); // key: module name, value: VerilogModule
/** map of cells that are or contain standard cells */ private SCLibraryGen.StandardCellHierarchy standardCells = new SCLibraryGen.StandardCellHierarchy();
/** file we are writing to */ private String filePath;
public static String getVerilogSafeName(String name, boolean isNode, boolean isBus) {
Verilog v = new Verilog();
if (isNode) return v.getSafeCellName(name);
return v.getSafeNetName(name, isBus);
}
/**
* The main entry point for Verilog deck writing.
* @param cell the top-level cell to write.
* @param context the hierarchical context to the cell.
* @param filePath the disk file to create.
*/
public static void writeVerilogFile(Cell cell, VarContext context, String filePath)
{
Verilog out = new Verilog();
if (out.openTextOutputStream(filePath)) return;
out.filePath = filePath;
if (out.writeCell(cell, context)) return;
if (out.closeTextOutputStream()) return;
System.out.println(filePath + " written");
}
/**
* Creates a new instance of Verilog
*/
Verilog()
{
}
protected void start()
{
// parameters to the output-line-length limit and how to break long lines
setOutputWidth(MAXDECLARATIONWIDTH, false);
setContinuationString(" ");
// write header information
printWriter.println("/* Verilog for " + topCell + " from " + topCell.getLibrary() + " */");
emitCopyright("/* ", " */");
if (User.isIncludeDateAndVersionInOutput())
{
printWriter.println("/* Created on " + TextUtils.formatDate(topCell.getCreationDate()) + " */");
printWriter.println("/* Last revised on " + TextUtils.formatDate(topCell.getRevisionDate()) + " */");
printWriter.println("/* Written on " + TextUtils.formatDate(new Date()) +
" by Electric VLSI Design System, version " + Version.getVersion() + " */");
} else
{
printWriter.println("/* Written by Electric VLSI Design System */");
}
if (Simulation.getVerilogStopAtStandardCells()) {
// enumerate to find which cells contain standard cells
HierarchyEnumerator.enumerateCell(topCell, VarContext.globalContext, standardCells);
for (Cell acell : standardCells.getDoesNotContainStandardCellsInHier()) {
System.out.println("Warning: Not netlisting cell "+acell.describe(false)+" because it does not contain any standard cells.");
}
if (standardCells.getNameConflict()) {
System.out.println("Name conflicts found, please see above messages");
}
}
}
protected void done()
{
// Remove this call that auto-overrides the new user visible preference
// Simulation.setVerilogStopAtStandardCells(false);
}
protected boolean skipCellAndSubcells(Cell cell) {
// do not netlist contents of standard cells
// also, if writing a standard cell netlist, ignore all verilog views, verilog templates, etc.
if (Simulation.getVerilogStopAtStandardCells()) {
if (!standardCells.containsStandardCell(cell)) {
return true;
} else {
return false;
}
}
// do not write modules for cells with verilog_templates defined
// also skip their subcells
if (cell.getVar(VERILOG_TEMPLATE_KEY) != null) {
return true;
}
// also skip subcells if a behavioral file specified.
// If one specified, write it out here and skip both cell and subcells
if (CellModelPrefs.verilogModelPrefs.isUseModelFromFile(cell)) {
String fileName = CellModelPrefs.verilogModelPrefs.getModelFile(cell);
if (filePath.equals(fileName)) {
System.out.println("Error: Use Model From File file path for cell "+cell.describe(false)+" is the same as the file being written, skipping.");
return false;
}
// check that data from file is consistent
VerilogReader reader = new VerilogReader();
VerilogData data = reader.parseVerilog(fileName, true);
if (data == null) {
System.out.println("Error reading include file: "+fileName);
return false;
}
if (!checkIncludedData(data, cell, fileName))
return false;
if (!modelOverrides.contains(cell))
{
printWriter.println("`include \"" + fileName + "\"");
modelOverrides.add(cell);
}
return true;
}
// use library behavior if it is available
Cell verViewCell = cell.otherView(View.VERILOG);
if (verViewCell != null)
{
String [] stringArray = verViewCell.getTextViewContents();
if (stringArray != null)
{
if (stringArray.length > 0) {
String line = stringArray[0].toLowerCase();
if (line.startsWith("do not use")) {
return false;
}
}
VerilogReader reader = new VerilogReader();
VerilogData data = reader.parseVerilog(stringArray, cell.getLibrary().getName());
if (data == null) {
System.out.println("Error parsing Verilog View for cell "+cell.describe(false));
return false;
}
if (!checkIncludedData(data, cell, null))
return false;
// write to output file
System.out.println("Info: Netlisting Verilog view of "+cell.describe(false));
printWriter.println();
printWriter.println("/* Verilog view of "+verViewCell.libDescribe()+" */");
for(int i=0; i<stringArray.length; i++)
printWriter.println(stringArray[i]);
}
return true;
}
return false;
}
/**
* Method to write cellGeom
*/
protected void writeCellTopology(Cell cell, CellNetInfo cni, VarContext context, Topology.MyCellInfo info)
{
if (cell == topCell) {
// gather all global signal names
Netlist netList = cni.getNetList();
Global.Set globals = netList.getGlobals();
int globalSize = globals.size();
// see if any globals besides power and ground to write
List<Global> globalsToWrite = new ArrayList<Global>();
for (int i=0; i<globalSize; i++) {
Global global = globals.get(i);
if (global == Global.power || global == Global.ground) continue;
globalsToWrite.add(global);
}
if (globalsToWrite.size() > 0)
{
printWriter.println("\nmodule glbl();");
for(int i=0; i<globalsToWrite.size(); i++)
{
Global global = globalsToWrite.get(i);
if (Simulation.getVerilogUseTrireg())
{
printWriter.println(" trireg " + global.getName() + ";");
} else
{
printWriter.println(" wire " + global.getName() + ";");
}
}
printWriter.println("endmodule");
}
}
// prepare arcs to store implicit inverters
Map<ArcInst,Integer> implicitHeadInverters = new HashMap<ArcInst,Integer>();
Map<ArcInst,Integer> implicitTailInverters = new HashMap<ArcInst,Integer>();
int impInvCount = 0;
for(Iterator<ArcInst> it = cell.getArcs(); it.hasNext(); )
{
ArcInst ai = it.next();
for(int e=0; e<2; e++)
{
if (!ai.isNegated(e)) continue;
PortInst pi = ai.getPortInst(e);
NodeInst ni = pi.getNodeInst();
if (ni.getProto() == Schematics.tech().bufferNode || ni.getProto() == Schematics.tech().andNode ||
ni.getProto() == Schematics.tech().orNode || ni.getProto() == Schematics.tech().xorNode)
{
if (Simulation.getVerilogUseAssign()) continue;
if (pi.getPortProto().getName().equals("y")) continue;
}
// must create implicit inverter here
if (e == ArcInst.HEADEND) implicitHeadInverters.put(ai, new Integer(impInvCount)); else
implicitTailInverters.put(ai, new Integer(impInvCount));
if (ai.getProto() != Schematics.tech().bus_arc) impInvCount++; else
{
int wid = cni.getNetList().getBusWidth(ai);
impInvCount += wid;
}
}
}
// gather networks in the cell
Netlist netList = cni.getNetList();
// add in any user-specified defines
includeTypedCode(cell, VERILOG_EXTERNAL_CODE_KEY, "external code");
// write the module header
printWriter.println();
StringBuffer sb = new StringBuffer();
sb.append("module " + cni.getParameterizedName() + "(");
boolean first = true;
for(Iterator<CellAggregateSignal> it = cni.getCellAggregateSignals(); it.hasNext(); )
{
CellAggregateSignal cas = it.next();
if (cas.getExport() == null) continue;
if (cas.getLowIndex() <= cas.getHighIndex() && cas.getIndices() != null)
{
// fragmented bus: write individual signals
int [] indices = cas.getIndices();
for(int i=0; i<indices.length; i++)
{
int ind = i;
if (cas.isDescending()) ind = indices.length - i - 1;
if (!first) sb.append(",");
sb.append(" \\" + cas.getName() + "[" + indices[ind] + "] ");
first = false;
}
} else
{
// simple name, add to module header
if (!first) sb.append(", ");
sb.append(cas.getName());
first = false;
}
}
sb.append(");\n");
writeWidthLimited(sb.toString());
definedModules.put(cni.getParameterizedName(), "Cell "+cell.libDescribe());
// add in any user-specified parameters
includeTypedCode(cell, VERILOG_PARAMETER_KEY, "parameters");
// look for "wire/trireg" overrides
for(Iterator<ArcInst> it = cell.getArcs(); it.hasNext(); )
{
ArcInst ai = it.next();
Variable var = ai.getVar(WIRE_TYPE_KEY);
if (var == null) continue;
String wireType = var.getObject().toString();
int overrideValue = 0;
if (wireType.equalsIgnoreCase("wire")) overrideValue = 1; else
if (wireType.equalsIgnoreCase("trireg")) overrideValue = 2;
int busWidth = netList.getBusWidth(ai);
for(int i=0; i<busWidth; i++)
{
Network net = netList.getNetwork(ai, i);
CellSignal cs = cni.getCellSignal(net);
if (cs == null) continue;
cs.getAggregateSignal().setFlags(overrideValue);
}
}
// write description of formal parameters to module
first = true;
for(Iterator<CellAggregateSignal> it = cni.getCellAggregateSignals(); it.hasNext(); )
{
CellAggregateSignal cas = it.next();
Export pp = cas.getExport();
if (pp == null) continue;
String portType = "input";
if (pp.getCharacteristic() == PortCharacteristic.OUT)
portType = "output";
else if (pp.getCharacteristic() == PortCharacteristic.BIDIR)
portType = "inout";
sb = new StringBuffer();
sb.append(" " + portType);
if (cas.getLowIndex() > cas.getHighIndex())
{
sb.append(" " + cas.getName() + ";");
} else
{
int [] indices = cas.getIndices();
if (indices != null)
{
for(int i=0; i<indices.length; i++)
{
int ind = i;
if (cas.isDescending()) ind = indices.length - i - 1;
if (i != 0) sb.append(",");
sb.append(" \\" + cas.getName() + "[" + indices[ind] + "] ");
}
sb.append(";");
} else
{
int low = cas.getLowIndex(), high = cas.getHighIndex();
if (cas.isDescending())
{
low = cas.getHighIndex(); high = cas.getLowIndex();
}
sb.append(" [" + low + ":" + high + "] " + cas.getName() + ";");
}
}
if (cas.getFlags() != 0)
{
if (cas.getFlags() == 1) sb.append(" wire"); else
sb.append(" trireg");
sb.append(" " + cas.getName() + ";");
}
sb.append("\n");
writeWidthLimited(sb.toString());
first = false;
}
if (!first) printWriter.println();
// if writing standard cell netlist, do not netlist contents of standard cells
if (Simulation.getVerilogStopAtStandardCells())
{
if (SCLibraryGen.isStandardCell(cell)) {
printWriter.println("endmodule /* " + cni.getParameterizedName() + " */");
return;
}
}
// describe power and ground nets
if (cni.getPowerNet() != null) printWriter.println(" supply1 vdd;");
if (cni.getGroundNet() != null) printWriter.println(" supply0 gnd;");
// determine whether to use "wire" or "trireg" for networks
String wireType = "wire";
if (Simulation.getVerilogUseTrireg()) wireType = "trireg";
// write "wire/trireg" declarations for internal single-wide signals
int localWires = 0;
for(int wt=0; wt<2; wt++)
{
first = true;
for(Iterator<CellAggregateSignal> it = cni.getCellAggregateSignals(); it.hasNext(); )
{
CellAggregateSignal cas = it.next();
if (cas.getExport() != null) continue;
if (cas.isSupply()) continue;
if (cas.getLowIndex() <= cas.getHighIndex()) continue;
if (cas.isGlobal()) continue;
String impSigName = wireType;
if (cas.getFlags() != 0)
{
if (cas.getFlags() == 1) impSigName = "wire"; else
impSigName = "trireg";
}
if ((wt == 0) ^ !wireType.equals(impSigName))
{
if (first)
{
initDeclaration(" " + impSigName);
}
addDeclaration(cas.getName());
localWires++;
first = false;
}
}
if (!first) termDeclaration();
}
// write "wire/trireg" declarations for internal busses
for(Iterator<CellAggregateSignal> it = cni.getCellAggregateSignals(); it.hasNext(); )
{
CellAggregateSignal cas = it.next();
if (cas.getExport() != null) continue;
if (cas.isSupply()) continue;
if (cas.getLowIndex() > cas.getHighIndex()) continue;
if (cas.isGlobal()) continue;
int [] indices = cas.getIndices();
if (indices != null)
{
for(int i=0; i<indices.length; i++)
{
int ind = i;
if (cas.isDescending()) ind = indices.length - i - 1;
printWriter.println(" " + wireType + " \\" + cas.getName() + "[" + indices[ind] + "] ;");
}
} else
{
if (cas.isDescending())
{
printWriter.println(" " + wireType + " [" + cas.getHighIndex() + ":" + cas.getLowIndex() + "] " + cas.getName() + ";");
} else
{
printWriter.println(" " + wireType + " [" + cas.getLowIndex() + ":" + cas.getHighIndex() + "] " + cas.getName() + ";");
}
}
localWires++;
}
if (localWires != 0) printWriter.println();
// add "wire" declarations for implicit inverters
if (impInvCount > 0)
{
initDeclaration(" " + wireType);
for(int i=0; i<impInvCount; i++)
{
String impsigname = IMPLICITINVERTERSIGNAME + i;
addDeclaration(impsigname);
}
termDeclaration();
}
// add in any user-specified declarations and code
if (!Simulation.getVerilogStopAtStandardCells()) {
// STA does not like general verilog code (like and #delay out ina inb etc)
first = includeTypedCode(cell, VERILOG_DECLARATION_KEY, "declarations");
first |= includeTypedCode(cell, VERILOG_CODE_KEY, "code");
if (!first)
printWriter.println(" /* automatically generated Verilog */");
}
// accumulate port connectivity information for port directional consistency check
Map<Network,List<Export>> instancePortsOnNet = new HashMap<Network,List<Export>>();
// look at every node in this cell
for(Iterator<Nodable> nIt = netList.getNodables(); nIt.hasNext(); )
{
Nodable no = nIt.next();
NodeProto niProto = no.getProto();
// not interested in passive nodes (ports electrically connected)
PrimitiveNode.Function nodeType = PrimitiveNode.Function.UNKNOWN;
if (!no.isCellInstance())
{
NodeInst ni = (NodeInst)no;
Iterator<PortInst> pIt = ni.getPortInsts();
if (pIt.hasNext())
{
boolean allConnected = true;
PortInst firstPi = pIt.next();
Network firstNet = netList.getNetwork(firstPi);
for( ; pIt.hasNext(); )
{
PortInst pi = pIt.next();
Network thisNet = netList.getNetwork(pi);
if (thisNet != firstNet) { allConnected = false; break; }
}
if (allConnected) continue;
}
nodeType = ni.getFunction();
// special case: verilog should ignore R L C etc.
if (nodeType.isResistor() || // == PrimitiveNode.Function.RESIST ||
nodeType.isCapacitor() || // == PrimitiveNode.Function.CAPAC || nodeType == PrimitiveNode.Function.ECAPAC ||
nodeType == PrimitiveNode.Function.INDUCT ||
nodeType == PrimitiveNode.Function.DIODE || nodeType == PrimitiveNode.Function.DIODEZ)
continue;
}
// look for a Verilog template on the prototype
if (no.isCellInstance())
{
// if writing standard cell netlist, do not write out cells that
// do not contain standard cells
if (Simulation.getVerilogStopAtStandardCells())
{
if (!standardCells.containsStandardCell((Cell)niProto) &&
!SCLibraryGen.isStandardCell((Cell)niProto)) continue;
}
Variable varTemplate = ((Cell)niProto).getVar(VERILOG_TEMPLATE_KEY);
if (varTemplate != null)
{
if (varTemplate.getObject() instanceof String []) {
String [] lines = (String [])varTemplate.getObject();
writeWidthLimited(" /* begin Verilog_template for "+no.getProto().describe(false)+"*/\n");
for (int i=0; i<lines.length; i++) {
writeTemplate(lines[i], no, cni, context);
}
writeWidthLimited(" // end Verilog_template\n");
} else {
// special case: do not write out string "//"
if (!((String)varTemplate.getObject()).equals("//")) {
writeWidthLimited(" /* begin Verilog_template for "+no.getProto().describe(false)+"*/\n");
writeTemplate((String)varTemplate.getObject(), no, cni, context);
writeWidthLimited(" // end Verilog_template\n");
}
}
continue;
}
}
// look for a Verilog defparam template on the prototype
// Defparam templates provide a mechanism for prepending per instance
// parameters on verilog declarations
if (no.isCellInstance())
{
Variable varDefparamTemplate = ((Cell)niProto).getVar(VERILOG_DEFPARAM_KEY);
if (varDefparamTemplate != null)
{
if (varDefparamTemplate.getObject() instanceof String []) {
String [] lines = (String [])varDefparamTemplate.getObject();
// writeWidthLimited(" /* begin Verilog_defparam for "+no.getProto().describe(false)+" */\n");
boolean firstDefparam = true;
for (int i=0; i<lines.length; i++) {
//StringBuffer infstr = new StringBuffer();
String defparam = new String();
defparam = writeDefparam(lines[i], no, context);
if (defparam.length() != 0)
{
if (firstDefparam)
{
writeWidthLimited(" /* begin Verilog_defparam for "+no.getProto().describe(false)+" */\n");
firstDefparam = false;
}
writeWidthLimited(defparam);
}
}
if (!firstDefparam)
{
writeWidthLimited(" // end Verilog_defparam\n");
}
} else
{
// special case: do not write out string "//"
if (!((String)varDefparamTemplate.getObject()).equals("//"))
{
String defparam = new String();
defparam = writeDefparam((String)varDefparamTemplate.getObject(), no, context);
if (defparam.length() != 0)
{
writeWidthLimited(" /* begin Verilog_defparam for "+no.getProto().describe(false)+"*/\n");
writeWidthLimited(defparam);
writeWidthLimited(" // end Verilog_defparam\n");
}
}
}
}
}
// use "assign" statement if requested
if (Simulation.getVerilogUseAssign())
{
if (nodeType == PrimitiveNode.Function.GATEAND || nodeType == PrimitiveNode.Function.GATEOR ||
nodeType == PrimitiveNode.Function.GATEXOR || nodeType == PrimitiveNode.Function.BUFFER)
{
// assign possible: determine operator
String op = "";
if (nodeType == PrimitiveNode.Function.GATEAND) op = " & "; else
if (nodeType == PrimitiveNode.Function.GATEOR) op = " | "; else
if (nodeType == PrimitiveNode.Function.GATEXOR) op = " ^ ";
// write a line describing this signal
StringBuffer infstr = new StringBuffer();
boolean wholeNegated = false;
first = true;
NodeInst ni = (NodeInst)no;
for(int i=0; i<2; i++)
{
for(Iterator<Connection> cIt = ni.getConnections(); cIt.hasNext(); )
{
Connection con = cIt.next();
PortInst pi = con.getPortInst();
if (i == 0)
{
if (!pi.getPortProto().getName().equals("y")) continue;
} else
{
if (!pi.getPortProto().getName().equals("a")) continue;
}
// determine the network name at this port
ArcInst ai = con.getArc();
Network net = netList.getNetwork(ai, 0);
CellSignal cs = cni.getCellSignal(net);
String sigName = getSignalName(cs);
// see if this end is negated
boolean isNegated = false;
if (ai.isTailNegated() || ai.isHeadNegated()) isNegated = true;
// write the port name
if (i == 0)
{
// got the output port: do the left-side of the "assign"
infstr.append("assign " + sigName + " = ");
if (isNegated)
{
infstr.append("~(");
wholeNegated = true;
}
break;
}
if (!first)
infstr.append(op);
first = false;
if (isNegated) infstr.append("~");
infstr.append(sigName);
}
}
if (wholeNegated)
infstr.append(")");
infstr.append(";\n");
writeWidthLimited(infstr.toString());
continue;
}
}
// get the name of the node
int implicitPorts = 0;
boolean dropBias = false;
String nodeName = "";
if (no.isCellInstance())
{
// make sure there are contents for this cell instance
if (((Cell)niProto).isIcon()) continue;
nodeName = parameterizedName(no, context);
// cells defined as "primitives" in Verilog View must have implicit port ordering
if (definedPrimitives.containsKey(niProto)) {
implicitPorts = 3;
}
} else
{
// convert 4-port transistors to 3-port
if (nodeType == PrimitiveNode.Function.TRA4NMOS)
{
nodeType = PrimitiveNode.Function.TRANMOS; dropBias = true;
} else if (nodeType == PrimitiveNode.Function.TRA4PMOS)
{
nodeType = PrimitiveNode.Function.TRAPMOS; dropBias = true;
}
- if (nodeType == PrimitiveNode.Function.TRANMOS)
+ if (nodeType.isNTypeTransistor())
{
implicitPorts = 2;
nodeName = "tranif1";
Variable varWeakNode = ((NodeInst)no).getVar(Simulation.WEAK_NODE_KEY);
if (varWeakNode != null) nodeName = "rtranif1";
} else if (nodeType == PrimitiveNode.Function.TRAPMOS)
{
implicitPorts = 2;
nodeName = "tranif0";
Variable varWeakNode = ((NodeInst)no).getVar(Simulation.WEAK_NODE_KEY);
if (varWeakNode != null) nodeName = "rtranif0";
} else if (nodeType == PrimitiveNode.Function.GATEAND)
{
implicitPorts = 1;
nodeName = chooseNodeName((NodeInst)no, "and", "nand");
} else if (nodeType == PrimitiveNode.Function.GATEOR)
{
implicitPorts = 1;
nodeName = chooseNodeName((NodeInst)no, "or", "nor");
} else if (nodeType == PrimitiveNode.Function.GATEXOR)
{
implicitPorts = 1;
nodeName = chooseNodeName((NodeInst)no, "xor", "xnor");
} else if (nodeType == PrimitiveNode.Function.BUFFER)
{
implicitPorts = 1;
nodeName = chooseNodeName((NodeInst)no, "buf", "not");
}
}
if (nodeName.length() == 0) continue;
// write the type of the node
StringBuffer infstr = new StringBuffer();
infstr.append(" " + nodeName + " " + nameNoIndices(no.getName()) + "(");
// write the rest of the ports
first = true;
NodeInst ni = null;
switch (implicitPorts)
{
case 0: // explicit ports (for cell instances)
CellNetInfo subCni = getCellNetInfo(nodeName);
for(Iterator<CellAggregateSignal> sIt = subCni.getCellAggregateSignals(); sIt.hasNext(); )
{
CellAggregateSignal cas = sIt.next();
// ignore networks that aren't exported
PortProto pp = cas.getExport();
if (pp == null) continue;
if (first) first = false; else
infstr.append(", ");
if (cas.getLowIndex() > cas.getHighIndex())
{
// single signal
infstr.append("." + cas.getName() + "(");
Network net = netList.getNetwork(no, pp, cas.getExportIndex());
CellSignal cs = cni.getCellSignal(net);
infstr.append(getSignalName(cs));
infstr.append(")");
accumulatePortConnectivity(instancePortsOnNet, net, (Export)pp);
} else
{
int [] indices = cas.getIndices();
if (indices != null)
{
// broken bus internally, write signals individually
for(int i=0; i<indices.length; i++)
{
CellSignal cInnerSig = cas.getSignal(i);
Network net = netList.getNetwork(no, cas.getExport(), cInnerSig.getExportIndex());
CellSignal outerSignal = cni.getCellSignal(net);
accumulatePortConnectivity(instancePortsOnNet, net, (Export)pp);
int ind = i;
if (cas.isDescending()) ind = indices.length - i - 1;
if (i > 0) infstr.append(", ");
infstr.append(".\\" + cas.getName() + "[" + indices[ind] + "] (");
infstr.append(getSignalName(outerSignal));
infstr.append(")");
}
} else
{
// simple bus, write signals
int total = cas.getNumSignals();
CellSignal [] outerSignalList = new CellSignal[total];
for(int j=0; j<total; j++)
{
CellSignal cInnerSig = cas.getSignal(j);
Network net = netList.getNetwork(no, cas.getExport(), cInnerSig.getExportIndex());
outerSignalList[j] = cni.getCellSignal(net);
accumulatePortConnectivity(instancePortsOnNet, net, (Export)pp);
}
writeBus(outerSignalList, total, cas.isDescending(),
cas.getName(), cni.getPowerNet(), cni.getGroundNet(), infstr);
}
}
}
infstr.append(");");
break;
case 1: // and/or gate: write ports in the proper order
ni = (NodeInst)no;
for(int i=0; i<2; i++)
{
for(Iterator<Connection> cIt = ni.getConnections(); cIt.hasNext(); )
{
Connection con = cIt.next();
PortInst pi = con.getPortInst();
if (i == 0)
{
if (!pi.getPortProto().getName().equals("y")) continue;
} else
{
if (!pi.getPortProto().getName().equals("a")) continue;
}
if (first) first = false; else
infstr.append(", ");
ArcInst ai = con.getArc();
Network net = netList.getNetwork(ai, 0);
CellSignal cs = cni.getCellSignal(net);
if (cs == null) continue;
String sigName = getSignalName(cs);
if (i != 0 && con.isNegated())
{
// this input is negated: write the implicit inverter
Integer invIndex;
if (con.getEndIndex() == ArcInst.HEADEND) invIndex = implicitHeadInverters.get(ai); else
invIndex = implicitTailInverters.get(ai);
if (invIndex != null)
{
String invSigName = IMPLICITINVERTERSIGNAME + invIndex.intValue();
printWriter.println(" inv " + IMPLICITINVERTERNODENAME +
invIndex.intValue() + " (" + invSigName + ", " + sigName + ");");
sigName = invSigName;
}
}
infstr.append(sigName);
}
}
infstr.append(");");
break;
case 2: // transistors: write ports in the proper order: s/d/g
ni = (NodeInst)no;
Network gateNet = netList.getNetwork(ni.getTransistorGatePort());
for(int i=0; i<2; i++)
{
boolean didGate = false;
for(Iterator<PortInst> pIt = ni.getPortInsts(); pIt.hasNext(); )
{
PortInst pi = pIt.next();
Network net = netList.getNetwork(pi);
if (dropBias && pi.getPortProto().getName().equals("b")) continue;
if (i == 0)
{
if (net == gateNet) continue;
} else
{
if (net != gateNet) continue;
if (didGate) continue;
didGate = true;
}
if (first) first = false; else
infstr.append(", ");
CellSignal cs = cni.getCellSignal(net);
String sigName = getSignalName(cs);
infstr.append(sigName);
}
}
infstr.append(");");
break;
case 3: // implicit ports ordering for cells defined as primitives in Verilog View
ni = no.getNodeInst();
VerilogData.VerilogModule module = definedPrimitives.get(niProto);
if (module == null) break;
System.out.print(cell.getName()+" ports: ");
for (VerilogData.VerilogPort port : module.getPorts()) {
List<String> portnames = port.getPinNames(true);
if (portnames.size() == 0) {
// continue
} else if (portnames.size() > 1) {
// Bill thinks bussed ports are not allowed for primitives
System.out.println("Error: bussed ports not allowed on Verilog primitives: "+niProto.getName());
} else {
String portname = portnames.get(0);
PortInst pi = ni.findPortInst(portname);
Network net = netList.getNetwork(no, pi.getProtoEquivalent(), 0);
CellSignal cs = cni.getCellSignal(net);
String sigName = getSignalName(cs);
if (first) first = false; else
infstr.append(", ");
infstr.append(sigName);
System.out.print(portname+" ");
}
}
System.out.println();
infstr.append(");");
break;
}
infstr.append("\n");
writeWidthLimited(infstr.toString());
}
printWriter.println("endmodule /* " + cni.getParameterizedName() + " */");
// check export direction consistency (inconsistent directions can cause opens in some tools)
for (Iterator<Export> it = cell.getExports(); it.hasNext(); ) {
Export ex = it.next();
PortCharacteristic type = ex.getCharacteristic();
if (type == PortCharacteristic.BIDIR) continue; // whatever it is connect to is fine
for (int i=0; i<ex.getNameKey().busWidth(); i++) {
Network net = netList.getNetwork(ex, i);
List<Export> subports = instancePortsOnNet.get(net);
if (subports == null) continue;
for (Export subex : subports) {
PortCharacteristic subtype = subex.getCharacteristic();
if (type != subtype) {
System.out.println("Warning: Port Direction Inconsistency in cell "+cell.describe(false)+
" between export "+ex.getNameKey().subname(i)+"["+type+"] and instance port "+
subex.getParent().noLibDescribe()+" - "+subex.getName()+"["+subtype+"]");
}
}
}
}
}
private String getSignalName(CellSignal cs)
{
CellAggregateSignal cas = cs.getAggregateSignal();
if (cas == null) return cs.getName();
if (cas.getIndices() == null) return cs.getName();
return " \\" + cs.getName() + " ";
}
private String chooseNodeName(NodeInst ni, String positive, String negative)
{
for(Iterator<Connection> aIt = ni.getConnections(); aIt.hasNext(); )
{
Connection con = aIt.next();
if (con.isNegated() &&
con.getPortInst().getPortProto().getName().equals("y"))
return negative;
}
return positive;
}
private void writeTemplate(String line, Nodable no, CellNetInfo cni, VarContext context)
{
// special case for Verilog templates
Netlist netList = cni.getNetList();
StringBuffer infstr = new StringBuffer();
infstr.append(" ");
for(int pt = 0; pt < line.length(); pt++)
{
char chr = line.charAt(pt);
if (chr != '$' || pt+1 >= line.length() || line.charAt(pt+1) != '(')
{
// process normal character
infstr.append(chr);
continue;
}
int startpt = pt + 2;
for(pt = startpt; pt < line.length(); pt++)
if (line.charAt(pt) == ')') break;
String paramName = line.substring(startpt, pt);
PortProto pp = no.getProto().findPortProto(paramName);
String nodeName = parameterizedName(no, context);
CellNetInfo subCni = getCellNetInfo(nodeName);
// see if aggregate signal matches pp
CellAggregateSignal cas = null;
CellSignal netcs = null;
if (pp != null) {
// it matches the whole port (may be a bussed port)
for (Iterator<CellAggregateSignal> it = subCni.getCellAggregateSignals(); it.hasNext(); ) {
CellAggregateSignal cas2 = it.next();
if (cas2.getExport() == pp) {
cas = cas2;
break;
}
if (netList.sameNetwork(no, pp, no, cas2.getExport())) {
// this will be true if there are two exports connected together
// in the subcell, and we are searching for the export name that is not used.
cas = cas2;
break;
}
}
} else {
// maybe it is a single bit in an bussed export
for (Iterator<PortProto> it = no.getProto().getPorts(); it.hasNext(); ) {
PortProto ppcheck = it.next();
for (int i=0; i<ppcheck.getNameKey().busWidth(); i++) {
if (paramName.equals(ppcheck.getNameKey().subname(i).toString())) {
Network net = netList.getNetwork(no, ppcheck, i);
netcs = cni.getCellSignal(net);
break;
}
}
}
}
if (cas != null) {
// this code is copied from instantiated
if (cas.getLowIndex() > cas.getHighIndex())
{
// single signal
Network net = netList.getNetwork(no, pp, cas.getExportIndex());
CellSignal cs = cni.getCellSignal(net);
infstr.append(getSignalName(cs));
} else
{
int total = cas.getNumSignals();
CellSignal [] outerSignalList = new CellSignal[total];
for(int j=0; j<total; j++)
{
CellSignal cInnerSig = cas.getSignal(j);
Network net = netList.getNetwork(no, cas.getExport(), cInnerSig.getExportIndex());
outerSignalList[j] = cni.getCellSignal(net);
}
writeBus(outerSignalList, total, cas.isDescending(),
null, cni.getPowerNet(), cni.getGroundNet(), infstr);
}
} else if (netcs != null) {
infstr.append(getSignalName(netcs));
} else if (paramName.equalsIgnoreCase("node_name"))
{
infstr.append(getSafeNetName(no.getName(), true));
} else
{
// no port name found, look for variable name
Variable var = null;
Variable.Key varKey = Variable.findKey("ATTR_" + paramName);
if (varKey != null) {
var = no.getParameterOrVariable(varKey);
}
if (var == null) infstr.append("??"); else
{
infstr.append(context.evalVar(var));
}
}
}
infstr.append("\n");
writeWidthLimited(infstr.toString());
}
/**
* writeDefparam is a specialized version of writeTemplate. This function will
* take a Electric Variable (Attribute) and write it out as a parameter.
* @param line
* @param no
* @param cni
* @param context
* @return
*/
private String writeDefparam(String line, Nodable no, VarContext context)
{
// special case for Verilog defparams
StringBuffer infstr = new StringBuffer();
// Setup a standard template for defparams
infstr.append(" defparam ");
// Get the nodes instance name
infstr.append(getSafeNetName(no.getName(), true));
infstr.append(".");
// Prepend whatever text is on the line, assuming it is a a variable per line
// Garbage will be generated otherwise
for(int pt = 0; pt < line.length(); pt++)
{
char chr = line.charAt(pt);
if (chr != '$' || pt+1 >= line.length() || line.charAt(pt+1) != '(')
{
// process normal character
infstr.append(chr);
continue;
}
int startpt = pt + 2;
for(pt = startpt; pt < line.length(); pt++)
if (line.charAt(pt) == ')') break;
String paramName = line.substring(startpt, pt);
// Check the current parameter value against the default parameter value
// only overwrite if they are different.
if (!(no.getProto() instanceof Cell))
{
System.out.println("Illegal attempt to replace a variable.");
return "";
}
String defaultValue = replaceVariable(paramName, (Cell) no.getProto());
String paramValue = replaceVariable(paramName, no, context);
if (paramValue == "" || paramValue.equals(defaultValue)) return "";
infstr.append(paramName);
infstr.append(" = ");
infstr.append(paramValue);
infstr.append(";");
}
infstr.append("\n");
// writeWidthLimited(infstr.toString());
return infstr.toString();
}
/**
* replaceVariable - Replace Electric variables (attributes) with their
* values on instances of a cell. Given that left and right parens are not
* valid characters in Verilog identifiers, any Verilog code that matches
* $([a-zA-Z0-9_$]*) is not a valid sequence. This allows us to extract any
* electric variable and replace it with the attribute value.
* Additionally, search the value of the Electric variable for a nested
* variable and replace that as well.
* Added for ArchGen Plugin - BVE
*
* @param line
* @param no
* @param context
* @return
*/
private String replaceVariable(String varName, Nodable no, VarContext context)
{
// FIXIT - BVE should this be getSafeCellName
if (varName.equalsIgnoreCase("node_name"))
return getSafeNetName(no.getName(), true);
// look for variable name
Variable var = null;
Variable.Key varKey = Variable.findKey("ATTR_" + varName);
if (varKey != null)
{
var = no.getVar(varKey);
if (var == null) var = no.getParameter(varKey);
}
if (var == null) return "";
String val = String.valueOf(context.evalVar(var));
// Semi-recursive call to search the value of a variable for a nested variable.
return replaceVarInString(val, no.getParent());
}
/**
* replaceVariable - Replace Electric variables (attributes) with their
* values on definitions of a cell. Given that left and right parens are not
* valid characters in Verilog identifiers, any verilog code that matches
* $([a-zA-Z0-9_$]*) is not a valid sequence. This allows us to extract any
* electric variable and replace it with the attribute value.
* Added for ArchGen Plugin - BVE
*
* @param line
* @param cell
* @return
*/
private String replaceVariable(String varName, Cell cell)
{
// FIXIT - BVE should this be getSafeCellName
if (varName.equalsIgnoreCase("node_name"))
return getSafeNetName(cell.getName(), true);
// look for variable name
Variable var = null;
Variable.Key varKey = Variable.findKey("ATTR_" + varName);
if (varKey != null) {
var = cell.getVar(varKey);
if (var == null) var = cell.getParameter(varKey);
}
if (var == null) return "";
// Copied this code from VarContext.java - evalVarRecurse
CodeExpression.Code code = var.getCode();
Object value = var.getObject();
if ((code == CodeExpression.Code.JAVA) ||
(code == CodeExpression.Code.TCL) ||
(code == CodeExpression.Code.SPICE)) return "";
return String.valueOf(value);
}
/**
* replaceVarInString will search a string and replace any electric variable
* with its attribute or parameter value, if it has one.
* Added for ArchGen Plugin - BVE
*
* @param line
* @param cell
* @return
*/
private String replaceVarInString(String line, Cell cell)
{
StringBuffer infstr = new StringBuffer();
// Search the line for any electric variables
for(int pt = 0; pt < line.length(); pt++)
{
char chr = line.charAt(pt);
if (chr != '$' || pt+1 >= line.length() || line.charAt(pt+1) != '(')
{
// process normal character
infstr.append(chr);
continue;
}
int startpt = pt + 2;
for(pt = startpt; pt < line.length(); pt++)
if (line.charAt(pt) == ')') break;
String paramName = line.substring(startpt, pt);
String paramValue = replaceVariable(paramName, cell);
// If the parameter doesn't have a value, then look in the bus parameters
if (paramValue != "") {
infstr.append(paramValue);
}else {
paramValue = BusParameters.replaceBusParameterInt("$("+paramName+")");
// If the parameter isn't a bus parameter, then just leave the paramName
if (paramValue != "") {
infstr.append(paramValue);
} else
{
infstr.append("$(");
infstr.append(paramName);
infstr.append(")");
}
}
}
return infstr.toString();
}
/**
* Method to add a bus of signals named "name" to the infinite string "infstr". If "name" is zero,
* do not include the ".NAME()" wrapper. The signals are in "outerSignalList" and range in index from
* "lowindex" to "highindex". They are described by a bus with characteristic "tempval"
* (low bit is on if the bus descends). Any unconnected networks can be numbered starting at
* "*unconnectednet". The power and grounds nets are "pwrnet" and "gndnet".
*/
private void writeBus(CellSignal [] outerSignalList, int total, boolean descending,
String name, Network pwrNet, Network gndNet, StringBuffer infstr)
{
// array signal: see if it gets split out
boolean breakBus = false;
// bus cannot have pwr/gnd, must be connected
int numExported = 0, numInternal = 0;
for(int j=0; j<total; j++)
{
CellSignal cs = outerSignalList[j];
CellAggregateSignal cas = cs.getAggregateSignal();
if (cas != null && cas.getIndices() != null) { breakBus = true; break; }
if (cs.isPower() || cs.isGround()) { breakBus = true; break; }
if (cs.isExported()) numExported++; else
numInternal++;
}
// must be all exported or all internal, not a mix
if (numExported > 0 && numInternal > 0) breakBus = true;
if (!breakBus)
{
// see if all of the nets on this bus are distinct
int j = 1;
for( ; j<total; j++)
{
CellSignal cs = outerSignalList[j];
int k = 0;
for( ; k<j; k++)
{
CellSignal oCs = outerSignalList[k];
if (cs == oCs) break;
}
if (k < j) break;
}
if (j < total) breakBus = true; else
{
// bus entries must have the same root name and go in order
String lastnetname = null;
for(j=0; j<total; j++)
{
CellSignal wl = outerSignalList[j];
String thisnetname = getSignalName(wl);
if (wl.isDescending())
{
if (!descending) break;
} else
{
if (descending) break;
}
int openSquare = thisnetname.indexOf('[');
if (openSquare < 0) break;
if (j > 0)
{
int li = 0;
for( ; li < lastnetname.length(); li++)
{
if (thisnetname.charAt(li) != lastnetname.charAt(li)) break;
if (lastnetname.charAt(li) == '[') break;
}
if (lastnetname.charAt(li) != '[' || thisnetname.charAt(li) != '[') break;
int thisIndex = TextUtils.atoi(thisnetname.substring(li+1));
int lastIndex = TextUtils.atoi(lastnetname.substring(li+1));
if (thisIndex != lastIndex + 1) break;
}
lastnetname = thisnetname;
}
if (j < total) breakBus = true;
}
}
if (name != null) infstr.append("." + name + "(");
if (breakBus)
{
infstr.append("{");
int start = 0, end = total-1;
int order = 1;
if (descending)
{
start = total-1;
end = 0;
order = -1;
}
for(int j=start; ; j += order)
{
if (j != start)
infstr.append(", ");
CellSignal cs = outerSignalList[j];
infstr.append(getSignalName(cs));
if (j == end) break;
}
infstr.append("}");
} else
{
CellSignal lastCs = outerSignalList[0];
String lastNetName = getSignalName(lastCs);
int openSquare = lastNetName.indexOf('[');
CellSignal cs = outerSignalList[total-1];
String netName = getSignalName(cs);
int i = 0;
for( ; i<netName.length(); i++)
{
if (netName.charAt(i) == '[') break;
infstr.append(netName.charAt(i));
}
if (descending)
{
int first = TextUtils.atoi(netName.substring(i+1));
int second = TextUtils.atoi(lastNetName.substring(openSquare+1));
infstr.append("[" + first + ":" + second + "]");
} else
{
int first = TextUtils.atoi(netName.substring(i+1));
int second = TextUtils.atoi(lastNetName.substring(openSquare+1));
infstr.append("[" + second + ":" + first + "]");
}
}
if (name != null) infstr.append(")");
}
/**
* Method to add text from all nodes in cell "np"
* (which have "verilogkey" text on them)
* to that text to the output file. Returns true if anything
* was found.
*/
private boolean includeTypedCode(Cell cell, Variable.Key verilogkey, String descript)
{
// write out any directly-typed Verilog code
boolean first = true;
for(Iterator<NodeInst> it = cell.getNodes(); it.hasNext(); )
{
NodeInst ni = it.next();
if (ni.getProto() != Generic.tech().invisiblePinNode) continue;
Variable var = ni.getVar(verilogkey);
if (var == null) continue;
if (!var.isDisplay()) continue;
Object obj = var.getObject();
if (!(obj instanceof String) && !(obj instanceof String [])) continue;
if (first)
{
first = false;
printWriter.println(" /* user-specified Verilog " + descript + " */");
}
if (obj instanceof String)
{
String tmp = replaceVarInString((String)obj, cell);
printWriter.println(" " + tmp);
// printWriter.println(" " + (String)obj);
} else
{
String [] stringArray = (String [])obj;
int len = stringArray.length;
for(int i=0; i<len; i++) {
String tmp = replaceVarInString(stringArray[i], cell);
printWriter.println(" " + tmp);
// printWriter.println(" " + stringArray[i]);
}
}
}
if (!first) printWriter.println();
return first;
}
private StringBuffer sim_verDeclarationLine;
private int sim_verdeclarationprefix;
/**
* Method to initialize the collection of signal names in a declaration.
* The declaration starts with the string "header".
*/
private void initDeclaration(String header)
{
sim_verDeclarationLine = new StringBuffer();
sim_verDeclarationLine.append(header);
sim_verdeclarationprefix = header.length();
}
/**
* Method to add "signame" to the collection of signal names in a declaration.
*/
private void addDeclaration(String signame)
{
if (sim_verDeclarationLine.length() + signame.length() + 3 > MAXDECLARATIONWIDTH)
{
printWriter.println(sim_verDeclarationLine.toString() + ";");
sim_verDeclarationLine.delete(sim_verdeclarationprefix, sim_verDeclarationLine.length());
}
if (sim_verDeclarationLine.length() != sim_verdeclarationprefix)
sim_verDeclarationLine.append(",");
sim_verDeclarationLine.append(" " + signame);
}
/**
* Method to terminate the collection of signal names in a declaration
* and write the declaration to the Verilog file.
*/
private void termDeclaration()
{
printWriter.println(sim_verDeclarationLine.toString() + ";");
}
/**
* Method to adjust name "p" and return the string.
* This code removes all index indicators and other special characters, turning
* them into "_".
*/
private String nameNoIndices(String p)
{
StringBuffer sb = new StringBuffer();
if (TextUtils.isDigit(p.charAt(0))) sb.append('_');
for(int i=0; i<p.length(); i++)
{
char chr = p.charAt(i);
if (!TextUtils.isLetterOrDigit(chr) && chr != '_' && chr != '$') chr = '_';
sb.append(chr);
}
return sb.toString();
}
/****************************** SUBCLASSED METHODS FOR THE TOPOLOGY ANALYZER ******************************/
/**
* Method to adjust a cell name to be safe for Verilog output.
* @param name the cell name.
* @return the name, adjusted for Verilog output.
*/
protected String getSafeCellName(String name)
{
String n = getSafeNetName(name, false);
// [ and ] are not allowed in cell names
return n.replaceAll("[\\[\\]]", "_");
}
/** Method to return the proper name of Power */
protected String getPowerName(Network net) { return "vdd"; }
/** Method to return the proper name of Ground */
protected String getGroundName(Network net) { return "gnd"; }
/** Method to return the proper name of a Global signal */
protected String getGlobalName(Global glob) { return "glbl." + glob.getName(); }
/** Method to report that export names DO take precedence over
* arc names when determining the name of the network. */
protected boolean isNetworksUseExportedNames() { return true; }
/** Method to report that library names ARE always prepended to cell names. */
protected boolean isLibraryNameAlwaysAddedToCellName() { return true; }
/** Method to report that aggregate names (busses) ARE used. */
protected boolean isAggregateNamesSupported() { return true; }
/** Abstract method to decide whether aggregate names (busses) can have gaps in their ranges. */
protected boolean isAggregateNameGapsSupported() { return true; }
/** Method to report whether input and output names are separated. */
protected boolean isSeparateInputAndOutput() { return true; }
/**
* Method to adjust a network name to be safe for Verilog output.
* Verilog does permit a digit in the first location; prepend a "_" if found.
* Verilog only permits the "_" and "$" characters: all others are converted to "_".
* Verilog does not permit nonnumeric indices, so "P[A]" is converted to "P_A_"
* Verilog does not permit multidimensional arrays, so "P[1][2]" is converted to "P_1_[2]"
* and "P[1][T]" is converted to "P_1__T_"
* @param bus true if this is a bus name.
*/
protected String getSafeNetName(String name, boolean bus)
{
// simple names are trivially accepted as is
boolean allAlnum = true;
int len = name.length();
if (len == 0) return name;
int openSquareCount = 0;
int openSquarePos = 0;
for(int i=0; i<len; i++)
{
char chr = name.charAt(i);
if (chr == '[') { openSquareCount++; openSquarePos = i; }
if (!TextUtils.isLetterOrDigit(chr)) allAlnum = false;
if (i == 0 && TextUtils.isDigit(chr)) allAlnum = false;
}
if (!allAlnum || !Character.isLetter(name.charAt(0)))
{
// if there are indexed values, make sure they are numeric
if (openSquareCount == 1)
{
if (openSquarePos+1 >= name.length() ||
!Character.isDigit(name.charAt(openSquarePos+1))) openSquareCount = 0;
}
if (bus) openSquareCount = 0;
StringBuffer sb = new StringBuffer();
for(int t=0; t<name.length(); t++)
{
char chr = name.charAt(t);
if (chr == '[' || chr == ']')
{
if (openSquareCount == 1) sb.append(chr); else
{
sb.append('_');
// merge two underscores into one
// if (t+1 < name.length() && chr == ']' && name.charAt(t+1) == '[') t++;
}
} else
{
if (t == 0 && TextUtils.isDigit(chr)) sb.append('_');
if (TextUtils.isLetterOrDigit(chr) || chr == '$')
sb.append(chr); else
sb.append('_');
}
}
name = sb.toString();
}
// make sure it isn't a reserved word
if (reservedWords.contains(name)) name = "_" + name;
return name;
}
/** Tell the Hierarchy enumerator how to short resistors */
@Override
protected Netlist.ShortResistors getShortResistors() { return Netlist.ShortResistors.PARASITIC; }
/**
* Method to tell whether the topological analysis should mangle cell names that are parameterized.
*/
protected boolean canParameterizeNames() {
if (Simulation.getVerilogStopAtStandardCells())
return false;
// Check user preference
if (Simulation.getVerilogParameterizeModuleNames()) return true;
return false;
}
private static final String [] verilogGates = new String [] {
"and",
"nand",
"or",
"nor",
"xor",
"xnor",
"buf",
"bufif0",
"bufif1",
"not",
"notif0",
"notif1",
"pulldown",
"pullup",
"nmos",
"rnmos",
"pmos",
"rpmos",
"cmos",
"rcmos",
"tran",
"rtran",
"tranif0",
"rtranif0",
"tranif1",
"rtranif1",
};
/**
* Perform some checks on parsed Verilog data, including the
* check that module is defined for the cell it is replacing.
* Some checks are different depending upon if the source is
* a Verilog View or an included external file.
* @param data the parsed Verilog data
* @param cell the cell to be replaced (must be verilog view if replacing Verilog View)
* @param includeFile the included file (null if replacing Verilog View)
* @return false if there was an error
*/
private boolean checkIncludedData(VerilogData data, Cell cell, String includeFile) {
// make sure there is module for current cell
Collection<VerilogData.VerilogModule> modules = data.getModules();
VerilogData.VerilogModule main = null, alternative = null;
for (VerilogData.VerilogModule mod : modules) {
if (mod.getName().equals(getVerilogName(cell)))
main = mod;
else {
Cell.CellGroup grp = cell.getCellGroup(); // if cell group is available
if (grp != null && mod.getName().equals(grp.getName()))
alternative = mod;
}
}
if (main == null) main = alternative;
if (main == null) {
System.out.println("Error! Expected Verilog module definition '"+getVerilogName(cell)+
" in Verilog View: "+cell.libDescribe());
return false;
}
if (main.isPrimitive())
definedPrimitives.put(cell, main);
String source = includeFile == null ? "Verilog View for "+cell.libDescribe() :
"Include file: "+includeFile;
// check that modules have not already been defined
for (VerilogData.VerilogModule mod : modules) {
String prevSource = definedModules.get(mod.getName());
if (mod.isValid()) {
if (prevSource != null) {
System.out.println("Error, module "+mod.getName()+" already defined from: "+prevSource);
}
else
definedModules.put(mod.getName(), source);
}
}
// make sure ports for module match ports for cell
// Collection<VerilogData.VerilogPort> ports = main.getPorts();
// not sure how to do this right now
// check for undefined instances, search libraries for them
for (VerilogData.VerilogModule mod : modules) {
for (VerilogData.VerilogInstance inst : mod.getInstances()) {
VerilogData.VerilogModule instMod = inst.getModule();
if (instMod.isValid())
continue; // found in file, continue
// check if primitive
boolean primitiveGate = false;
for (String s : verilogGates) {
if (s.equals(instMod.getName().toLowerCase())) {
primitiveGate = true;
break;
}
}
if (primitiveGate) continue;
// undefined, look in modules already written
String moduleName = instMod.getName();
String found = definedModules.get(moduleName);
if (found == null && includeFile == null) {
// search libraries for it
Cell missingCell = findCell(moduleName, View.VERILOG);
if (missingCell == null) {
System.out.println("Error: Undefined reference to module "+moduleName+", and no matching cell found");
continue;
}
// hmm...name map might be wrong at for this new enumeration
System.out.println("Info: Netlisting cell "+missingCell.libDescribe()+" as instanced in: "+source);
HierarchyEnumerator.enumerateCell(missingCell, VarContext.globalContext,
new Visitor(this), getShortResistors());
}
}
}
return true;
}
/**
* Get the Verilog-style name for a cell.
* @param cell the cell to name.
* @return the name of the cell.
*/
private String getVerilogName(Cell cell) {
// this should mirror the code in parameterizedName(), minus the parameter stuff
String uniqueCellName = getUniqueCellName(cell);
if (uniqueCellName != null) return uniqueCellName;
// otherwise, use old code
String safeCellName = getSafeCellName(cell.getName());
if (!safeCellName.startsWith("_")) safeCellName = "__" + safeCellName;
return cell.getLibrary().getName() + safeCellName;
}
/**
* Find a cell corresponding to the Verilog-style name
* of a cell. See
* {@link Verilog#getVerilogName(com.sun.electric.database.hierarchy.Cell)}.
* @param verilogName the Verilog-style name of the cell
* @param preferredView the preferred cell view. Schematic if null.
* @return the cell, or null if not found
*/
public static Cell findCell(String verilogName, View preferredView) {
String [] parts = verilogName.split("__");
if (parts.length != 2) {
//System.out.println("Invalid Verilog-style module name: "+verilogName);
return null;
}
Library lib = Library.findLibrary(parts[0]);
if (lib == null) {
System.out.println("Cannot find library "+parts[0]+" for Verilog-style module name: "+verilogName);
return null;
}
if (preferredView == null) preferredView = View.SCHEMATIC;
Cell cell = lib.findNodeProto(parts[1]);
if (cell == null) {
System.out.println("Cannot find Cell "+parts[1]+" in Library "+parts[0]+" for Verilog-style module name: "+verilogName);
return null;
}
Cell preferred = cell.otherView(preferredView);
if (preferred != null) return preferred;
preferred = cell.getCellGroup().getMainSchematics();
if (preferred != null) return preferred;
return cell;
}
private static void accumulatePortConnectivity(Map<Network,List<Export>> instancePortsOnNet, Network net, Export ex)
{
List<Export> list = instancePortsOnNet.get(net);
if (list == null) {
list = new ArrayList<Export>();
instancePortsOnNet.put(net, list);
}
if (!list.contains(ex)) list.add(ex);
}
}
| true | true | protected void writeCellTopology(Cell cell, CellNetInfo cni, VarContext context, Topology.MyCellInfo info)
{
if (cell == topCell) {
// gather all global signal names
Netlist netList = cni.getNetList();
Global.Set globals = netList.getGlobals();
int globalSize = globals.size();
// see if any globals besides power and ground to write
List<Global> globalsToWrite = new ArrayList<Global>();
for (int i=0; i<globalSize; i++) {
Global global = globals.get(i);
if (global == Global.power || global == Global.ground) continue;
globalsToWrite.add(global);
}
if (globalsToWrite.size() > 0)
{
printWriter.println("\nmodule glbl();");
for(int i=0; i<globalsToWrite.size(); i++)
{
Global global = globalsToWrite.get(i);
if (Simulation.getVerilogUseTrireg())
{
printWriter.println(" trireg " + global.getName() + ";");
} else
{
printWriter.println(" wire " + global.getName() + ";");
}
}
printWriter.println("endmodule");
}
}
// prepare arcs to store implicit inverters
Map<ArcInst,Integer> implicitHeadInverters = new HashMap<ArcInst,Integer>();
Map<ArcInst,Integer> implicitTailInverters = new HashMap<ArcInst,Integer>();
int impInvCount = 0;
for(Iterator<ArcInst> it = cell.getArcs(); it.hasNext(); )
{
ArcInst ai = it.next();
for(int e=0; e<2; e++)
{
if (!ai.isNegated(e)) continue;
PortInst pi = ai.getPortInst(e);
NodeInst ni = pi.getNodeInst();
if (ni.getProto() == Schematics.tech().bufferNode || ni.getProto() == Schematics.tech().andNode ||
ni.getProto() == Schematics.tech().orNode || ni.getProto() == Schematics.tech().xorNode)
{
if (Simulation.getVerilogUseAssign()) continue;
if (pi.getPortProto().getName().equals("y")) continue;
}
// must create implicit inverter here
if (e == ArcInst.HEADEND) implicitHeadInverters.put(ai, new Integer(impInvCount)); else
implicitTailInverters.put(ai, new Integer(impInvCount));
if (ai.getProto() != Schematics.tech().bus_arc) impInvCount++; else
{
int wid = cni.getNetList().getBusWidth(ai);
impInvCount += wid;
}
}
}
// gather networks in the cell
Netlist netList = cni.getNetList();
// add in any user-specified defines
includeTypedCode(cell, VERILOG_EXTERNAL_CODE_KEY, "external code");
// write the module header
printWriter.println();
StringBuffer sb = new StringBuffer();
sb.append("module " + cni.getParameterizedName() + "(");
boolean first = true;
for(Iterator<CellAggregateSignal> it = cni.getCellAggregateSignals(); it.hasNext(); )
{
CellAggregateSignal cas = it.next();
if (cas.getExport() == null) continue;
if (cas.getLowIndex() <= cas.getHighIndex() && cas.getIndices() != null)
{
// fragmented bus: write individual signals
int [] indices = cas.getIndices();
for(int i=0; i<indices.length; i++)
{
int ind = i;
if (cas.isDescending()) ind = indices.length - i - 1;
if (!first) sb.append(",");
sb.append(" \\" + cas.getName() + "[" + indices[ind] + "] ");
first = false;
}
} else
{
// simple name, add to module header
if (!first) sb.append(", ");
sb.append(cas.getName());
first = false;
}
}
sb.append(");\n");
writeWidthLimited(sb.toString());
definedModules.put(cni.getParameterizedName(), "Cell "+cell.libDescribe());
// add in any user-specified parameters
includeTypedCode(cell, VERILOG_PARAMETER_KEY, "parameters");
// look for "wire/trireg" overrides
for(Iterator<ArcInst> it = cell.getArcs(); it.hasNext(); )
{
ArcInst ai = it.next();
Variable var = ai.getVar(WIRE_TYPE_KEY);
if (var == null) continue;
String wireType = var.getObject().toString();
int overrideValue = 0;
if (wireType.equalsIgnoreCase("wire")) overrideValue = 1; else
if (wireType.equalsIgnoreCase("trireg")) overrideValue = 2;
int busWidth = netList.getBusWidth(ai);
for(int i=0; i<busWidth; i++)
{
Network net = netList.getNetwork(ai, i);
CellSignal cs = cni.getCellSignal(net);
if (cs == null) continue;
cs.getAggregateSignal().setFlags(overrideValue);
}
}
// write description of formal parameters to module
first = true;
for(Iterator<CellAggregateSignal> it = cni.getCellAggregateSignals(); it.hasNext(); )
{
CellAggregateSignal cas = it.next();
Export pp = cas.getExport();
if (pp == null) continue;
String portType = "input";
if (pp.getCharacteristic() == PortCharacteristic.OUT)
portType = "output";
else if (pp.getCharacteristic() == PortCharacteristic.BIDIR)
portType = "inout";
sb = new StringBuffer();
sb.append(" " + portType);
if (cas.getLowIndex() > cas.getHighIndex())
{
sb.append(" " + cas.getName() + ";");
} else
{
int [] indices = cas.getIndices();
if (indices != null)
{
for(int i=0; i<indices.length; i++)
{
int ind = i;
if (cas.isDescending()) ind = indices.length - i - 1;
if (i != 0) sb.append(",");
sb.append(" \\" + cas.getName() + "[" + indices[ind] + "] ");
}
sb.append(";");
} else
{
int low = cas.getLowIndex(), high = cas.getHighIndex();
if (cas.isDescending())
{
low = cas.getHighIndex(); high = cas.getLowIndex();
}
sb.append(" [" + low + ":" + high + "] " + cas.getName() + ";");
}
}
if (cas.getFlags() != 0)
{
if (cas.getFlags() == 1) sb.append(" wire"); else
sb.append(" trireg");
sb.append(" " + cas.getName() + ";");
}
sb.append("\n");
writeWidthLimited(sb.toString());
first = false;
}
if (!first) printWriter.println();
// if writing standard cell netlist, do not netlist contents of standard cells
if (Simulation.getVerilogStopAtStandardCells())
{
if (SCLibraryGen.isStandardCell(cell)) {
printWriter.println("endmodule /* " + cni.getParameterizedName() + " */");
return;
}
}
// describe power and ground nets
if (cni.getPowerNet() != null) printWriter.println(" supply1 vdd;");
if (cni.getGroundNet() != null) printWriter.println(" supply0 gnd;");
// determine whether to use "wire" or "trireg" for networks
String wireType = "wire";
if (Simulation.getVerilogUseTrireg()) wireType = "trireg";
// write "wire/trireg" declarations for internal single-wide signals
int localWires = 0;
for(int wt=0; wt<2; wt++)
{
first = true;
for(Iterator<CellAggregateSignal> it = cni.getCellAggregateSignals(); it.hasNext(); )
{
CellAggregateSignal cas = it.next();
if (cas.getExport() != null) continue;
if (cas.isSupply()) continue;
if (cas.getLowIndex() <= cas.getHighIndex()) continue;
if (cas.isGlobal()) continue;
String impSigName = wireType;
if (cas.getFlags() != 0)
{
if (cas.getFlags() == 1) impSigName = "wire"; else
impSigName = "trireg";
}
if ((wt == 0) ^ !wireType.equals(impSigName))
{
if (first)
{
initDeclaration(" " + impSigName);
}
addDeclaration(cas.getName());
localWires++;
first = false;
}
}
if (!first) termDeclaration();
}
// write "wire/trireg" declarations for internal busses
for(Iterator<CellAggregateSignal> it = cni.getCellAggregateSignals(); it.hasNext(); )
{
CellAggregateSignal cas = it.next();
if (cas.getExport() != null) continue;
if (cas.isSupply()) continue;
if (cas.getLowIndex() > cas.getHighIndex()) continue;
if (cas.isGlobal()) continue;
int [] indices = cas.getIndices();
if (indices != null)
{
for(int i=0; i<indices.length; i++)
{
int ind = i;
if (cas.isDescending()) ind = indices.length - i - 1;
printWriter.println(" " + wireType + " \\" + cas.getName() + "[" + indices[ind] + "] ;");
}
} else
{
if (cas.isDescending())
{
printWriter.println(" " + wireType + " [" + cas.getHighIndex() + ":" + cas.getLowIndex() + "] " + cas.getName() + ";");
} else
{
printWriter.println(" " + wireType + " [" + cas.getLowIndex() + ":" + cas.getHighIndex() + "] " + cas.getName() + ";");
}
}
localWires++;
}
if (localWires != 0) printWriter.println();
// add "wire" declarations for implicit inverters
if (impInvCount > 0)
{
initDeclaration(" " + wireType);
for(int i=0; i<impInvCount; i++)
{
String impsigname = IMPLICITINVERTERSIGNAME + i;
addDeclaration(impsigname);
}
termDeclaration();
}
// add in any user-specified declarations and code
if (!Simulation.getVerilogStopAtStandardCells()) {
// STA does not like general verilog code (like and #delay out ina inb etc)
first = includeTypedCode(cell, VERILOG_DECLARATION_KEY, "declarations");
first |= includeTypedCode(cell, VERILOG_CODE_KEY, "code");
if (!first)
printWriter.println(" /* automatically generated Verilog */");
}
// accumulate port connectivity information for port directional consistency check
Map<Network,List<Export>> instancePortsOnNet = new HashMap<Network,List<Export>>();
// look at every node in this cell
for(Iterator<Nodable> nIt = netList.getNodables(); nIt.hasNext(); )
{
Nodable no = nIt.next();
NodeProto niProto = no.getProto();
// not interested in passive nodes (ports electrically connected)
PrimitiveNode.Function nodeType = PrimitiveNode.Function.UNKNOWN;
if (!no.isCellInstance())
{
NodeInst ni = (NodeInst)no;
Iterator<PortInst> pIt = ni.getPortInsts();
if (pIt.hasNext())
{
boolean allConnected = true;
PortInst firstPi = pIt.next();
Network firstNet = netList.getNetwork(firstPi);
for( ; pIt.hasNext(); )
{
PortInst pi = pIt.next();
Network thisNet = netList.getNetwork(pi);
if (thisNet != firstNet) { allConnected = false; break; }
}
if (allConnected) continue;
}
nodeType = ni.getFunction();
// special case: verilog should ignore R L C etc.
if (nodeType.isResistor() || // == PrimitiveNode.Function.RESIST ||
nodeType.isCapacitor() || // == PrimitiveNode.Function.CAPAC || nodeType == PrimitiveNode.Function.ECAPAC ||
nodeType == PrimitiveNode.Function.INDUCT ||
nodeType == PrimitiveNode.Function.DIODE || nodeType == PrimitiveNode.Function.DIODEZ)
continue;
}
// look for a Verilog template on the prototype
if (no.isCellInstance())
{
// if writing standard cell netlist, do not write out cells that
// do not contain standard cells
if (Simulation.getVerilogStopAtStandardCells())
{
if (!standardCells.containsStandardCell((Cell)niProto) &&
!SCLibraryGen.isStandardCell((Cell)niProto)) continue;
}
Variable varTemplate = ((Cell)niProto).getVar(VERILOG_TEMPLATE_KEY);
if (varTemplate != null)
{
if (varTemplate.getObject() instanceof String []) {
String [] lines = (String [])varTemplate.getObject();
writeWidthLimited(" /* begin Verilog_template for "+no.getProto().describe(false)+"*/\n");
for (int i=0; i<lines.length; i++) {
writeTemplate(lines[i], no, cni, context);
}
writeWidthLimited(" // end Verilog_template\n");
} else {
// special case: do not write out string "//"
if (!((String)varTemplate.getObject()).equals("//")) {
writeWidthLimited(" /* begin Verilog_template for "+no.getProto().describe(false)+"*/\n");
writeTemplate((String)varTemplate.getObject(), no, cni, context);
writeWidthLimited(" // end Verilog_template\n");
}
}
continue;
}
}
// look for a Verilog defparam template on the prototype
// Defparam templates provide a mechanism for prepending per instance
// parameters on verilog declarations
if (no.isCellInstance())
{
Variable varDefparamTemplate = ((Cell)niProto).getVar(VERILOG_DEFPARAM_KEY);
if (varDefparamTemplate != null)
{
if (varDefparamTemplate.getObject() instanceof String []) {
String [] lines = (String [])varDefparamTemplate.getObject();
// writeWidthLimited(" /* begin Verilog_defparam for "+no.getProto().describe(false)+" */\n");
boolean firstDefparam = true;
for (int i=0; i<lines.length; i++) {
//StringBuffer infstr = new StringBuffer();
String defparam = new String();
defparam = writeDefparam(lines[i], no, context);
if (defparam.length() != 0)
{
if (firstDefparam)
{
writeWidthLimited(" /* begin Verilog_defparam for "+no.getProto().describe(false)+" */\n");
firstDefparam = false;
}
writeWidthLimited(defparam);
}
}
if (!firstDefparam)
{
writeWidthLimited(" // end Verilog_defparam\n");
}
} else
{
// special case: do not write out string "//"
if (!((String)varDefparamTemplate.getObject()).equals("//"))
{
String defparam = new String();
defparam = writeDefparam((String)varDefparamTemplate.getObject(), no, context);
if (defparam.length() != 0)
{
writeWidthLimited(" /* begin Verilog_defparam for "+no.getProto().describe(false)+"*/\n");
writeWidthLimited(defparam);
writeWidthLimited(" // end Verilog_defparam\n");
}
}
}
}
}
// use "assign" statement if requested
if (Simulation.getVerilogUseAssign())
{
if (nodeType == PrimitiveNode.Function.GATEAND || nodeType == PrimitiveNode.Function.GATEOR ||
nodeType == PrimitiveNode.Function.GATEXOR || nodeType == PrimitiveNode.Function.BUFFER)
{
// assign possible: determine operator
String op = "";
if (nodeType == PrimitiveNode.Function.GATEAND) op = " & "; else
if (nodeType == PrimitiveNode.Function.GATEOR) op = " | "; else
if (nodeType == PrimitiveNode.Function.GATEXOR) op = " ^ ";
// write a line describing this signal
StringBuffer infstr = new StringBuffer();
boolean wholeNegated = false;
first = true;
NodeInst ni = (NodeInst)no;
for(int i=0; i<2; i++)
{
for(Iterator<Connection> cIt = ni.getConnections(); cIt.hasNext(); )
{
Connection con = cIt.next();
PortInst pi = con.getPortInst();
if (i == 0)
{
if (!pi.getPortProto().getName().equals("y")) continue;
} else
{
if (!pi.getPortProto().getName().equals("a")) continue;
}
// determine the network name at this port
ArcInst ai = con.getArc();
Network net = netList.getNetwork(ai, 0);
CellSignal cs = cni.getCellSignal(net);
String sigName = getSignalName(cs);
// see if this end is negated
boolean isNegated = false;
if (ai.isTailNegated() || ai.isHeadNegated()) isNegated = true;
// write the port name
if (i == 0)
{
// got the output port: do the left-side of the "assign"
infstr.append("assign " + sigName + " = ");
if (isNegated)
{
infstr.append("~(");
wholeNegated = true;
}
break;
}
if (!first)
infstr.append(op);
first = false;
if (isNegated) infstr.append("~");
infstr.append(sigName);
}
}
if (wholeNegated)
infstr.append(")");
infstr.append(";\n");
writeWidthLimited(infstr.toString());
continue;
}
}
// get the name of the node
int implicitPorts = 0;
boolean dropBias = false;
String nodeName = "";
if (no.isCellInstance())
{
// make sure there are contents for this cell instance
if (((Cell)niProto).isIcon()) continue;
nodeName = parameterizedName(no, context);
// cells defined as "primitives" in Verilog View must have implicit port ordering
if (definedPrimitives.containsKey(niProto)) {
implicitPorts = 3;
}
} else
{
// convert 4-port transistors to 3-port
if (nodeType == PrimitiveNode.Function.TRA4NMOS)
{
nodeType = PrimitiveNode.Function.TRANMOS; dropBias = true;
} else if (nodeType == PrimitiveNode.Function.TRA4PMOS)
{
nodeType = PrimitiveNode.Function.TRAPMOS; dropBias = true;
}
if (nodeType == PrimitiveNode.Function.TRANMOS)
{
implicitPorts = 2;
nodeName = "tranif1";
Variable varWeakNode = ((NodeInst)no).getVar(Simulation.WEAK_NODE_KEY);
if (varWeakNode != null) nodeName = "rtranif1";
} else if (nodeType == PrimitiveNode.Function.TRAPMOS)
{
implicitPorts = 2;
nodeName = "tranif0";
Variable varWeakNode = ((NodeInst)no).getVar(Simulation.WEAK_NODE_KEY);
if (varWeakNode != null) nodeName = "rtranif0";
} else if (nodeType == PrimitiveNode.Function.GATEAND)
{
implicitPorts = 1;
nodeName = chooseNodeName((NodeInst)no, "and", "nand");
} else if (nodeType == PrimitiveNode.Function.GATEOR)
{
implicitPorts = 1;
nodeName = chooseNodeName((NodeInst)no, "or", "nor");
} else if (nodeType == PrimitiveNode.Function.GATEXOR)
{
implicitPorts = 1;
nodeName = chooseNodeName((NodeInst)no, "xor", "xnor");
} else if (nodeType == PrimitiveNode.Function.BUFFER)
{
implicitPorts = 1;
nodeName = chooseNodeName((NodeInst)no, "buf", "not");
}
}
if (nodeName.length() == 0) continue;
// write the type of the node
StringBuffer infstr = new StringBuffer();
infstr.append(" " + nodeName + " " + nameNoIndices(no.getName()) + "(");
// write the rest of the ports
first = true;
NodeInst ni = null;
switch (implicitPorts)
{
case 0: // explicit ports (for cell instances)
CellNetInfo subCni = getCellNetInfo(nodeName);
for(Iterator<CellAggregateSignal> sIt = subCni.getCellAggregateSignals(); sIt.hasNext(); )
{
CellAggregateSignal cas = sIt.next();
// ignore networks that aren't exported
PortProto pp = cas.getExport();
if (pp == null) continue;
if (first) first = false; else
infstr.append(", ");
if (cas.getLowIndex() > cas.getHighIndex())
{
// single signal
infstr.append("." + cas.getName() + "(");
Network net = netList.getNetwork(no, pp, cas.getExportIndex());
CellSignal cs = cni.getCellSignal(net);
infstr.append(getSignalName(cs));
infstr.append(")");
accumulatePortConnectivity(instancePortsOnNet, net, (Export)pp);
} else
{
int [] indices = cas.getIndices();
if (indices != null)
{
// broken bus internally, write signals individually
for(int i=0; i<indices.length; i++)
{
CellSignal cInnerSig = cas.getSignal(i);
Network net = netList.getNetwork(no, cas.getExport(), cInnerSig.getExportIndex());
CellSignal outerSignal = cni.getCellSignal(net);
accumulatePortConnectivity(instancePortsOnNet, net, (Export)pp);
int ind = i;
if (cas.isDescending()) ind = indices.length - i - 1;
if (i > 0) infstr.append(", ");
infstr.append(".\\" + cas.getName() + "[" + indices[ind] + "] (");
infstr.append(getSignalName(outerSignal));
infstr.append(")");
}
} else
{
// simple bus, write signals
int total = cas.getNumSignals();
CellSignal [] outerSignalList = new CellSignal[total];
for(int j=0; j<total; j++)
{
CellSignal cInnerSig = cas.getSignal(j);
Network net = netList.getNetwork(no, cas.getExport(), cInnerSig.getExportIndex());
outerSignalList[j] = cni.getCellSignal(net);
accumulatePortConnectivity(instancePortsOnNet, net, (Export)pp);
}
writeBus(outerSignalList, total, cas.isDescending(),
cas.getName(), cni.getPowerNet(), cni.getGroundNet(), infstr);
}
}
}
infstr.append(");");
break;
case 1: // and/or gate: write ports in the proper order
ni = (NodeInst)no;
for(int i=0; i<2; i++)
{
for(Iterator<Connection> cIt = ni.getConnections(); cIt.hasNext(); )
{
Connection con = cIt.next();
PortInst pi = con.getPortInst();
if (i == 0)
{
if (!pi.getPortProto().getName().equals("y")) continue;
} else
{
if (!pi.getPortProto().getName().equals("a")) continue;
}
if (first) first = false; else
infstr.append(", ");
ArcInst ai = con.getArc();
Network net = netList.getNetwork(ai, 0);
CellSignal cs = cni.getCellSignal(net);
if (cs == null) continue;
String sigName = getSignalName(cs);
if (i != 0 && con.isNegated())
{
// this input is negated: write the implicit inverter
Integer invIndex;
if (con.getEndIndex() == ArcInst.HEADEND) invIndex = implicitHeadInverters.get(ai); else
invIndex = implicitTailInverters.get(ai);
if (invIndex != null)
{
String invSigName = IMPLICITINVERTERSIGNAME + invIndex.intValue();
printWriter.println(" inv " + IMPLICITINVERTERNODENAME +
invIndex.intValue() + " (" + invSigName + ", " + sigName + ");");
sigName = invSigName;
}
}
infstr.append(sigName);
}
}
infstr.append(");");
break;
case 2: // transistors: write ports in the proper order: s/d/g
ni = (NodeInst)no;
Network gateNet = netList.getNetwork(ni.getTransistorGatePort());
for(int i=0; i<2; i++)
{
boolean didGate = false;
for(Iterator<PortInst> pIt = ni.getPortInsts(); pIt.hasNext(); )
{
PortInst pi = pIt.next();
Network net = netList.getNetwork(pi);
if (dropBias && pi.getPortProto().getName().equals("b")) continue;
if (i == 0)
{
if (net == gateNet) continue;
} else
{
if (net != gateNet) continue;
if (didGate) continue;
didGate = true;
}
if (first) first = false; else
infstr.append(", ");
CellSignal cs = cni.getCellSignal(net);
String sigName = getSignalName(cs);
infstr.append(sigName);
}
}
infstr.append(");");
break;
case 3: // implicit ports ordering for cells defined as primitives in Verilog View
ni = no.getNodeInst();
VerilogData.VerilogModule module = definedPrimitives.get(niProto);
if (module == null) break;
System.out.print(cell.getName()+" ports: ");
for (VerilogData.VerilogPort port : module.getPorts()) {
List<String> portnames = port.getPinNames(true);
if (portnames.size() == 0) {
// continue
} else if (portnames.size() > 1) {
// Bill thinks bussed ports are not allowed for primitives
System.out.println("Error: bussed ports not allowed on Verilog primitives: "+niProto.getName());
} else {
String portname = portnames.get(0);
PortInst pi = ni.findPortInst(portname);
Network net = netList.getNetwork(no, pi.getProtoEquivalent(), 0);
CellSignal cs = cni.getCellSignal(net);
String sigName = getSignalName(cs);
if (first) first = false; else
infstr.append(", ");
infstr.append(sigName);
System.out.print(portname+" ");
}
}
System.out.println();
infstr.append(");");
break;
}
infstr.append("\n");
writeWidthLimited(infstr.toString());
}
printWriter.println("endmodule /* " + cni.getParameterizedName() + " */");
// check export direction consistency (inconsistent directions can cause opens in some tools)
for (Iterator<Export> it = cell.getExports(); it.hasNext(); ) {
Export ex = it.next();
PortCharacteristic type = ex.getCharacteristic();
if (type == PortCharacteristic.BIDIR) continue; // whatever it is connect to is fine
for (int i=0; i<ex.getNameKey().busWidth(); i++) {
Network net = netList.getNetwork(ex, i);
List<Export> subports = instancePortsOnNet.get(net);
if (subports == null) continue;
for (Export subex : subports) {
PortCharacteristic subtype = subex.getCharacteristic();
if (type != subtype) {
System.out.println("Warning: Port Direction Inconsistency in cell "+cell.describe(false)+
" between export "+ex.getNameKey().subname(i)+"["+type+"] and instance port "+
subex.getParent().noLibDescribe()+" - "+subex.getName()+"["+subtype+"]");
}
}
}
}
}
| protected void writeCellTopology(Cell cell, CellNetInfo cni, VarContext context, Topology.MyCellInfo info)
{
if (cell == topCell) {
// gather all global signal names
Netlist netList = cni.getNetList();
Global.Set globals = netList.getGlobals();
int globalSize = globals.size();
// see if any globals besides power and ground to write
List<Global> globalsToWrite = new ArrayList<Global>();
for (int i=0; i<globalSize; i++) {
Global global = globals.get(i);
if (global == Global.power || global == Global.ground) continue;
globalsToWrite.add(global);
}
if (globalsToWrite.size() > 0)
{
printWriter.println("\nmodule glbl();");
for(int i=0; i<globalsToWrite.size(); i++)
{
Global global = globalsToWrite.get(i);
if (Simulation.getVerilogUseTrireg())
{
printWriter.println(" trireg " + global.getName() + ";");
} else
{
printWriter.println(" wire " + global.getName() + ";");
}
}
printWriter.println("endmodule");
}
}
// prepare arcs to store implicit inverters
Map<ArcInst,Integer> implicitHeadInverters = new HashMap<ArcInst,Integer>();
Map<ArcInst,Integer> implicitTailInverters = new HashMap<ArcInst,Integer>();
int impInvCount = 0;
for(Iterator<ArcInst> it = cell.getArcs(); it.hasNext(); )
{
ArcInst ai = it.next();
for(int e=0; e<2; e++)
{
if (!ai.isNegated(e)) continue;
PortInst pi = ai.getPortInst(e);
NodeInst ni = pi.getNodeInst();
if (ni.getProto() == Schematics.tech().bufferNode || ni.getProto() == Schematics.tech().andNode ||
ni.getProto() == Schematics.tech().orNode || ni.getProto() == Schematics.tech().xorNode)
{
if (Simulation.getVerilogUseAssign()) continue;
if (pi.getPortProto().getName().equals("y")) continue;
}
// must create implicit inverter here
if (e == ArcInst.HEADEND) implicitHeadInverters.put(ai, new Integer(impInvCount)); else
implicitTailInverters.put(ai, new Integer(impInvCount));
if (ai.getProto() != Schematics.tech().bus_arc) impInvCount++; else
{
int wid = cni.getNetList().getBusWidth(ai);
impInvCount += wid;
}
}
}
// gather networks in the cell
Netlist netList = cni.getNetList();
// add in any user-specified defines
includeTypedCode(cell, VERILOG_EXTERNAL_CODE_KEY, "external code");
// write the module header
printWriter.println();
StringBuffer sb = new StringBuffer();
sb.append("module " + cni.getParameterizedName() + "(");
boolean first = true;
for(Iterator<CellAggregateSignal> it = cni.getCellAggregateSignals(); it.hasNext(); )
{
CellAggregateSignal cas = it.next();
if (cas.getExport() == null) continue;
if (cas.getLowIndex() <= cas.getHighIndex() && cas.getIndices() != null)
{
// fragmented bus: write individual signals
int [] indices = cas.getIndices();
for(int i=0; i<indices.length; i++)
{
int ind = i;
if (cas.isDescending()) ind = indices.length - i - 1;
if (!first) sb.append(",");
sb.append(" \\" + cas.getName() + "[" + indices[ind] + "] ");
first = false;
}
} else
{
// simple name, add to module header
if (!first) sb.append(", ");
sb.append(cas.getName());
first = false;
}
}
sb.append(");\n");
writeWidthLimited(sb.toString());
definedModules.put(cni.getParameterizedName(), "Cell "+cell.libDescribe());
// add in any user-specified parameters
includeTypedCode(cell, VERILOG_PARAMETER_KEY, "parameters");
// look for "wire/trireg" overrides
for(Iterator<ArcInst> it = cell.getArcs(); it.hasNext(); )
{
ArcInst ai = it.next();
Variable var = ai.getVar(WIRE_TYPE_KEY);
if (var == null) continue;
String wireType = var.getObject().toString();
int overrideValue = 0;
if (wireType.equalsIgnoreCase("wire")) overrideValue = 1; else
if (wireType.equalsIgnoreCase("trireg")) overrideValue = 2;
int busWidth = netList.getBusWidth(ai);
for(int i=0; i<busWidth; i++)
{
Network net = netList.getNetwork(ai, i);
CellSignal cs = cni.getCellSignal(net);
if (cs == null) continue;
cs.getAggregateSignal().setFlags(overrideValue);
}
}
// write description of formal parameters to module
first = true;
for(Iterator<CellAggregateSignal> it = cni.getCellAggregateSignals(); it.hasNext(); )
{
CellAggregateSignal cas = it.next();
Export pp = cas.getExport();
if (pp == null) continue;
String portType = "input";
if (pp.getCharacteristic() == PortCharacteristic.OUT)
portType = "output";
else if (pp.getCharacteristic() == PortCharacteristic.BIDIR)
portType = "inout";
sb = new StringBuffer();
sb.append(" " + portType);
if (cas.getLowIndex() > cas.getHighIndex())
{
sb.append(" " + cas.getName() + ";");
} else
{
int [] indices = cas.getIndices();
if (indices != null)
{
for(int i=0; i<indices.length; i++)
{
int ind = i;
if (cas.isDescending()) ind = indices.length - i - 1;
if (i != 0) sb.append(",");
sb.append(" \\" + cas.getName() + "[" + indices[ind] + "] ");
}
sb.append(";");
} else
{
int low = cas.getLowIndex(), high = cas.getHighIndex();
if (cas.isDescending())
{
low = cas.getHighIndex(); high = cas.getLowIndex();
}
sb.append(" [" + low + ":" + high + "] " + cas.getName() + ";");
}
}
if (cas.getFlags() != 0)
{
if (cas.getFlags() == 1) sb.append(" wire"); else
sb.append(" trireg");
sb.append(" " + cas.getName() + ";");
}
sb.append("\n");
writeWidthLimited(sb.toString());
first = false;
}
if (!first) printWriter.println();
// if writing standard cell netlist, do not netlist contents of standard cells
if (Simulation.getVerilogStopAtStandardCells())
{
if (SCLibraryGen.isStandardCell(cell)) {
printWriter.println("endmodule /* " + cni.getParameterizedName() + " */");
return;
}
}
// describe power and ground nets
if (cni.getPowerNet() != null) printWriter.println(" supply1 vdd;");
if (cni.getGroundNet() != null) printWriter.println(" supply0 gnd;");
// determine whether to use "wire" or "trireg" for networks
String wireType = "wire";
if (Simulation.getVerilogUseTrireg()) wireType = "trireg";
// write "wire/trireg" declarations for internal single-wide signals
int localWires = 0;
for(int wt=0; wt<2; wt++)
{
first = true;
for(Iterator<CellAggregateSignal> it = cni.getCellAggregateSignals(); it.hasNext(); )
{
CellAggregateSignal cas = it.next();
if (cas.getExport() != null) continue;
if (cas.isSupply()) continue;
if (cas.getLowIndex() <= cas.getHighIndex()) continue;
if (cas.isGlobal()) continue;
String impSigName = wireType;
if (cas.getFlags() != 0)
{
if (cas.getFlags() == 1) impSigName = "wire"; else
impSigName = "trireg";
}
if ((wt == 0) ^ !wireType.equals(impSigName))
{
if (first)
{
initDeclaration(" " + impSigName);
}
addDeclaration(cas.getName());
localWires++;
first = false;
}
}
if (!first) termDeclaration();
}
// write "wire/trireg" declarations for internal busses
for(Iterator<CellAggregateSignal> it = cni.getCellAggregateSignals(); it.hasNext(); )
{
CellAggregateSignal cas = it.next();
if (cas.getExport() != null) continue;
if (cas.isSupply()) continue;
if (cas.getLowIndex() > cas.getHighIndex()) continue;
if (cas.isGlobal()) continue;
int [] indices = cas.getIndices();
if (indices != null)
{
for(int i=0; i<indices.length; i++)
{
int ind = i;
if (cas.isDescending()) ind = indices.length - i - 1;
printWriter.println(" " + wireType + " \\" + cas.getName() + "[" + indices[ind] + "] ;");
}
} else
{
if (cas.isDescending())
{
printWriter.println(" " + wireType + " [" + cas.getHighIndex() + ":" + cas.getLowIndex() + "] " + cas.getName() + ";");
} else
{
printWriter.println(" " + wireType + " [" + cas.getLowIndex() + ":" + cas.getHighIndex() + "] " + cas.getName() + ";");
}
}
localWires++;
}
if (localWires != 0) printWriter.println();
// add "wire" declarations for implicit inverters
if (impInvCount > 0)
{
initDeclaration(" " + wireType);
for(int i=0; i<impInvCount; i++)
{
String impsigname = IMPLICITINVERTERSIGNAME + i;
addDeclaration(impsigname);
}
termDeclaration();
}
// add in any user-specified declarations and code
if (!Simulation.getVerilogStopAtStandardCells()) {
// STA does not like general verilog code (like and #delay out ina inb etc)
first = includeTypedCode(cell, VERILOG_DECLARATION_KEY, "declarations");
first |= includeTypedCode(cell, VERILOG_CODE_KEY, "code");
if (!first)
printWriter.println(" /* automatically generated Verilog */");
}
// accumulate port connectivity information for port directional consistency check
Map<Network,List<Export>> instancePortsOnNet = new HashMap<Network,List<Export>>();
// look at every node in this cell
for(Iterator<Nodable> nIt = netList.getNodables(); nIt.hasNext(); )
{
Nodable no = nIt.next();
NodeProto niProto = no.getProto();
// not interested in passive nodes (ports electrically connected)
PrimitiveNode.Function nodeType = PrimitiveNode.Function.UNKNOWN;
if (!no.isCellInstance())
{
NodeInst ni = (NodeInst)no;
Iterator<PortInst> pIt = ni.getPortInsts();
if (pIt.hasNext())
{
boolean allConnected = true;
PortInst firstPi = pIt.next();
Network firstNet = netList.getNetwork(firstPi);
for( ; pIt.hasNext(); )
{
PortInst pi = pIt.next();
Network thisNet = netList.getNetwork(pi);
if (thisNet != firstNet) { allConnected = false; break; }
}
if (allConnected) continue;
}
nodeType = ni.getFunction();
// special case: verilog should ignore R L C etc.
if (nodeType.isResistor() || // == PrimitiveNode.Function.RESIST ||
nodeType.isCapacitor() || // == PrimitiveNode.Function.CAPAC || nodeType == PrimitiveNode.Function.ECAPAC ||
nodeType == PrimitiveNode.Function.INDUCT ||
nodeType == PrimitiveNode.Function.DIODE || nodeType == PrimitiveNode.Function.DIODEZ)
continue;
}
// look for a Verilog template on the prototype
if (no.isCellInstance())
{
// if writing standard cell netlist, do not write out cells that
// do not contain standard cells
if (Simulation.getVerilogStopAtStandardCells())
{
if (!standardCells.containsStandardCell((Cell)niProto) &&
!SCLibraryGen.isStandardCell((Cell)niProto)) continue;
}
Variable varTemplate = ((Cell)niProto).getVar(VERILOG_TEMPLATE_KEY);
if (varTemplate != null)
{
if (varTemplate.getObject() instanceof String []) {
String [] lines = (String [])varTemplate.getObject();
writeWidthLimited(" /* begin Verilog_template for "+no.getProto().describe(false)+"*/\n");
for (int i=0; i<lines.length; i++) {
writeTemplate(lines[i], no, cni, context);
}
writeWidthLimited(" // end Verilog_template\n");
} else {
// special case: do not write out string "//"
if (!((String)varTemplate.getObject()).equals("//")) {
writeWidthLimited(" /* begin Verilog_template for "+no.getProto().describe(false)+"*/\n");
writeTemplate((String)varTemplate.getObject(), no, cni, context);
writeWidthLimited(" // end Verilog_template\n");
}
}
continue;
}
}
// look for a Verilog defparam template on the prototype
// Defparam templates provide a mechanism for prepending per instance
// parameters on verilog declarations
if (no.isCellInstance())
{
Variable varDefparamTemplate = ((Cell)niProto).getVar(VERILOG_DEFPARAM_KEY);
if (varDefparamTemplate != null)
{
if (varDefparamTemplate.getObject() instanceof String []) {
String [] lines = (String [])varDefparamTemplate.getObject();
// writeWidthLimited(" /* begin Verilog_defparam for "+no.getProto().describe(false)+" */\n");
boolean firstDefparam = true;
for (int i=0; i<lines.length; i++) {
//StringBuffer infstr = new StringBuffer();
String defparam = new String();
defparam = writeDefparam(lines[i], no, context);
if (defparam.length() != 0)
{
if (firstDefparam)
{
writeWidthLimited(" /* begin Verilog_defparam for "+no.getProto().describe(false)+" */\n");
firstDefparam = false;
}
writeWidthLimited(defparam);
}
}
if (!firstDefparam)
{
writeWidthLimited(" // end Verilog_defparam\n");
}
} else
{
// special case: do not write out string "//"
if (!((String)varDefparamTemplate.getObject()).equals("//"))
{
String defparam = new String();
defparam = writeDefparam((String)varDefparamTemplate.getObject(), no, context);
if (defparam.length() != 0)
{
writeWidthLimited(" /* begin Verilog_defparam for "+no.getProto().describe(false)+"*/\n");
writeWidthLimited(defparam);
writeWidthLimited(" // end Verilog_defparam\n");
}
}
}
}
}
// use "assign" statement if requested
if (Simulation.getVerilogUseAssign())
{
if (nodeType == PrimitiveNode.Function.GATEAND || nodeType == PrimitiveNode.Function.GATEOR ||
nodeType == PrimitiveNode.Function.GATEXOR || nodeType == PrimitiveNode.Function.BUFFER)
{
// assign possible: determine operator
String op = "";
if (nodeType == PrimitiveNode.Function.GATEAND) op = " & "; else
if (nodeType == PrimitiveNode.Function.GATEOR) op = " | "; else
if (nodeType == PrimitiveNode.Function.GATEXOR) op = " ^ ";
// write a line describing this signal
StringBuffer infstr = new StringBuffer();
boolean wholeNegated = false;
first = true;
NodeInst ni = (NodeInst)no;
for(int i=0; i<2; i++)
{
for(Iterator<Connection> cIt = ni.getConnections(); cIt.hasNext(); )
{
Connection con = cIt.next();
PortInst pi = con.getPortInst();
if (i == 0)
{
if (!pi.getPortProto().getName().equals("y")) continue;
} else
{
if (!pi.getPortProto().getName().equals("a")) continue;
}
// determine the network name at this port
ArcInst ai = con.getArc();
Network net = netList.getNetwork(ai, 0);
CellSignal cs = cni.getCellSignal(net);
String sigName = getSignalName(cs);
// see if this end is negated
boolean isNegated = false;
if (ai.isTailNegated() || ai.isHeadNegated()) isNegated = true;
// write the port name
if (i == 0)
{
// got the output port: do the left-side of the "assign"
infstr.append("assign " + sigName + " = ");
if (isNegated)
{
infstr.append("~(");
wholeNegated = true;
}
break;
}
if (!first)
infstr.append(op);
first = false;
if (isNegated) infstr.append("~");
infstr.append(sigName);
}
}
if (wholeNegated)
infstr.append(")");
infstr.append(";\n");
writeWidthLimited(infstr.toString());
continue;
}
}
// get the name of the node
int implicitPorts = 0;
boolean dropBias = false;
String nodeName = "";
if (no.isCellInstance())
{
// make sure there are contents for this cell instance
if (((Cell)niProto).isIcon()) continue;
nodeName = parameterizedName(no, context);
// cells defined as "primitives" in Verilog View must have implicit port ordering
if (definedPrimitives.containsKey(niProto)) {
implicitPorts = 3;
}
} else
{
// convert 4-port transistors to 3-port
if (nodeType == PrimitiveNode.Function.TRA4NMOS)
{
nodeType = PrimitiveNode.Function.TRANMOS; dropBias = true;
} else if (nodeType == PrimitiveNode.Function.TRA4PMOS)
{
nodeType = PrimitiveNode.Function.TRAPMOS; dropBias = true;
}
if (nodeType.isNTypeTransistor())
{
implicitPorts = 2;
nodeName = "tranif1";
Variable varWeakNode = ((NodeInst)no).getVar(Simulation.WEAK_NODE_KEY);
if (varWeakNode != null) nodeName = "rtranif1";
} else if (nodeType == PrimitiveNode.Function.TRAPMOS)
{
implicitPorts = 2;
nodeName = "tranif0";
Variable varWeakNode = ((NodeInst)no).getVar(Simulation.WEAK_NODE_KEY);
if (varWeakNode != null) nodeName = "rtranif0";
} else if (nodeType == PrimitiveNode.Function.GATEAND)
{
implicitPorts = 1;
nodeName = chooseNodeName((NodeInst)no, "and", "nand");
} else if (nodeType == PrimitiveNode.Function.GATEOR)
{
implicitPorts = 1;
nodeName = chooseNodeName((NodeInst)no, "or", "nor");
} else if (nodeType == PrimitiveNode.Function.GATEXOR)
{
implicitPorts = 1;
nodeName = chooseNodeName((NodeInst)no, "xor", "xnor");
} else if (nodeType == PrimitiveNode.Function.BUFFER)
{
implicitPorts = 1;
nodeName = chooseNodeName((NodeInst)no, "buf", "not");
}
}
if (nodeName.length() == 0) continue;
// write the type of the node
StringBuffer infstr = new StringBuffer();
infstr.append(" " + nodeName + " " + nameNoIndices(no.getName()) + "(");
// write the rest of the ports
first = true;
NodeInst ni = null;
switch (implicitPorts)
{
case 0: // explicit ports (for cell instances)
CellNetInfo subCni = getCellNetInfo(nodeName);
for(Iterator<CellAggregateSignal> sIt = subCni.getCellAggregateSignals(); sIt.hasNext(); )
{
CellAggregateSignal cas = sIt.next();
// ignore networks that aren't exported
PortProto pp = cas.getExport();
if (pp == null) continue;
if (first) first = false; else
infstr.append(", ");
if (cas.getLowIndex() > cas.getHighIndex())
{
// single signal
infstr.append("." + cas.getName() + "(");
Network net = netList.getNetwork(no, pp, cas.getExportIndex());
CellSignal cs = cni.getCellSignal(net);
infstr.append(getSignalName(cs));
infstr.append(")");
accumulatePortConnectivity(instancePortsOnNet, net, (Export)pp);
} else
{
int [] indices = cas.getIndices();
if (indices != null)
{
// broken bus internally, write signals individually
for(int i=0; i<indices.length; i++)
{
CellSignal cInnerSig = cas.getSignal(i);
Network net = netList.getNetwork(no, cas.getExport(), cInnerSig.getExportIndex());
CellSignal outerSignal = cni.getCellSignal(net);
accumulatePortConnectivity(instancePortsOnNet, net, (Export)pp);
int ind = i;
if (cas.isDescending()) ind = indices.length - i - 1;
if (i > 0) infstr.append(", ");
infstr.append(".\\" + cas.getName() + "[" + indices[ind] + "] (");
infstr.append(getSignalName(outerSignal));
infstr.append(")");
}
} else
{
// simple bus, write signals
int total = cas.getNumSignals();
CellSignal [] outerSignalList = new CellSignal[total];
for(int j=0; j<total; j++)
{
CellSignal cInnerSig = cas.getSignal(j);
Network net = netList.getNetwork(no, cas.getExport(), cInnerSig.getExportIndex());
outerSignalList[j] = cni.getCellSignal(net);
accumulatePortConnectivity(instancePortsOnNet, net, (Export)pp);
}
writeBus(outerSignalList, total, cas.isDescending(),
cas.getName(), cni.getPowerNet(), cni.getGroundNet(), infstr);
}
}
}
infstr.append(");");
break;
case 1: // and/or gate: write ports in the proper order
ni = (NodeInst)no;
for(int i=0; i<2; i++)
{
for(Iterator<Connection> cIt = ni.getConnections(); cIt.hasNext(); )
{
Connection con = cIt.next();
PortInst pi = con.getPortInst();
if (i == 0)
{
if (!pi.getPortProto().getName().equals("y")) continue;
} else
{
if (!pi.getPortProto().getName().equals("a")) continue;
}
if (first) first = false; else
infstr.append(", ");
ArcInst ai = con.getArc();
Network net = netList.getNetwork(ai, 0);
CellSignal cs = cni.getCellSignal(net);
if (cs == null) continue;
String sigName = getSignalName(cs);
if (i != 0 && con.isNegated())
{
// this input is negated: write the implicit inverter
Integer invIndex;
if (con.getEndIndex() == ArcInst.HEADEND) invIndex = implicitHeadInverters.get(ai); else
invIndex = implicitTailInverters.get(ai);
if (invIndex != null)
{
String invSigName = IMPLICITINVERTERSIGNAME + invIndex.intValue();
printWriter.println(" inv " + IMPLICITINVERTERNODENAME +
invIndex.intValue() + " (" + invSigName + ", " + sigName + ");");
sigName = invSigName;
}
}
infstr.append(sigName);
}
}
infstr.append(");");
break;
case 2: // transistors: write ports in the proper order: s/d/g
ni = (NodeInst)no;
Network gateNet = netList.getNetwork(ni.getTransistorGatePort());
for(int i=0; i<2; i++)
{
boolean didGate = false;
for(Iterator<PortInst> pIt = ni.getPortInsts(); pIt.hasNext(); )
{
PortInst pi = pIt.next();
Network net = netList.getNetwork(pi);
if (dropBias && pi.getPortProto().getName().equals("b")) continue;
if (i == 0)
{
if (net == gateNet) continue;
} else
{
if (net != gateNet) continue;
if (didGate) continue;
didGate = true;
}
if (first) first = false; else
infstr.append(", ");
CellSignal cs = cni.getCellSignal(net);
String sigName = getSignalName(cs);
infstr.append(sigName);
}
}
infstr.append(");");
break;
case 3: // implicit ports ordering for cells defined as primitives in Verilog View
ni = no.getNodeInst();
VerilogData.VerilogModule module = definedPrimitives.get(niProto);
if (module == null) break;
System.out.print(cell.getName()+" ports: ");
for (VerilogData.VerilogPort port : module.getPorts()) {
List<String> portnames = port.getPinNames(true);
if (portnames.size() == 0) {
// continue
} else if (portnames.size() > 1) {
// Bill thinks bussed ports are not allowed for primitives
System.out.println("Error: bussed ports not allowed on Verilog primitives: "+niProto.getName());
} else {
String portname = portnames.get(0);
PortInst pi = ni.findPortInst(portname);
Network net = netList.getNetwork(no, pi.getProtoEquivalent(), 0);
CellSignal cs = cni.getCellSignal(net);
String sigName = getSignalName(cs);
if (first) first = false; else
infstr.append(", ");
infstr.append(sigName);
System.out.print(portname+" ");
}
}
System.out.println();
infstr.append(");");
break;
}
infstr.append("\n");
writeWidthLimited(infstr.toString());
}
printWriter.println("endmodule /* " + cni.getParameterizedName() + " */");
// check export direction consistency (inconsistent directions can cause opens in some tools)
for (Iterator<Export> it = cell.getExports(); it.hasNext(); ) {
Export ex = it.next();
PortCharacteristic type = ex.getCharacteristic();
if (type == PortCharacteristic.BIDIR) continue; // whatever it is connect to is fine
for (int i=0; i<ex.getNameKey().busWidth(); i++) {
Network net = netList.getNetwork(ex, i);
List<Export> subports = instancePortsOnNet.get(net);
if (subports == null) continue;
for (Export subex : subports) {
PortCharacteristic subtype = subex.getCharacteristic();
if (type != subtype) {
System.out.println("Warning: Port Direction Inconsistency in cell "+cell.describe(false)+
" between export "+ex.getNameKey().subname(i)+"["+type+"] and instance port "+
subex.getParent().noLibDescribe()+" - "+subex.getName()+"["+subtype+"]");
}
}
}
}
}
|
diff --git a/oak-core/src/main/java/org/apache/jackrabbit/oak/plugins/name/NameValidatorProvider.java b/oak-core/src/main/java/org/apache/jackrabbit/oak/plugins/name/NameValidatorProvider.java
index b958d1d32b..423b652608 100644
--- a/oak-core/src/main/java/org/apache/jackrabbit/oak/plugins/name/NameValidatorProvider.java
+++ b/oak-core/src/main/java/org/apache/jackrabbit/oak/plugins/name/NameValidatorProvider.java
@@ -1,50 +1,50 @@
/*
* 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.jackrabbit.oak.plugins.name;
import static com.google.common.collect.Sets.newHashSet;
import static org.apache.jackrabbit.JcrConstants.JCR_SYSTEM;
import static org.apache.jackrabbit.oak.plugins.name.NamespaceConstants.NSDATA;
import static org.apache.jackrabbit.oak.plugins.name.NamespaceConstants.NSDATA_PREFIXES;
import static org.apache.jackrabbit.oak.plugins.name.NamespaceConstants.REP_NAMESPACES;
import org.apache.felix.scr.annotations.Component;
import org.apache.felix.scr.annotations.Service;
import org.apache.jackrabbit.oak.spi.commit.EditorProvider;
import org.apache.jackrabbit.oak.spi.commit.Validator;
import org.apache.jackrabbit.oak.spi.commit.ValidatorProvider;
import org.apache.jackrabbit.oak.spi.state.NodeState;
/**
* Validator service that checks that all node and property names as well
* as any name values are syntactically valid and that any namespace prefixes
* are properly registered.
*/
@Component
@Service(EditorProvider.class)
public class NameValidatorProvider extends ValidatorProvider {
@Override
public Validator getRootValidator(NodeState before, NodeState after) {
return new NameValidator(newHashSet(after
.getChildNode(JCR_SYSTEM)
.getChildNode(REP_NAMESPACES)
.getChildNode(NSDATA)
- .getString(NSDATA_PREFIXES)));
+ .getStrings(NSDATA_PREFIXES)));
}
}
| true | true | public Validator getRootValidator(NodeState before, NodeState after) {
return new NameValidator(newHashSet(after
.getChildNode(JCR_SYSTEM)
.getChildNode(REP_NAMESPACES)
.getChildNode(NSDATA)
.getString(NSDATA_PREFIXES)));
}
| public Validator getRootValidator(NodeState before, NodeState after) {
return new NameValidator(newHashSet(after
.getChildNode(JCR_SYSTEM)
.getChildNode(REP_NAMESPACES)
.getChildNode(NSDATA)
.getStrings(NSDATA_PREFIXES)));
}
|
diff --git a/org.eclipse.mylyn.trac.core/src/org/eclipse/mylyn/internal/trac/core/TracTaskDataHandler.java b/org.eclipse.mylyn.trac.core/src/org/eclipse/mylyn/internal/trac/core/TracTaskDataHandler.java
index 9da8a0e91..d97d52092 100644
--- a/org.eclipse.mylyn.trac.core/src/org/eclipse/mylyn/internal/trac/core/TracTaskDataHandler.java
+++ b/org.eclipse.mylyn.trac.core/src/org/eclipse/mylyn/internal/trac/core/TracTaskDataHandler.java
@@ -1,403 +1,405 @@
/*******************************************************************************
* Copyright (c) 2004, 2007 Mylyn project committers and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*******************************************************************************/
package org.eclipse.mylyn.internal.trac.core;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.StringTokenizer;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.core.runtime.OperationCanceledException;
import org.eclipse.mylyn.internal.trac.core.TracAttributeFactory.Attribute;
import org.eclipse.mylyn.internal.trac.core.model.TracAttachment;
import org.eclipse.mylyn.internal.trac.core.model.TracComment;
import org.eclipse.mylyn.internal.trac.core.model.TracTicket;
import org.eclipse.mylyn.internal.trac.core.model.TracTicketField;
import org.eclipse.mylyn.internal.trac.core.model.TracTicket.Key;
import org.eclipse.mylyn.internal.trac.core.util.TracUtils;
import org.eclipse.mylyn.tasks.core.AbstractAttributeFactory;
import org.eclipse.mylyn.tasks.core.AbstractTask;
import org.eclipse.mylyn.tasks.core.AbstractTaskDataHandler;
import org.eclipse.mylyn.tasks.core.RepositoryAttachment;
import org.eclipse.mylyn.tasks.core.RepositoryOperation;
import org.eclipse.mylyn.tasks.core.RepositoryStatus;
import org.eclipse.mylyn.tasks.core.RepositoryTaskAttribute;
import org.eclipse.mylyn.tasks.core.RepositoryTaskData;
import org.eclipse.mylyn.tasks.core.TaskComment;
import org.eclipse.mylyn.tasks.core.TaskRepository;
/**
* @author Steffen Pingel
*/
public class TracTaskDataHandler extends AbstractTaskDataHandler {
public static final String ATTRIBUTE_BLOCKED_BY = "blockedby";
public static final String ATTRIBUTE_BLOCKING = "blocking";
private static final String CC_DELIMETER = ", ";
private AbstractAttributeFactory attributeFactory = new TracAttributeFactory();
private TracRepositoryConnector connector;
public TracTaskDataHandler(TracRepositoryConnector connector) {
this.connector = connector;
}
@Override
public RepositoryTaskData getTaskData(TaskRepository repository, String taskId, IProgressMonitor monitor)
throws CoreException {
return downloadTaskData(repository, TracRepositoryConnector.getTicketId(taskId));
}
public RepositoryTaskData downloadTaskData(TaskRepository repository, int id) throws CoreException {
if (!TracRepositoryConnector.hasRichEditor(repository)) {
// offline mode is only supported for XML-RPC
return null;
}
try {
RepositoryTaskData data = new RepositoryTaskData(attributeFactory, TracCorePlugin.REPOSITORY_KIND,
repository.getUrl(), id + "");
ITracClient client = connector.getClientManager().getRepository(repository);
client.updateAttributes(new NullProgressMonitor(), false);
TracTicket ticket = client.getTicket(id);
createDefaultAttributes(attributeFactory, data, client, true);
updateTaskData(repository, attributeFactory, data, ticket);
return data;
} catch (OperationCanceledException e) {
throw e;
} catch (Exception e) {
// TODO catch TracException
throw new CoreException(TracCorePlugin.toStatus(e, repository));
}
}
@Override
public AbstractAttributeFactory getAttributeFactory(String repositoryUrl, String repositoryKind, String taskKind) {
// we don't care about the repository information right now
return attributeFactory;
}
@Override
public AbstractAttributeFactory getAttributeFactory(RepositoryTaskData taskData) {
return getAttributeFactory(taskData.getRepositoryUrl(), taskData.getRepositoryKind(), taskData.getTaskKind());
}
public static void updateTaskData(TaskRepository repository, AbstractAttributeFactory factory,
RepositoryTaskData data, TracTicket ticket) {
if (ticket.getCreated() != null) {
data.setAttributeValue(Attribute.TIME.getTracKey(), TracUtils.toTracTime(ticket.getCreated()) + "");
}
Date lastChanged = ticket.getLastChanged();
Map<String, String> valueByKey = ticket.getValues();
for (String key : valueByKey.keySet()) {
if (Key.CC.getKey().equals(key)) {
StringTokenizer t = new StringTokenizer(valueByKey.get(key), CC_DELIMETER);
while (t.hasMoreTokens()) {
data.addAttributeValue(key, t.nextToken());
}
} else {
data.setAttributeValue(key, valueByKey.get(key));
}
}
TracComment[] comments = ticket.getComments();
if (comments != null) {
for (int i = 0; i < comments.length; i++) {
if (!"comment".equals(comments[i].getField()) || "".equals(comments[i].getNewValue())) {
continue;
}
TaskComment taskComment = new TaskComment(factory, data.getComments().size() + 1);
taskComment.setAttributeValue(RepositoryTaskAttribute.COMMENT_AUTHOR, comments[i].getAuthor());
taskComment.setAttributeValue(RepositoryTaskAttribute.COMMENT_DATE, comments[i].getCreated().toString());
taskComment.setAttributeValue(RepositoryTaskAttribute.COMMENT_TEXT, comments[i].getNewValue());
data.addComment(taskComment);
}
}
TracAttachment[] attachments = ticket.getAttachments();
if (attachments != null) {
for (int i = 0; i < attachments.length; i++) {
RepositoryAttachment taskAttachment = new RepositoryAttachment(factory);
taskAttachment.setCreator(attachments[i].getAuthor());
taskAttachment.setRepositoryKind(TracCorePlugin.REPOSITORY_KIND);
taskAttachment.setRepositoryUrl(repository.getUrl());
taskAttachment.setTaskId("" + ticket.getId());
taskAttachment.setAttributeValue(Attribute.DESCRIPTION.getTracKey(), attachments[i].getDescription());
taskAttachment.setAttributeValue(RepositoryTaskAttribute.ATTACHMENT_FILENAME,
attachments[i].getFilename());
+ taskAttachment.setAttributeValue(RepositoryTaskAttribute.ATTACHMENT_SIZE,
+ attachments[i].getSize() + "");
taskAttachment.setAttributeValue(RepositoryTaskAttribute.USER_OWNER, attachments[i].getAuthor());
if (attachments[i].getCreated() != null) {
if (lastChanged == null || attachments[i].getCreated().after(lastChanged)) {
lastChanged = attachments[i].getCreated();
}
taskAttachment.setAttributeValue(RepositoryTaskAttribute.ATTACHMENT_DATE, attachments[i].getCreated()
.toString());
}
taskAttachment.setAttributeValue(RepositoryTaskAttribute.ATTACHMENT_URL, repository.getUrl()
+ ITracClient.TICKET_ATTACHMENT_URL + ticket.getId() + "/" + attachments[i].getFilename());
taskAttachment.setAttributeValue(RepositoryTaskAttribute.ATTACHMENT_ID, i + "");
data.addAttachment(taskAttachment);
}
}
String[] actions = ticket.getActions();
if (actions != null) {
// add operations in a defined order
List<String> actionList = new ArrayList<String>(Arrays.asList(actions));
addOperation(repository, data, ticket, actionList, "leave");
addOperation(repository, data, ticket, actionList, "accept");
addOperation(repository, data, ticket, actionList, "resolve");
addOperation(repository, data, ticket, actionList, "reassign");
addOperation(repository, data, ticket, actionList, "reopen");
}
if (lastChanged != null) {
data.setAttributeValue(Attribute.CHANGE_TIME.getTracKey(), TracUtils.toTracTime(lastChanged) + "");
}
}
// TODO Reuse Labels from BugzillaServerFacade
private static void addOperation(TaskRepository repository, RepositoryTaskData data, TracTicket ticket,
List<String> actions, String action) {
if (!actions.remove(action)) {
return;
}
RepositoryOperation operation = null;
if ("leave".equals(action)) {
operation = new RepositoryOperation(action, "Leave as " + data.getStatus() + " " + data.getResolution());
operation.setChecked(true);
} else if ("accept".equals(action)) {
operation = new RepositoryOperation(action, "Accept");
} else if ("resolve".equals(action)) {
operation = new RepositoryOperation(action, "Resolve as");
operation.setUpOptions("resolution");
for (String resolution : ticket.getResolutions()) {
operation.addOption(resolution, resolution);
}
} else if ("reassign".equals(action)) {
operation = new RepositoryOperation(action, "Reassign to");
operation.setInputName("owner");
operation.setInputValue(TracRepositoryConnector.getDisplayUsername(repository));
} else if ("reopen".equals(action)) {
operation = new RepositoryOperation(action, "Reopen");
}
if (operation != null) {
data.addOperation(operation);
}
}
public static void createDefaultAttributes(AbstractAttributeFactory factory, RepositoryTaskData data,
ITracClient client, boolean existingTask) {
TracTicketField[] fields = client.getTicketFields();
if (existingTask) {
createAttribute(factory, data, Attribute.STATUS, client.getTicketStatus());
createAttribute(factory, data, Attribute.RESOLUTION, client.getTicketResolutions());
}
createAttribute(factory, data, Attribute.COMPONENT, client.getComponents());
createAttribute(factory, data, Attribute.VERSION, client.getVersions(), true);
createAttribute(factory, data, Attribute.PRIORITY, client.getPriorities());
createAttribute(factory, data, Attribute.SEVERITY, client.getSeverities());
createAttribute(factory, data, Attribute.TYPE, client.getTicketTypes());
RepositoryTaskAttribute attribute = createAttribute(factory, data, Attribute.OWNER);
if (!existingTask) {
attribute.setReadOnly(false);
}
createAttribute(factory, data, Attribute.MILESTONE, client.getMilestones(), true);
if (existingTask) {
createAttribute(factory, data, Attribute.REPORTER);
}
if (existingTask) {
createAttribute(factory, data, Attribute.NEW_CC);
}
createAttribute(factory, data, Attribute.CC);
createAttribute(factory, data, Attribute.KEYWORDS);
if (!existingTask) {
createAttribute(factory, data, Attribute.SUMMARY);
createAttribute(factory, data, Attribute.DESCRIPTION);
}
if (fields != null) {
for (TracTicketField field : fields) {
if (field.isCustom()) {
createAttribute(data, field);
}
}
}
}
private static void createAttribute(RepositoryTaskData data, TracTicketField field) {
RepositoryTaskAttribute attr = new RepositoryTaskAttribute(field.getName(), field.getLabel(), false);
if (field.getType() == TracTicketField.Type.CHECKBOX) {
// attr.addOption("True", "1");
// attr.addOption("False", "0");
attr.addOption("1", "1");
attr.addOption("0", "0");
if (field.getDefaultValue() != null) {
attr.setValue(field.getDefaultValue());
}
} else if (field.getType() == TracTicketField.Type.SELECT || field.getType() == TracTicketField.Type.RADIO) {
String[] values = field.getOptions();
if (values != null && values.length > 0) {
if (field.isOptional()) {
attr.addOption("", "");
}
for (int i = 0; i < values.length; i++) {
attr.addOption(values[i], values[i]);
}
if (field.getDefaultValue() != null) {
try {
int index = Integer.parseInt(field.getDefaultValue());
if (index > 0 && index < values.length) {
attr.setValue(values[index]);
}
} catch (NumberFormatException e) {
for (int i = 0; i < values.length; i++) {
if (field.getDefaultValue().equals(values[i].toString())) {
attr.setValue(values[i]);
break;
}
}
}
}
}
} else {
if (field.getDefaultValue() != null) {
attr.setValue(field.getDefaultValue());
}
}
data.addAttribute(attr.getId(), attr);
}
private static RepositoryTaskAttribute createAttribute(AbstractAttributeFactory factory, RepositoryTaskData data,
Attribute attribute, Object[] values, boolean allowEmtpy) {
RepositoryTaskAttribute attr = factory.createAttribute(attribute.getTracKey());
if (values != null && values.length > 0) {
if (allowEmtpy) {
attr.addOption("", "");
}
for (int i = 0; i < values.length; i++) {
attr.addOption(values[i].toString(), values[i].toString());
}
} else {
attr.setHidden(true);
attr.setReadOnly(true);
}
data.addAttribute(attribute.getTracKey(), attr);
return attr;
}
private static RepositoryTaskAttribute createAttribute(AbstractAttributeFactory factory, RepositoryTaskData data,
Attribute attribute) {
RepositoryTaskAttribute attr = factory.createAttribute(attribute.getTracKey());
data.addAttribute(attribute.getTracKey(), attr);
return attr;
}
private static RepositoryTaskAttribute createAttribute(AbstractAttributeFactory factory, RepositoryTaskData data,
Attribute attribute, Object[] values) {
return createAttribute(factory, data, attribute, values, false);
}
@Override
public String postTaskData(TaskRepository repository, RepositoryTaskData taskData, IProgressMonitor monitor)
throws CoreException {
try {
TracTicket ticket = TracRepositoryConnector.getTracTicket(repository, taskData);
ITracClient server = connector.getClientManager().getRepository(repository);
if (taskData.isNew()) {
int id = server.createTicket(ticket);
return id + "";
} else {
server.updateTicket(ticket, taskData.getNewComment());
return null;
}
} catch (OperationCanceledException e) {
throw e;
} catch (Exception e) {
// TODO catch TracException
throw new CoreException(TracCorePlugin.toStatus(e, repository));
}
}
@Override
public boolean initializeTaskData(TaskRepository repository, RepositoryTaskData data, IProgressMonitor monitor)
throws CoreException {
try {
ITracClient client = connector.getClientManager().getRepository(repository);
client.updateAttributes(new NullProgressMonitor(), false);
createDefaultAttributes(attributeFactory, data, client, false);
return true;
} catch (OperationCanceledException e) {
throw e;
} catch (Exception e) {
// TODO catch TracException
throw new CoreException(TracCorePlugin.toStatus(e, repository));
}
}
@Override
public boolean initializeSubTaskData(TaskRepository repository, RepositoryTaskData taskData,
RepositoryTaskData parentTaskData, IProgressMonitor monitor) throws CoreException {
initializeTaskData(repository, taskData, monitor);
RepositoryTaskAttribute attribute = taskData.getAttribute(ATTRIBUTE_BLOCKING);
if (attribute == null) {
throw new CoreException(new RepositoryStatus(repository, IStatus.ERROR, TracCorePlugin.PLUGIN_ID, RepositoryStatus.ERROR_REPOSITORY, "The repository does not support subtasks"));
}
cloneTaskData(parentTaskData, taskData);
taskData.setDescription("");
taskData.setSummary("");
attribute.setValue(parentTaskData.getId());
return true;
}
@Override
public Set<String> getSubTaskIds(RepositoryTaskData taskData) {
RepositoryTaskAttribute attribute = taskData.getAttribute(ATTRIBUTE_BLOCKED_BY);
if (attribute != null) {
return new HashSet<String>(Arrays.asList(attribute.getValue().split("\\s")));
}
return Collections.emptySet();
}
@Override
public boolean canInitializeSubTaskData(AbstractTask task, RepositoryTaskData parentTaskData) {
if (parentTaskData != null) {
return parentTaskData.getAttribute(ATTRIBUTE_BLOCKED_BY) != null;
} else if (task instanceof TracTask) {
return ((TracTask)task).getSupportsSubtasks();
}
return false;
}
}
| true | true | public static void updateTaskData(TaskRepository repository, AbstractAttributeFactory factory,
RepositoryTaskData data, TracTicket ticket) {
if (ticket.getCreated() != null) {
data.setAttributeValue(Attribute.TIME.getTracKey(), TracUtils.toTracTime(ticket.getCreated()) + "");
}
Date lastChanged = ticket.getLastChanged();
Map<String, String> valueByKey = ticket.getValues();
for (String key : valueByKey.keySet()) {
if (Key.CC.getKey().equals(key)) {
StringTokenizer t = new StringTokenizer(valueByKey.get(key), CC_DELIMETER);
while (t.hasMoreTokens()) {
data.addAttributeValue(key, t.nextToken());
}
} else {
data.setAttributeValue(key, valueByKey.get(key));
}
}
TracComment[] comments = ticket.getComments();
if (comments != null) {
for (int i = 0; i < comments.length; i++) {
if (!"comment".equals(comments[i].getField()) || "".equals(comments[i].getNewValue())) {
continue;
}
TaskComment taskComment = new TaskComment(factory, data.getComments().size() + 1);
taskComment.setAttributeValue(RepositoryTaskAttribute.COMMENT_AUTHOR, comments[i].getAuthor());
taskComment.setAttributeValue(RepositoryTaskAttribute.COMMENT_DATE, comments[i].getCreated().toString());
taskComment.setAttributeValue(RepositoryTaskAttribute.COMMENT_TEXT, comments[i].getNewValue());
data.addComment(taskComment);
}
}
TracAttachment[] attachments = ticket.getAttachments();
if (attachments != null) {
for (int i = 0; i < attachments.length; i++) {
RepositoryAttachment taskAttachment = new RepositoryAttachment(factory);
taskAttachment.setCreator(attachments[i].getAuthor());
taskAttachment.setRepositoryKind(TracCorePlugin.REPOSITORY_KIND);
taskAttachment.setRepositoryUrl(repository.getUrl());
taskAttachment.setTaskId("" + ticket.getId());
taskAttachment.setAttributeValue(Attribute.DESCRIPTION.getTracKey(), attachments[i].getDescription());
taskAttachment.setAttributeValue(RepositoryTaskAttribute.ATTACHMENT_FILENAME,
attachments[i].getFilename());
taskAttachment.setAttributeValue(RepositoryTaskAttribute.USER_OWNER, attachments[i].getAuthor());
if (attachments[i].getCreated() != null) {
if (lastChanged == null || attachments[i].getCreated().after(lastChanged)) {
lastChanged = attachments[i].getCreated();
}
taskAttachment.setAttributeValue(RepositoryTaskAttribute.ATTACHMENT_DATE, attachments[i].getCreated()
.toString());
}
taskAttachment.setAttributeValue(RepositoryTaskAttribute.ATTACHMENT_URL, repository.getUrl()
+ ITracClient.TICKET_ATTACHMENT_URL + ticket.getId() + "/" + attachments[i].getFilename());
taskAttachment.setAttributeValue(RepositoryTaskAttribute.ATTACHMENT_ID, i + "");
data.addAttachment(taskAttachment);
}
}
String[] actions = ticket.getActions();
if (actions != null) {
// add operations in a defined order
List<String> actionList = new ArrayList<String>(Arrays.asList(actions));
addOperation(repository, data, ticket, actionList, "leave");
addOperation(repository, data, ticket, actionList, "accept");
addOperation(repository, data, ticket, actionList, "resolve");
addOperation(repository, data, ticket, actionList, "reassign");
addOperation(repository, data, ticket, actionList, "reopen");
}
if (lastChanged != null) {
data.setAttributeValue(Attribute.CHANGE_TIME.getTracKey(), TracUtils.toTracTime(lastChanged) + "");
}
}
| public static void updateTaskData(TaskRepository repository, AbstractAttributeFactory factory,
RepositoryTaskData data, TracTicket ticket) {
if (ticket.getCreated() != null) {
data.setAttributeValue(Attribute.TIME.getTracKey(), TracUtils.toTracTime(ticket.getCreated()) + "");
}
Date lastChanged = ticket.getLastChanged();
Map<String, String> valueByKey = ticket.getValues();
for (String key : valueByKey.keySet()) {
if (Key.CC.getKey().equals(key)) {
StringTokenizer t = new StringTokenizer(valueByKey.get(key), CC_DELIMETER);
while (t.hasMoreTokens()) {
data.addAttributeValue(key, t.nextToken());
}
} else {
data.setAttributeValue(key, valueByKey.get(key));
}
}
TracComment[] comments = ticket.getComments();
if (comments != null) {
for (int i = 0; i < comments.length; i++) {
if (!"comment".equals(comments[i].getField()) || "".equals(comments[i].getNewValue())) {
continue;
}
TaskComment taskComment = new TaskComment(factory, data.getComments().size() + 1);
taskComment.setAttributeValue(RepositoryTaskAttribute.COMMENT_AUTHOR, comments[i].getAuthor());
taskComment.setAttributeValue(RepositoryTaskAttribute.COMMENT_DATE, comments[i].getCreated().toString());
taskComment.setAttributeValue(RepositoryTaskAttribute.COMMENT_TEXT, comments[i].getNewValue());
data.addComment(taskComment);
}
}
TracAttachment[] attachments = ticket.getAttachments();
if (attachments != null) {
for (int i = 0; i < attachments.length; i++) {
RepositoryAttachment taskAttachment = new RepositoryAttachment(factory);
taskAttachment.setCreator(attachments[i].getAuthor());
taskAttachment.setRepositoryKind(TracCorePlugin.REPOSITORY_KIND);
taskAttachment.setRepositoryUrl(repository.getUrl());
taskAttachment.setTaskId("" + ticket.getId());
taskAttachment.setAttributeValue(Attribute.DESCRIPTION.getTracKey(), attachments[i].getDescription());
taskAttachment.setAttributeValue(RepositoryTaskAttribute.ATTACHMENT_FILENAME,
attachments[i].getFilename());
taskAttachment.setAttributeValue(RepositoryTaskAttribute.ATTACHMENT_SIZE,
attachments[i].getSize() + "");
taskAttachment.setAttributeValue(RepositoryTaskAttribute.USER_OWNER, attachments[i].getAuthor());
if (attachments[i].getCreated() != null) {
if (lastChanged == null || attachments[i].getCreated().after(lastChanged)) {
lastChanged = attachments[i].getCreated();
}
taskAttachment.setAttributeValue(RepositoryTaskAttribute.ATTACHMENT_DATE, attachments[i].getCreated()
.toString());
}
taskAttachment.setAttributeValue(RepositoryTaskAttribute.ATTACHMENT_URL, repository.getUrl()
+ ITracClient.TICKET_ATTACHMENT_URL + ticket.getId() + "/" + attachments[i].getFilename());
taskAttachment.setAttributeValue(RepositoryTaskAttribute.ATTACHMENT_ID, i + "");
data.addAttachment(taskAttachment);
}
}
String[] actions = ticket.getActions();
if (actions != null) {
// add operations in a defined order
List<String> actionList = new ArrayList<String>(Arrays.asList(actions));
addOperation(repository, data, ticket, actionList, "leave");
addOperation(repository, data, ticket, actionList, "accept");
addOperation(repository, data, ticket, actionList, "resolve");
addOperation(repository, data, ticket, actionList, "reassign");
addOperation(repository, data, ticket, actionList, "reopen");
}
if (lastChanged != null) {
data.setAttributeValue(Attribute.CHANGE_TIME.getTracKey(), TracUtils.toTracTime(lastChanged) + "");
}
}
|
diff --git a/common/cpw/mods/fml/common/network/NetworkModHandler.java b/common/cpw/mods/fml/common/network/NetworkModHandler.java
index 1b94fb41..09c16ffb 100644
--- a/common/cpw/mods/fml/common/network/NetworkModHandler.java
+++ b/common/cpw/mods/fml/common/network/NetworkModHandler.java
@@ -1,350 +1,350 @@
package cpw.mods.fml.common.network;
import java.lang.reflect.Method;
import java.util.Set;
import java.util.logging.Level;
import net.minecraft.src.Item;
import com.google.common.base.Strings;
import cpw.mods.fml.common.FMLCommonHandler;
import cpw.mods.fml.common.FMLLog;
import cpw.mods.fml.common.ModContainer;
import cpw.mods.fml.common.Side;
import cpw.mods.fml.common.discovery.ASMDataTable;
import cpw.mods.fml.common.discovery.ASMDataTable.ASMData;
import cpw.mods.fml.common.versioning.DefaultArtifactVersion;
import cpw.mods.fml.common.versioning.InvalidVersionSpecificationException;
import cpw.mods.fml.common.versioning.VersionRange;
public class NetworkModHandler
{
private static Object connectionHandlerDefaultValue;
private static Object packetHandlerDefaultValue;
private static Object clientHandlerDefaultValue;
private static Object serverHandlerDefaultValue;
private static Object tinyPacketHandlerDefaultValue;
private static int assignedIds = 1;
private int localId;
private int networkId;
private ModContainer container;
private NetworkMod mod;
private Method checkHandler;
private VersionRange acceptableRange;
private ITinyPacketHandler tinyPacketHandler;
public NetworkModHandler(ModContainer container, NetworkMod modAnnotation)
{
this.container = container;
this.mod = modAnnotation;
this.localId = assignedIds++;
this.networkId = this.localId;
// Skip over the map object because it has special network id meaning
if (Item.field_77744_bd.field_77779_bT == assignedIds)
{
assignedIds++;
}
}
public NetworkModHandler(ModContainer container, Class<?> networkModClass, ASMDataTable table)
{
this(container, networkModClass.getAnnotation(NetworkMod.class));
if (this.mod == null)
{
return;
}
Set<ASMData> versionCheckHandlers = table.getAnnotationsFor(container).get(NetworkMod.VersionCheckHandler.class.getName());
String versionCheckHandlerMethod = null;
for (ASMData vch : versionCheckHandlers)
{
if (vch.getClassName().equals(networkModClass.getName()))
{
versionCheckHandlerMethod = vch.getObjectName();
break;
}
}
if (versionCheckHandlerMethod != null)
{
try
{
Method checkHandlerMethod = networkModClass.getDeclaredMethod(versionCheckHandlerMethod, String.class);
if (checkHandlerMethod.isAnnotationPresent(NetworkMod.VersionCheckHandler.class))
{
this.checkHandler = checkHandlerMethod;
}
}
catch (Exception e)
{
FMLLog.log(Level.WARNING, e, "The declared version check handler method %s on network mod id %s is not accessible", versionCheckHandlerMethod, container.getModId());
}
}
if (this.checkHandler == null)
{
String versionBounds = mod.versionBounds();
if (!Strings.isNullOrEmpty(versionBounds))
{
try
{
this.acceptableRange = VersionRange.createFromVersionSpec(versionBounds);
}
catch (InvalidVersionSpecificationException e)
{
FMLLog.log(Level.WARNING, e, "Invalid bounded range %s specified for network mod id %s", versionBounds, container.getModId());
}
}
}
FMLLog.finest("Testing mod %s to very it can accept it's own version in a remote connection", container.getModId());
boolean acceptsSelf = acceptVersion(container.getVersion());
if (!acceptsSelf)
{
FMLLog.severe("The mod %s appears to reject it's own version number (%s) in it's version handling. This is likely a severe bug in the mod!", container.getModId(), container.getVersion());
}
else
{
FMLLog.finest("The mod %s accepts it's own version (%s)", container.getModId(), container.getVersion());
}
tryCreatingPacketHandler(container, mod.packetHandler(), mod.channels(), null);
if (FMLCommonHandler.instance().getSide().isClient())
{
if (mod.clientPacketHandlerSpec() != getClientHandlerSpecDefaultValue())
{
tryCreatingPacketHandler(container, mod.clientPacketHandlerSpec().packetHandler(), mod.clientPacketHandlerSpec().channels(), Side.CLIENT);
}
}
if (mod.serverPacketHandlerSpec() != getServerHandlerSpecDefaultValue())
{
tryCreatingPacketHandler(container, mod.serverPacketHandlerSpec().packetHandler(), mod.serverPacketHandlerSpec().channels(), Side.SERVER);
}
if (mod.connectionHandler() != getConnectionHandlerDefaultValue())
{
IConnectionHandler instance;
try
{
instance = mod.connectionHandler().newInstance();
}
catch (Exception e)
{
FMLLog.log(Level.SEVERE, e, "Unable to create connection handler instance %s", mod.connectionHandler().getName());
throw new FMLNetworkException(e);
}
NetworkRegistry.instance().registerConnectionHandler(instance);
}
- if (mod.tinyPacketHandler()!=tinyPacketHandlerDefaultValue)
+ if (mod.tinyPacketHandler()!=getTinyPacketHandlerDefaultValue())
{
try
{
tinyPacketHandler = mod.tinyPacketHandler().newInstance();
}
catch (Exception e)
{
FMLLog.log(Level.SEVERE, e, "Unable to create tiny packet handler instance %s", mod.tinyPacketHandler().getName());
throw new FMLNetworkException(e);
}
}
}
/**
* @param container
*/
private void tryCreatingPacketHandler(ModContainer container, Class<? extends IPacketHandler> clazz, String[] channels, Side side)
{
if (side!=null && side.isClient() && ! FMLCommonHandler.instance().getSide().isClient())
{
return;
}
if (clazz!=getPacketHandlerDefaultValue())
{
if (channels.length==0)
{
FMLLog.log(Level.WARNING, "The mod id %s attempted to register a packet handler without specifying channels for it", container.getModId());
}
else
{
IPacketHandler instance;
try
{
instance = clazz.newInstance();
}
catch (Exception e)
{
FMLLog.log(Level.SEVERE, e, "Unable to create a packet handler instance %s for mod %s", clazz.getName(), container.getModId());
throw new FMLNetworkException(e);
}
for (String channel : channels)
{
NetworkRegistry.instance().registerChannel(instance, channel, side);
}
}
}
else if (channels.length > 0)
{
FMLLog.warning("The mod id %s attempted to register channels without specifying a packet handler", container.getModId());
}
}
/**
* @return
*/
private Object getConnectionHandlerDefaultValue()
{
try {
if (connectionHandlerDefaultValue == null)
{
connectionHandlerDefaultValue = NetworkMod.class.getMethod("connectionHandler").getDefaultValue();
}
return connectionHandlerDefaultValue;
}
catch (NoSuchMethodException e)
{
throw new RuntimeException("Derp?", e);
}
}
/**
* @return
*/
private Object getPacketHandlerDefaultValue()
{
try {
if (packetHandlerDefaultValue == null)
{
packetHandlerDefaultValue = NetworkMod.class.getMethod("packetHandler").getDefaultValue();
}
return packetHandlerDefaultValue;
}
catch (NoSuchMethodException e)
{
throw new RuntimeException("Derp?", e);
}
}
private Object getTinyPacketHandlerDefaultValue()
{
try {
if (tinyPacketHandlerDefaultValue == null)
{
tinyPacketHandlerDefaultValue = NetworkMod.class.getMethod("tinyPacketHandler").getDefaultValue();
}
return tinyPacketHandlerDefaultValue;
}
catch (NoSuchMethodException e)
{
throw new RuntimeException("Derp?", e);
}
}
/**
* @return
*/
private Object getClientHandlerSpecDefaultValue()
{
try {
if (clientHandlerDefaultValue == null)
{
clientHandlerDefaultValue = NetworkMod.class.getMethod("clientPacketHandlerSpec").getDefaultValue();
}
return clientHandlerDefaultValue;
}
catch (NoSuchMethodException e)
{
throw new RuntimeException("Derp?", e);
}
}
/**
* @return
*/
private Object getServerHandlerSpecDefaultValue()
{
try {
if (serverHandlerDefaultValue == null)
{
serverHandlerDefaultValue = NetworkMod.class.getMethod("serverPacketHandlerSpec").getDefaultValue();
}
return serverHandlerDefaultValue;
}
catch (NoSuchMethodException e)
{
throw new RuntimeException("Derp?", e);
}
}
public boolean requiresClientSide()
{
return mod.clientSideRequired();
}
public boolean requiresServerSide()
{
return mod.serverSideRequired();
}
public boolean acceptVersion(String version)
{
if (checkHandler != null)
{
try
{
return (Boolean)checkHandler.invoke(container.getMod(), version);
}
catch (Exception e)
{
FMLLog.log(Level.WARNING, e, "There was a problem invoking the checkhandler method %s for network mod id %s", checkHandler.getName(), container.getModId());
return false;
}
}
if (acceptableRange!=null)
{
return acceptableRange.containsVersion(new DefaultArtifactVersion(version));
}
return container.getVersion().equals(version);
}
public int getLocalId()
{
return localId;
}
public int getNetworkId()
{
return networkId;
}
public ModContainer getContainer()
{
return container;
}
public NetworkMod getMod()
{
return mod;
}
public boolean isNetworkMod()
{
return mod != null;
}
public void setNetworkId(int value)
{
this.networkId = value;
}
public boolean hasTinyPacketHandler()
{
return tinyPacketHandler != null;
}
public ITinyPacketHandler getTinyPacketHandler()
{
return tinyPacketHandler;
}
}
| true | true | public NetworkModHandler(ModContainer container, Class<?> networkModClass, ASMDataTable table)
{
this(container, networkModClass.getAnnotation(NetworkMod.class));
if (this.mod == null)
{
return;
}
Set<ASMData> versionCheckHandlers = table.getAnnotationsFor(container).get(NetworkMod.VersionCheckHandler.class.getName());
String versionCheckHandlerMethod = null;
for (ASMData vch : versionCheckHandlers)
{
if (vch.getClassName().equals(networkModClass.getName()))
{
versionCheckHandlerMethod = vch.getObjectName();
break;
}
}
if (versionCheckHandlerMethod != null)
{
try
{
Method checkHandlerMethod = networkModClass.getDeclaredMethod(versionCheckHandlerMethod, String.class);
if (checkHandlerMethod.isAnnotationPresent(NetworkMod.VersionCheckHandler.class))
{
this.checkHandler = checkHandlerMethod;
}
}
catch (Exception e)
{
FMLLog.log(Level.WARNING, e, "The declared version check handler method %s on network mod id %s is not accessible", versionCheckHandlerMethod, container.getModId());
}
}
if (this.checkHandler == null)
{
String versionBounds = mod.versionBounds();
if (!Strings.isNullOrEmpty(versionBounds))
{
try
{
this.acceptableRange = VersionRange.createFromVersionSpec(versionBounds);
}
catch (InvalidVersionSpecificationException e)
{
FMLLog.log(Level.WARNING, e, "Invalid bounded range %s specified for network mod id %s", versionBounds, container.getModId());
}
}
}
FMLLog.finest("Testing mod %s to very it can accept it's own version in a remote connection", container.getModId());
boolean acceptsSelf = acceptVersion(container.getVersion());
if (!acceptsSelf)
{
FMLLog.severe("The mod %s appears to reject it's own version number (%s) in it's version handling. This is likely a severe bug in the mod!", container.getModId(), container.getVersion());
}
else
{
FMLLog.finest("The mod %s accepts it's own version (%s)", container.getModId(), container.getVersion());
}
tryCreatingPacketHandler(container, mod.packetHandler(), mod.channels(), null);
if (FMLCommonHandler.instance().getSide().isClient())
{
if (mod.clientPacketHandlerSpec() != getClientHandlerSpecDefaultValue())
{
tryCreatingPacketHandler(container, mod.clientPacketHandlerSpec().packetHandler(), mod.clientPacketHandlerSpec().channels(), Side.CLIENT);
}
}
if (mod.serverPacketHandlerSpec() != getServerHandlerSpecDefaultValue())
{
tryCreatingPacketHandler(container, mod.serverPacketHandlerSpec().packetHandler(), mod.serverPacketHandlerSpec().channels(), Side.SERVER);
}
if (mod.connectionHandler() != getConnectionHandlerDefaultValue())
{
IConnectionHandler instance;
try
{
instance = mod.connectionHandler().newInstance();
}
catch (Exception e)
{
FMLLog.log(Level.SEVERE, e, "Unable to create connection handler instance %s", mod.connectionHandler().getName());
throw new FMLNetworkException(e);
}
NetworkRegistry.instance().registerConnectionHandler(instance);
}
if (mod.tinyPacketHandler()!=tinyPacketHandlerDefaultValue)
{
try
{
tinyPacketHandler = mod.tinyPacketHandler().newInstance();
}
catch (Exception e)
{
FMLLog.log(Level.SEVERE, e, "Unable to create tiny packet handler instance %s", mod.tinyPacketHandler().getName());
throw new FMLNetworkException(e);
}
}
}
| public NetworkModHandler(ModContainer container, Class<?> networkModClass, ASMDataTable table)
{
this(container, networkModClass.getAnnotation(NetworkMod.class));
if (this.mod == null)
{
return;
}
Set<ASMData> versionCheckHandlers = table.getAnnotationsFor(container).get(NetworkMod.VersionCheckHandler.class.getName());
String versionCheckHandlerMethod = null;
for (ASMData vch : versionCheckHandlers)
{
if (vch.getClassName().equals(networkModClass.getName()))
{
versionCheckHandlerMethod = vch.getObjectName();
break;
}
}
if (versionCheckHandlerMethod != null)
{
try
{
Method checkHandlerMethod = networkModClass.getDeclaredMethod(versionCheckHandlerMethod, String.class);
if (checkHandlerMethod.isAnnotationPresent(NetworkMod.VersionCheckHandler.class))
{
this.checkHandler = checkHandlerMethod;
}
}
catch (Exception e)
{
FMLLog.log(Level.WARNING, e, "The declared version check handler method %s on network mod id %s is not accessible", versionCheckHandlerMethod, container.getModId());
}
}
if (this.checkHandler == null)
{
String versionBounds = mod.versionBounds();
if (!Strings.isNullOrEmpty(versionBounds))
{
try
{
this.acceptableRange = VersionRange.createFromVersionSpec(versionBounds);
}
catch (InvalidVersionSpecificationException e)
{
FMLLog.log(Level.WARNING, e, "Invalid bounded range %s specified for network mod id %s", versionBounds, container.getModId());
}
}
}
FMLLog.finest("Testing mod %s to very it can accept it's own version in a remote connection", container.getModId());
boolean acceptsSelf = acceptVersion(container.getVersion());
if (!acceptsSelf)
{
FMLLog.severe("The mod %s appears to reject it's own version number (%s) in it's version handling. This is likely a severe bug in the mod!", container.getModId(), container.getVersion());
}
else
{
FMLLog.finest("The mod %s accepts it's own version (%s)", container.getModId(), container.getVersion());
}
tryCreatingPacketHandler(container, mod.packetHandler(), mod.channels(), null);
if (FMLCommonHandler.instance().getSide().isClient())
{
if (mod.clientPacketHandlerSpec() != getClientHandlerSpecDefaultValue())
{
tryCreatingPacketHandler(container, mod.clientPacketHandlerSpec().packetHandler(), mod.clientPacketHandlerSpec().channels(), Side.CLIENT);
}
}
if (mod.serverPacketHandlerSpec() != getServerHandlerSpecDefaultValue())
{
tryCreatingPacketHandler(container, mod.serverPacketHandlerSpec().packetHandler(), mod.serverPacketHandlerSpec().channels(), Side.SERVER);
}
if (mod.connectionHandler() != getConnectionHandlerDefaultValue())
{
IConnectionHandler instance;
try
{
instance = mod.connectionHandler().newInstance();
}
catch (Exception e)
{
FMLLog.log(Level.SEVERE, e, "Unable to create connection handler instance %s", mod.connectionHandler().getName());
throw new FMLNetworkException(e);
}
NetworkRegistry.instance().registerConnectionHandler(instance);
}
if (mod.tinyPacketHandler()!=getTinyPacketHandlerDefaultValue())
{
try
{
tinyPacketHandler = mod.tinyPacketHandler().newInstance();
}
catch (Exception e)
{
FMLLog.log(Level.SEVERE, e, "Unable to create tiny packet handler instance %s", mod.tinyPacketHandler().getName());
throw new FMLNetworkException(e);
}
}
}
|
diff --git a/src/plugins/apple/src/com/jivesoftware/spark/plugin/apple/ApplePlugin.java b/src/plugins/apple/src/com/jivesoftware/spark/plugin/apple/ApplePlugin.java
index cfc91ac6..94aa00ed 100644
--- a/src/plugins/apple/src/com/jivesoftware/spark/plugin/apple/ApplePlugin.java
+++ b/src/plugins/apple/src/com/jivesoftware/spark/plugin/apple/ApplePlugin.java
@@ -1,137 +1,137 @@
/**
* $Revision: 22540 $
* $Date: 2005-10-10 08:44:25 -0700 (Mon, 10 Oct 2005) $
*
* Copyright (C) 1999-2005 Jive Software. All rights reserved.
*
* This software is the proprietary information of Jive Software.
* Use is subject to license terms.
*/
package com.jivesoftware.spark.plugin.apple;
import com.apple.eawt.Application;
import com.apple.eawt.ApplicationAdapter;
import com.apple.eawt.ApplicationEvent;
import javax.swing.*;
import java.awt.*;
import org.jivesoftware.spark.plugin.Plugin;
import org.jivesoftware.spark.SparkManager;
import org.jivesoftware.spark.ui.ChatRoomListener;
import org.jivesoftware.MainWindow;
import org.jivesoftware.Spark;
/**
* Plugins for handling Mac OS X specific functionality
*
* @author Andrew Wright
*/
public class ApplePlugin implements Plugin {
private ChatRoomListener roomListener;
public void initialize() {
if (Spark.isMac()) {
roomListener = new DockRoomListener();
SparkManager.getChatManager().addChatRoomListener(roomListener);
// Remove the About Menu Item from the help menu
MainWindow mainWindow = SparkManager.getMainWindow();
JMenu helpMenu = mainWindow.getMenuByName("Help");
Component[] menuComponents = helpMenu.getMenuComponents();
Component prev = null;
for (int i = 0; i < menuComponents.length; i++) {
Component current = menuComponents[i];
if (current instanceof JMenuItem) {
JMenuItem item = (JMenuItem) current;
if ("About".equals(item.getText())) {
helpMenu.remove(item);
// We want to remove the seperator
if (prev != null && (prev instanceof JSeparator)) {
helpMenu.remove(prev);
}
}
}
prev = current;
}
JMenu connectMenu = mainWindow.getMenuByName("Spark");
connectMenu.setText("Connect");
menuComponents = connectMenu.getMenuComponents();
JSeparator lastSeperator = null;
for (int i = 0; i < menuComponents.length; i++) {
Component current = menuComponents[i];
if (current instanceof JMenuItem) {
JMenuItem item = (JMenuItem) current;
if ("Preferences".equals(item.getText())) {
- connectMenu.remove(item);
+ //connectMenu.remove(item);
} else if ("Log Out".equals(item.getText())) {
connectMenu.remove(item);
}
} else if (current instanceof JSeparator) {
lastSeperator = (JSeparator) current;
}
}
if (lastSeperator != null) {
connectMenu.remove(lastSeperator);
}
// register an application listener to show the about box
Application application = Application.getApplication();
- application.setEnabledPreferencesMenu(true);
- application.addPreferencesMenuItem();
+ // application.setEnabledPreferencesMenu(true);
+ // application.addPreferencesMenuItem();
application.addApplicationListener(new ApplicationAdapter() {
public void handlePreferences(ApplicationEvent applicationEvent) {
SparkManager.getPreferenceManager().showPreferences();
}
public void handleReOpenApplication(ApplicationEvent event) {
MainWindow mainWindow = SparkManager.getMainWindow();
if (!mainWindow.isVisible()) {
mainWindow.setState(Frame.NORMAL);
mainWindow.setVisible(true);
}
}
public void handleQuit(ApplicationEvent applicationEvent) {
System.exit(0);
}
});
new AppleStatusMenu().display();
}
}
public void shutdown() {
if (Spark.isMac()) {
SparkManager.getChatManager().removeChatRoomListener(roomListener);
roomListener = null;
}
}
public boolean canShutDown() {
return false;
}
public void uninstall() {
// No need, since this is internal
}
}
| false | true | public void initialize() {
if (Spark.isMac()) {
roomListener = new DockRoomListener();
SparkManager.getChatManager().addChatRoomListener(roomListener);
// Remove the About Menu Item from the help menu
MainWindow mainWindow = SparkManager.getMainWindow();
JMenu helpMenu = mainWindow.getMenuByName("Help");
Component[] menuComponents = helpMenu.getMenuComponents();
Component prev = null;
for (int i = 0; i < menuComponents.length; i++) {
Component current = menuComponents[i];
if (current instanceof JMenuItem) {
JMenuItem item = (JMenuItem) current;
if ("About".equals(item.getText())) {
helpMenu.remove(item);
// We want to remove the seperator
if (prev != null && (prev instanceof JSeparator)) {
helpMenu.remove(prev);
}
}
}
prev = current;
}
JMenu connectMenu = mainWindow.getMenuByName("Spark");
connectMenu.setText("Connect");
menuComponents = connectMenu.getMenuComponents();
JSeparator lastSeperator = null;
for (int i = 0; i < menuComponents.length; i++) {
Component current = menuComponents[i];
if (current instanceof JMenuItem) {
JMenuItem item = (JMenuItem) current;
if ("Preferences".equals(item.getText())) {
connectMenu.remove(item);
} else if ("Log Out".equals(item.getText())) {
connectMenu.remove(item);
}
} else if (current instanceof JSeparator) {
lastSeperator = (JSeparator) current;
}
}
if (lastSeperator != null) {
connectMenu.remove(lastSeperator);
}
// register an application listener to show the about box
Application application = Application.getApplication();
application.setEnabledPreferencesMenu(true);
application.addPreferencesMenuItem();
application.addApplicationListener(new ApplicationAdapter() {
public void handlePreferences(ApplicationEvent applicationEvent) {
SparkManager.getPreferenceManager().showPreferences();
}
public void handleReOpenApplication(ApplicationEvent event) {
MainWindow mainWindow = SparkManager.getMainWindow();
if (!mainWindow.isVisible()) {
mainWindow.setState(Frame.NORMAL);
mainWindow.setVisible(true);
}
}
public void handleQuit(ApplicationEvent applicationEvent) {
System.exit(0);
}
});
new AppleStatusMenu().display();
}
}
| public void initialize() {
if (Spark.isMac()) {
roomListener = new DockRoomListener();
SparkManager.getChatManager().addChatRoomListener(roomListener);
// Remove the About Menu Item from the help menu
MainWindow mainWindow = SparkManager.getMainWindow();
JMenu helpMenu = mainWindow.getMenuByName("Help");
Component[] menuComponents = helpMenu.getMenuComponents();
Component prev = null;
for (int i = 0; i < menuComponents.length; i++) {
Component current = menuComponents[i];
if (current instanceof JMenuItem) {
JMenuItem item = (JMenuItem) current;
if ("About".equals(item.getText())) {
helpMenu.remove(item);
// We want to remove the seperator
if (prev != null && (prev instanceof JSeparator)) {
helpMenu.remove(prev);
}
}
}
prev = current;
}
JMenu connectMenu = mainWindow.getMenuByName("Spark");
connectMenu.setText("Connect");
menuComponents = connectMenu.getMenuComponents();
JSeparator lastSeperator = null;
for (int i = 0; i < menuComponents.length; i++) {
Component current = menuComponents[i];
if (current instanceof JMenuItem) {
JMenuItem item = (JMenuItem) current;
if ("Preferences".equals(item.getText())) {
//connectMenu.remove(item);
} else if ("Log Out".equals(item.getText())) {
connectMenu.remove(item);
}
} else if (current instanceof JSeparator) {
lastSeperator = (JSeparator) current;
}
}
if (lastSeperator != null) {
connectMenu.remove(lastSeperator);
}
// register an application listener to show the about box
Application application = Application.getApplication();
// application.setEnabledPreferencesMenu(true);
// application.addPreferencesMenuItem();
application.addApplicationListener(new ApplicationAdapter() {
public void handlePreferences(ApplicationEvent applicationEvent) {
SparkManager.getPreferenceManager().showPreferences();
}
public void handleReOpenApplication(ApplicationEvent event) {
MainWindow mainWindow = SparkManager.getMainWindow();
if (!mainWindow.isVisible()) {
mainWindow.setState(Frame.NORMAL);
mainWindow.setVisible(true);
}
}
public void handleQuit(ApplicationEvent applicationEvent) {
System.exit(0);
}
});
new AppleStatusMenu().display();
}
}
|
diff --git a/src/main/java/com/bergerkiller/bukkit/tc/rails/logic/RailLogicSloped.java b/src/main/java/com/bergerkiller/bukkit/tc/rails/logic/RailLogicSloped.java
index 0f22089..7a45268 100644
--- a/src/main/java/com/bergerkiller/bukkit/tc/rails/logic/RailLogicSloped.java
+++ b/src/main/java/com/bergerkiller/bukkit/tc/rails/logic/RailLogicSloped.java
@@ -1,130 +1,131 @@
package com.bergerkiller.bukkit.tc.rails.logic;
import org.bukkit.block.Block;
import org.bukkit.block.BlockFace;
import org.bukkit.util.Vector;
import com.bergerkiller.bukkit.common.bases.IntVector3;
import com.bergerkiller.bukkit.common.entity.type.CommonMinecart;
import com.bergerkiller.bukkit.common.utils.FaceUtil;
import com.bergerkiller.bukkit.common.utils.MaterialUtil;
import com.bergerkiller.bukkit.tc.controller.MinecartGroup;
import com.bergerkiller.bukkit.tc.controller.MinecartMember;
/**
* Handles minecart movement on sloped rails
*/
public class RailLogicSloped extends RailLogicHorizontal {
private static final RailLogicSloped [] values = new RailLogicSloped[4];
static {
for (int i = 0; i < 4; i++) {
values[i] = new RailLogicSloped(FaceUtil.notchToFace(i << 1));
}
}
private final double dy, startY;
protected RailLogicSloped(BlockFace direction) {
super(direction);
if (direction == BlockFace.SOUTH || direction == BlockFace.EAST) {
this.dy = 1.0;
this.startY = 0.0;
} else {
this.dy = -1.0;
this.startY = 1.0;
}
}
@Override
public boolean isSloped() {
return true;
}
@Override
public void onPostMove(MinecartMember<?> member) {
final CommonMinecart<?> entity = member.getEntity();
// Adjust the Y-position of the Minecart on this slope and calculate velocity
int dx = member.getBlockPos().x - entity.loc.x.block();
int dz = member.getBlockPos().z - entity.loc.z.block();
if (dx == this.getDirection().getModX() && dz == this.getDirection().getModZ()) {
entity.loc.y.subtract(1.0);
}
RailLogic logic = member.getRailTracker().getLastLogic();
IntVector3 lastRailPos = new IntVector3(member.getRailTracker().getLastBlock());
// Get from and to rail-fixed positions
Vector startVector = logic.getFixedPosition(entity, entity.last, lastRailPos);
Vector endVector = getFixedPosition(entity, entity.loc, member.getBlockPos());
// Update fixed Y-position
entity.setPosition(entity.loc.getX(), endVector.getY(), entity.loc.getZ());
// Apply velocity factors from going up/down the slope
if (member.getGroup().getProperties().isSlowingDown()) {
final double motLength = entity.vel.xz.length();
if (motLength > 0) {
entity.vel.xz.multiply((startVector.getY() - endVector.getY()) * 0.05 / motLength + 1.0);
}
}
}
@Override
public Vector getFixedPosition(CommonMinecart<?> entity, double x, double y, double z, IntVector3 railPos) {
Vector pos = super.getFixedPosition(entity, x, y, z, railPos);
// Adjust the Y-position to match this rail
double stage = 0.0;
if (alongZ) {
stage = z - (double) railPos.z;
} else if (alongX) {
stage = x - (double) railPos.x;
}
pos.setY(railPos.midY() + startY + dy * stage);
return pos;
}
@Override
public void onPreMove(MinecartMember<?> member) {
final CommonMinecart<?> entity = member.getEntity();
MinecartGroup group = member.getGroup();
// Velocity modifier for sloped tracks
if (group.getProperties().isSlowingDown() && !member.isMovementControlled()) {
entity.vel.xz.subtract(this.getDirection(), MinecartMember.SLOPE_VELOCITY_MULTIPLIER);
}
entity.vel.xz.add(this.getDirection(), entity.vel.getY());
entity.vel.y.setZero();
// Stop movement if colliding with a block at the slope
double blockedDistance = Double.MAX_VALUE;
- Block heading = member.getBlock(this.getDirection().getOppositeFace());
+ Block inside = member.getRailType().findMinecartPos(member.getBlock());
+ Block heading = inside.getRelative(this.getDirection().getOppositeFace());
if (!member.isMoving() || member.isHeadingTo(this.getDirection().getOppositeFace())) {
if (MaterialUtil.SUFFOCATES.get(heading)) {
blockedDistance = entity.loc.xz.distance(heading) - 1.0;
}
} else if (member.isHeadingTo(this.getDirection())) {
- Block above = member.getBlock(BlockFace.UP);
+ Block above = inside.getRelative(BlockFace.UP);
if (MaterialUtil.SUFFOCATES.get(above)) {
blockedDistance = entity.loc.xz.distance(above);
}
}
if (entity.vel.xz.length() > blockedDistance) {
member.getGroup().setForwardForce(blockedDistance);
}
// Perform remaining positioning updates
super.onPreMove(member);
entity.loc.y.add(1.0);
}
/**
* Gets the sloped rail logic for the the sloped track leading up on the direction specified
*
* @param direction of the sloped rail
* @param wasVertical, whether it was a change from vertical to sloped
* @return Rail Logic
*/
public static RailLogicSloped get(BlockFace direction) {
return values[FaceUtil.faceToNotch(direction) >> 1];
}
}
| false | true | public void onPreMove(MinecartMember<?> member) {
final CommonMinecart<?> entity = member.getEntity();
MinecartGroup group = member.getGroup();
// Velocity modifier for sloped tracks
if (group.getProperties().isSlowingDown() && !member.isMovementControlled()) {
entity.vel.xz.subtract(this.getDirection(), MinecartMember.SLOPE_VELOCITY_MULTIPLIER);
}
entity.vel.xz.add(this.getDirection(), entity.vel.getY());
entity.vel.y.setZero();
// Stop movement if colliding with a block at the slope
double blockedDistance = Double.MAX_VALUE;
Block heading = member.getBlock(this.getDirection().getOppositeFace());
if (!member.isMoving() || member.isHeadingTo(this.getDirection().getOppositeFace())) {
if (MaterialUtil.SUFFOCATES.get(heading)) {
blockedDistance = entity.loc.xz.distance(heading) - 1.0;
}
} else if (member.isHeadingTo(this.getDirection())) {
Block above = member.getBlock(BlockFace.UP);
if (MaterialUtil.SUFFOCATES.get(above)) {
blockedDistance = entity.loc.xz.distance(above);
}
}
if (entity.vel.xz.length() > blockedDistance) {
member.getGroup().setForwardForce(blockedDistance);
}
// Perform remaining positioning updates
super.onPreMove(member);
entity.loc.y.add(1.0);
}
| public void onPreMove(MinecartMember<?> member) {
final CommonMinecart<?> entity = member.getEntity();
MinecartGroup group = member.getGroup();
// Velocity modifier for sloped tracks
if (group.getProperties().isSlowingDown() && !member.isMovementControlled()) {
entity.vel.xz.subtract(this.getDirection(), MinecartMember.SLOPE_VELOCITY_MULTIPLIER);
}
entity.vel.xz.add(this.getDirection(), entity.vel.getY());
entity.vel.y.setZero();
// Stop movement if colliding with a block at the slope
double blockedDistance = Double.MAX_VALUE;
Block inside = member.getRailType().findMinecartPos(member.getBlock());
Block heading = inside.getRelative(this.getDirection().getOppositeFace());
if (!member.isMoving() || member.isHeadingTo(this.getDirection().getOppositeFace())) {
if (MaterialUtil.SUFFOCATES.get(heading)) {
blockedDistance = entity.loc.xz.distance(heading) - 1.0;
}
} else if (member.isHeadingTo(this.getDirection())) {
Block above = inside.getRelative(BlockFace.UP);
if (MaterialUtil.SUFFOCATES.get(above)) {
blockedDistance = entity.loc.xz.distance(above);
}
}
if (entity.vel.xz.length() > blockedDistance) {
member.getGroup().setForwardForce(blockedDistance);
}
// Perform remaining positioning updates
super.onPreMove(member);
entity.loc.y.add(1.0);
}
|
diff --git a/src/main/java/net/oneandone/lavender/cli/War.java b/src/main/java/net/oneandone/lavender/cli/War.java
index cf96a32..3731a67 100644
--- a/src/main/java/net/oneandone/lavender/cli/War.java
+++ b/src/main/java/net/oneandone/lavender/cli/War.java
@@ -1,122 +1,122 @@
/**
* Copyright 1&1 Internet AG, https://github.com/1and1/
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.oneandone.lavender.cli;
import net.oneandone.lavender.config.Alias;
import net.oneandone.lavender.config.Cluster;
import net.oneandone.lavender.config.Docroot;
import net.oneandone.lavender.config.Net;
import net.oneandone.lavender.config.Pool;
import net.oneandone.lavender.config.Settings;
import net.oneandone.lavender.config.Target;
import net.oneandone.lavender.index.Distributor;
import net.oneandone.sushi.cli.ArgumentException;
import net.oneandone.sushi.cli.Console;
import net.oneandone.sushi.cli.Remaining;
import net.oneandone.sushi.cli.Value;
import net.oneandone.sushi.fs.file.FileNode;
import net.oneandone.sushi.xml.XmlException;
import org.xml.sax.SAXException;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
public class War extends Base {
@Value(name = "inputWar", position = 1)
private FileNode inputWar;
@Value(name = "outputWar", position = 2)
private FileNode outputWar;
@Value(name = "idxName", position = 3)
private String indexName;
private final Map<String, Target> targets = new HashMap<>();
private String nodes;
@Remaining
public void target(String keyvalue) {
int idx;
String type;
String clusterName;
String aliasName;
Cluster cluster;
Docroot docroot;
Alias alias;
idx = keyvalue.indexOf('=');
if (idx == -1) {
throw new ArgumentException("<type>=<cluster> expected, got " + keyvalue);
}
type = keyvalue.substring(0, idx);
clusterName = keyvalue.substring(idx + 1);
idx = clusterName.indexOf('/');
if (idx == -1) {
aliasName = null;
} else {
aliasName = clusterName.substring(idx + 1);
- clusterName = clusterName.substring(idx);
+ clusterName = clusterName.substring(0, idx);
}
cluster = net.get(clusterName);
docroot = cluster.docroot(type);
alias = aliasName == null ? docroot.aliases().get(0) : docroot.alias(aliasName);
if (Docroot.WEB.equals(type)) {
nodes = alias.nodesFile();
}
targets.put(type, new Target(cluster, docroot, alias));
}
public War(Console console, Settings settings, Net net) {
super(console, settings, net);
}
@Override
public void invoke() throws IOException, SAXException, XmlException {
FileNode tmp;
FileNode outputNodesFile;
WarEngine engine;
Map<String, Distributor> distributors;
if (targets.isEmpty()) {
throw new ArgumentException("missing targets");
}
if (nodes == null) {
throw new ArgumentException("missing web target");
}
inputWar.checkFile();
outputWar.checkNotExists();
tmp = inputWar.getWorld().getTemp();
outputNodesFile = tmp.createTempFile();
try (Pool pool = pool()) {
distributors = distributors(pool);
engine = new WarEngine(distributors, indexName, settings.svnUsername, settings.svnPassword,
inputWar, outputWar, outputNodesFile, nodes);
engine.run();
}
outputNodesFile.deleteFile();
}
private Map<String, Distributor> distributors(Pool pool) throws IOException {
Map<String, Distributor> result;
result = new HashMap<>();
for (Map.Entry<String, Target> entry : targets.entrySet()) {
result.put(entry.getKey(), entry.getValue().open(pool, indexName));
}
return result;
}
}
| true | true | public void target(String keyvalue) {
int idx;
String type;
String clusterName;
String aliasName;
Cluster cluster;
Docroot docroot;
Alias alias;
idx = keyvalue.indexOf('=');
if (idx == -1) {
throw new ArgumentException("<type>=<cluster> expected, got " + keyvalue);
}
type = keyvalue.substring(0, idx);
clusterName = keyvalue.substring(idx + 1);
idx = clusterName.indexOf('/');
if (idx == -1) {
aliasName = null;
} else {
aliasName = clusterName.substring(idx + 1);
clusterName = clusterName.substring(idx);
}
cluster = net.get(clusterName);
docroot = cluster.docroot(type);
alias = aliasName == null ? docroot.aliases().get(0) : docroot.alias(aliasName);
if (Docroot.WEB.equals(type)) {
nodes = alias.nodesFile();
}
targets.put(type, new Target(cluster, docroot, alias));
}
| public void target(String keyvalue) {
int idx;
String type;
String clusterName;
String aliasName;
Cluster cluster;
Docroot docroot;
Alias alias;
idx = keyvalue.indexOf('=');
if (idx == -1) {
throw new ArgumentException("<type>=<cluster> expected, got " + keyvalue);
}
type = keyvalue.substring(0, idx);
clusterName = keyvalue.substring(idx + 1);
idx = clusterName.indexOf('/');
if (idx == -1) {
aliasName = null;
} else {
aliasName = clusterName.substring(idx + 1);
clusterName = clusterName.substring(0, idx);
}
cluster = net.get(clusterName);
docroot = cluster.docroot(type);
alias = aliasName == null ? docroot.aliases().get(0) : docroot.alias(aliasName);
if (Docroot.WEB.equals(type)) {
nodes = alias.nodesFile();
}
targets.put(type, new Target(cluster, docroot, alias));
}
|
diff --git a/src/org/jruby/parser/DefaultRubyParser.java b/src/org/jruby/parser/DefaultRubyParser.java
index 86627aa88..13a851473 100644
--- a/src/org/jruby/parser/DefaultRubyParser.java
+++ b/src/org/jruby/parser/DefaultRubyParser.java
@@ -1,3445 +1,3445 @@
// line 2 "DefaultRubyParser.y"
/*
* DefaultRubyParser.java - JRuby - Parser constructed from parse.y
* Created on 07. Oktober 2001, 01:28
*
* Copyright (C) 2001 Jan Arne Petersen, Stefan Matthias Aust
* Jan Arne Petersen <[email protected]>
* Stefan Matthias Aust <[email protected]>
*
* JRuby - http://jruby.sourceforge.net
*
* This file is part of JRuby
*
* JRuby 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.
*
* JRuby 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 JRuby; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
*/
package org.jruby.parser;
import java.math.*;
import org.jruby.common.*;
import org.jruby.lexer.yacc.*;
import org.jruby.ast.*;
import org.jruby.ast.types.*;
import org.jruby.ast.util.*;
import org.jruby.runtime.*;
import org.jruby.util.*;
public class DefaultRubyParser {
private ParserSupport support;
private RubyYaccLexer lexer;
private IRubyErrorHandler errorHandler;
public DefaultRubyParser() {
this.support = new ParserSupport();
this.lexer = new RubyYaccLexer();
// lame
this.lexer.setParserSupport(support);
}
public void setErrorHandler(IRubyErrorHandler errorHandler) {
this.errorHandler = errorHandler;
support.setErrorHandler(errorHandler);
lexer.setErrorHandler(errorHandler);
}
/*
%union {
Node *node;
VALUE val;
ID id;
int num;
struct RVarmap *vars;
}
*/
// line 72 "-"
// %token constants
public static final int kCLASS = 257;
public static final int kMODULE = 258;
public static final int kDEF = 259;
public static final int kUNDEF = 260;
public static final int kBEGIN = 261;
public static final int kRESCUE = 262;
public static final int kENSURE = 263;
public static final int kEND = 264;
public static final int kIF = 265;
public static final int kUNLESS = 266;
public static final int kTHEN = 267;
public static final int kELSIF = 268;
public static final int kELSE = 269;
public static final int kCASE = 270;
public static final int kWHEN = 271;
public static final int kWHILE = 272;
public static final int kUNTIL = 273;
public static final int kFOR = 274;
public static final int kBREAK = 275;
public static final int kNEXT = 276;
public static final int kREDO = 277;
public static final int kRETRY = 278;
public static final int kIN = 279;
public static final int kDO = 280;
public static final int kDO_COND = 281;
public static final int kDO_BLOCK = 282;
public static final int kRETURN = 283;
public static final int kYIELD = 284;
public static final int kSUPER = 285;
public static final int kSELF = 286;
public static final int kNIL = 287;
public static final int kTRUE = 288;
public static final int kFALSE = 289;
public static final int kAND = 290;
public static final int kOR = 291;
public static final int kNOT = 292;
public static final int kIF_MOD = 293;
public static final int kUNLESS_MOD = 294;
public static final int kWHILE_MOD = 295;
public static final int kUNTIL_MOD = 296;
public static final int kRESCUE_MOD = 297;
public static final int kALIAS = 298;
public static final int kDEFINED = 299;
public static final int klBEGIN = 300;
public static final int klEND = 301;
public static final int k__LINE__ = 302;
public static final int k__FILE__ = 303;
public static final int tIDENTIFIER = 304;
public static final int tFID = 305;
public static final int tGVAR = 306;
public static final int tIVAR = 307;
public static final int tCONSTANT = 308;
public static final int tCVAR = 309;
public static final int tINTEGER = 310;
public static final int tFLOAT = 311;
public static final int tSTRING_CONTENT = 312;
public static final int tNTH_REF = 313;
public static final int tBACK_REF = 314;
public static final int tREGEXP_END = 315;
public static final int tUPLUS = 316;
public static final int tUMINUS = 317;
public static final int tPOW = 318;
public static final int tCMP = 319;
public static final int tEQ = 320;
public static final int tEQQ = 321;
public static final int tNEQ = 322;
public static final int tGEQ = 323;
public static final int tLEQ = 324;
public static final int tANDOP = 325;
public static final int tOROP = 326;
public static final int tMATCH = 327;
public static final int tNMATCH = 328;
public static final int tDOT2 = 329;
public static final int tDOT3 = 330;
public static final int tAREF = 331;
public static final int tASET = 332;
public static final int tLSHFT = 333;
public static final int tRSHFT = 334;
public static final int tCOLON2 = 335;
public static final int tCOLON3 = 336;
public static final int tOP_ASGN = 337;
public static final int tASSOC = 338;
public static final int tLPAREN = 339;
public static final int tLPAREN_ARG = 340;
public static final int tLBRACK = 341;
public static final int tLBRACE = 342;
public static final int tLBRACE_ARG = 343;
public static final int tSTAR = 344;
public static final int tAMPER = 345;
public static final int tSYMBEG = 346;
public static final int tSTRING_BEG = 347;
public static final int tXSTRING_BEG = 348;
public static final int tREGEXP_BEG = 349;
public static final int tWORDS_BEG = 350;
public static final int tQWORDS_BEG = 351;
public static final int tSTRING_DBEG = 352;
public static final int tSTRING_DVAR = 353;
public static final int tSTRING_END = 354;
public static final int tLOWEST = 355;
public static final int tUMINUS_NUM = 356;
public static final int tLAST_TOKEN = 357;
public static final int yyErrorCode = 256;
/** thrown for irrecoverable syntax errors and stack overflow.
*/
public static class yyException extends java.lang.Exception {
public yyException (String message) {
super(message);
}
}
/** simplified error message.
@see <a href="#yyerror(java.lang.String, java.lang.String[])">yyerror</a>
*/
public void yyerror (String message) {
yyerror(message, null);
}
/** (syntax) error message.
Can be overwritten to control message format.
@param message text to be displayed.
@param expected vector of acceptable tokens, if available.
*/
public void yyerror (String message, Object expected) {
// FIXME: in skeleton.jruby: postition
errorHandler.handleError(IErrors.SYNTAX_ERROR, getPosition(), message, expected);
}
/** debugging support, requires the package jay.yydebug.
Set to null to suppress debugging messages.
*/
protected static final int yyFinal = 1;
/** index-checked interface to yyName[].
@param token single character or %token value.
@return token name or [illegal] or [unknown].
*/
/** computes list of expected tokens on error by tracing the tables.
@param state for which to compute the list.
@return list of token names.
*/
protected String[] yyExpecting (int state) {
int token, n, len = 0;
boolean[] ok = new boolean[YyNameClass.yyName.length];
if ((n = YySindexClass.yySindex[state]) != 0)
for (token = n < 0 ? -n : 0;
token < YyNameClass.yyName.length && n+token < YyTableClass.yyTable.length; ++ token)
if (YyCheckClass.yyCheck[n+token] == token && !ok[token] && YyNameClass.yyName[token] != null) {
++ len;
ok[token] = true;
}
if ((n = YyRindexClass.yyRindex[state]) != 0)
for (token = n < 0 ? -n : 0;
token < YyNameClass.yyName.length && n+token < YyTableClass.yyTable.length; ++ token)
if (YyCheckClass.yyCheck[n+token] == token && !ok[token] && YyNameClass.yyName[token] != null) {
++ len;
ok[token] = true;
}
String result[] = new String[len];
for (n = token = 0; n < len; ++ token)
if (ok[token]) result[n++] = YyNameClass.yyName[token];
return result;
}
/** the generated parser, with debugging messages.
Maintains a state and a value stack, currently with fixed maximum size.
@param yyLex The lexer.
@param yydebug debug message writer implementing yyDebug, or null.
@return result of the last reduction, if any.
@throws yyException on irrecoverable parse error.
*/
public Object yyparse (RubyYaccLexer yyLex, Object yydebug)
throws java.io.IOException, yyException {
return yyparse(yyLex);
}
/** initial size and increment of the state/value stack [default 256].
This is not final so that it can be overwritten outside of invocations
of yyparse().
*/
protected int yyMax;
/** executed at the beginning of a reduce action.
Used as $$ = yyDefault($1), prior to the user-specified action, if any.
Can be overwritten to provide deep copy, etc.
@param first value for $1, or null.
@return first.
*/
protected Object yyDefault (Object first) {
return first;
}
/** the generated parser.
Maintains a state and a value stack, currently with fixed maximum size.
@param yyLex The lexer.
@return result of the last reduction, if any.
@throws yyException on irrecoverable parse error.
*/
public Object yyparse (RubyYaccLexer yyLex)
throws java.io.IOException, yyException {
if (yyMax <= 0) yyMax = 256; // initial size
int yyState = 0, yyStates[] = new int[yyMax]; // state stack
Object yyVal = null, yyVals[] = new Object[yyMax]; // value stack
int yyToken = -1; // current input
int yyErrorFlag = 0; // #tks to shift
yyLoop: for (int yyTop = 0;; ++ yyTop) {
if (yyTop >= yyStates.length) { // dynamically increase
int[] i = new int[yyStates.length+yyMax];
System.arraycopy(yyStates, 0, i, 0, yyStates.length);
yyStates = i;
Object[] o = new Object[yyVals.length+yyMax];
System.arraycopy(yyVals, 0, o, 0, yyVals.length);
yyVals = o;
}
yyStates[yyTop] = yyState;
yyVals[yyTop] = yyVal;
yyDiscarded: for (;;) { // discarding a token does not change stack
int yyN;
if ((yyN = YyDefRedClass.yyDefRed[yyState]) == 0) { // else [default] reduce (yyN)
if (yyToken < 0) {
yyToken = yyLex.advance() ? yyLex.token() : 0;
}
if ((yyN = YySindexClass.yySindex[yyState]) != 0 && (yyN += yyToken) >= 0
&& yyN < YyTableClass.yyTable.length && YyCheckClass.yyCheck[yyN] == yyToken) {
yyState = YyTableClass.yyTable[yyN]; // shift to yyN
yyVal = yyLex.value();
yyToken = -1;
if (yyErrorFlag > 0) -- yyErrorFlag;
continue yyLoop;
}
if ((yyN = YyRindexClass.yyRindex[yyState]) != 0 && (yyN += yyToken) >= 0
&& yyN < YyTableClass.yyTable.length && YyCheckClass.yyCheck[yyN] == yyToken)
yyN = YyTableClass.yyTable[yyN]; // reduce (yyN)
else
switch (yyErrorFlag) {
case 0:
yyerror("syntax error", new SyntaxErrorState(yyExpecting(yyState), YyNameClass.yyName[yyToken]));
case 1: case 2:
yyErrorFlag = 3;
do {
if ((yyN = YySindexClass.yySindex[yyStates[yyTop]]) != 0
&& (yyN += yyErrorCode) >= 0 && yyN < YyTableClass.yyTable.length
&& YyCheckClass.yyCheck[yyN] == yyErrorCode) {
yyState = YyTableClass.yyTable[yyN];
yyVal = yyLex.value();
continue yyLoop;
}
} while (-- yyTop >= 0);
throw new yyException("irrecoverable syntax error");
case 3:
if (yyToken == 0) {
throw new yyException("irrecoverable syntax error at end-of-file");
}
yyToken = -1;
continue yyDiscarded; // leave stack alone
}
}
int yyV = yyTop + 1-YyLenClass.yyLen[yyN];
yyVal = yyDefault(yyV > yyTop ? null : yyVals[yyV]);
switch (yyN) {
case 1:
// line 214 "DefaultRubyParser.y"
{
lexer.setState(LexState.EXPR_BEG);
support.initTopLocalVariables();
/* Fix: Move to ruby runtime....?*/
/*if (ruby.getRubyClass() == ruby.getClasses().getObjectClass()) {*/
/* support.setClassNest(0);*/
/*} else {*/
/* support.setClassNest(1);*/
/*}*/
}
break;
case 2:
// line 224 "DefaultRubyParser.y"
{
if (((Node)yyVals[0+yyTop]) != null && !support.isCompileForEval()) {
/* last expression should not be void */
if (((Node)yyVals[0+yyTop]) instanceof BlockNode) {
support.checkUselessStatement(ListNodeUtil.getLast(((BlockNode)yyVals[0+yyTop])));
} else {
support.checkUselessStatement(((Node)yyVals[0+yyTop]));
}
}
support.getResult().setAST(support.appendToBlock(support.getResult().getAST(), ((Node)yyVals[0+yyTop])));
support.updateTopLocalVariables();
support.setClassNest(0);
}
break;
case 3:
// line 241 "DefaultRubyParser.y"
{
Node node = ((Node)yyVals[-3+yyTop]);
if (((RescueBodyNode)yyVals[-2+yyTop]) != null) {
node = new RescueNode(getPosition(), ((Node)yyVals[-3+yyTop]), ((RescueBodyNode)yyVals[-2+yyTop]), ((Node)yyVals[-1+yyTop]));
} else if (((Node)yyVals[-1+yyTop]) != null) {
errorHandler.handleError(IErrors.WARN, null, "else without rescue is useless");
node = support.appendToBlock(((Node)yyVals[-3+yyTop]), ((Node)yyVals[-1+yyTop]));
}
if (((Node)yyVals[0+yyTop]) != null) {
node = new EnsureNode(getPosition(), node, ((Node)yyVals[0+yyTop]));
}
yyVal = node;
}
break;
case 4:
// line 257 "DefaultRubyParser.y"
{
if (((Node)yyVals[-1+yyTop]) instanceof BlockNode) {
support.checkUselessStatements(((BlockNode)yyVals[-1+yyTop]));
}
yyVal = ((Node)yyVals[-1+yyTop]);
}
break;
case 6:
// line 265 "DefaultRubyParser.y"
{
yyVal = support.newline_node(((Node)yyVals[0+yyTop]), getPosition());
}
break;
case 7:
// line 268 "DefaultRubyParser.y"
{
yyVal = support.appendToBlock(((Node)yyVals[-2+yyTop]), support.newline_node(((Node)yyVals[0+yyTop]), getPosition()));
}
break;
case 8:
// line 271 "DefaultRubyParser.y"
{
yyVal = ((Node)yyVals[0+yyTop]);
}
break;
case 9:
// line 275 "DefaultRubyParser.y"
{
lexer.setState(LexState.EXPR_FNAME);
}
break;
case 10:
// line 277 "DefaultRubyParser.y"
{
yyVal = new AliasNode(getPosition(), ((String)yyVals[-2+yyTop]), ((String)yyVals[0+yyTop]));
}
break;
case 11:
// line 280 "DefaultRubyParser.y"
{
yyVal = new VAliasNode(getPosition(), ((String)yyVals[-1+yyTop]), ((String)yyVals[0+yyTop]));
}
break;
case 12:
// line 283 "DefaultRubyParser.y"
{
yyVal = new VAliasNode(getPosition(), ((String)yyVals[-1+yyTop]), "$" + ((BackRefNode)yyVals[0+yyTop]).getType()); /* XXX*/
}
break;
case 13:
// line 286 "DefaultRubyParser.y"
{
yyerror("can't make alias for the number variables");
yyVal = null; /*XXX 0*/
}
break;
case 14:
// line 290 "DefaultRubyParser.y"
{
yyVal = ((Node)yyVals[0+yyTop]);
}
break;
case 15:
// line 293 "DefaultRubyParser.y"
{
yyVal = new IfNode(getPosition(), support.getConditionNode(((Node)yyVals[0+yyTop])), ((Node)yyVals[-2+yyTop]), null);
}
break;
case 16:
// line 296 "DefaultRubyParser.y"
{
yyVal = new IfNode(getPosition(), support.getConditionNode(((Node)yyVals[0+yyTop])), null, ((Node)yyVals[-2+yyTop]));
}
break;
case 17:
// line 299 "DefaultRubyParser.y"
{
if (((Node)yyVals[-2+yyTop]) != null && ((Node)yyVals[-2+yyTop]) instanceof BeginNode) {
yyVal = new WhileNode(getPosition(), support.getConditionNode(((Node)yyVals[0+yyTop])), ((BeginNode)yyVals[-2+yyTop]).getBodyNode(), false);
} else {
- yyVal = new WhileNode(getPosition(), support.getConditionNode(((Node)yyVals[0+yyTop])), ((Node)yyVals[-2+yyTop]), false);
+ yyVal = new WhileNode(getPosition(), support.getConditionNode(((Node)yyVals[0+yyTop])), ((Node)yyVals[-2+yyTop]), true);
}
}
break;
case 18:
// line 306 "DefaultRubyParser.y"
{
if (((Node)yyVals[-2+yyTop]) != null && ((Node)yyVals[-2+yyTop]) instanceof BeginNode) {
yyVal = new UntilNode(getPosition(), support.getConditionNode(((Node)yyVals[0+yyTop])), ((BeginNode)yyVals[-2+yyTop]).getBodyNode());
} else {
yyVal = new UntilNode(getPosition(), support.getConditionNode(((Node)yyVals[0+yyTop])), ((Node)yyVals[-2+yyTop]));
}
}
break;
case 19:
// line 314 "DefaultRubyParser.y"
{
yyVal = new RescueNode(getPosition(), ((Node)yyVals[-2+yyTop]), new RescueBodyNode(getPosition(), null,((Node)yyVals[0+yyTop]), null), null);
}
break;
case 20:
// line 318 "DefaultRubyParser.y"
{
if (support.isInDef() || support.isInSingle()) {
yyerror("BEGIN in method");
}
support.getLocalNames().push();
}
break;
case 21:
// line 323 "DefaultRubyParser.y"
{
support.getResult().setBeginNodes(support.appendToBlock(support.getResult().getBeginNodes(), new ScopeNode(support.getLocalNames().getNames(), ((Node)yyVals[-1+yyTop]))));
support.getLocalNames().pop();
yyVal = null; /*XXX 0;*/
}
break;
case 22:
// line 328 "DefaultRubyParser.y"
{
if (support.isInDef() || support.isInSingle()) {
yyerror("END in method; use at_exit");
}
yyVal = new IterNode(getPosition(), null, new PostExeNode(getPosition()), ((Node)yyVals[-1+yyTop]));
}
break;
case 23:
// line 334 "DefaultRubyParser.y"
{
support.checkExpression(((Node)yyVals[0+yyTop]));
yyVal = support.node_assign(((Node)yyVals[-2+yyTop]), ((Node)yyVals[0+yyTop]));
}
break;
case 24:
// line 338 "DefaultRubyParser.y"
{
support.checkExpression(((Node)yyVals[0+yyTop]));
if (((MultipleAsgnNode)yyVals[-2+yyTop]).getHeadNode() != null) {
((MultipleAsgnNode)yyVals[-2+yyTop]).setValueNode(new ToAryNode(getPosition(), ((Node)yyVals[0+yyTop])));
} else {
((MultipleAsgnNode)yyVals[-2+yyTop]).setValueNode(new ArrayNode(getPosition()).add(((Node)yyVals[0+yyTop])));
}
yyVal = ((MultipleAsgnNode)yyVals[-2+yyTop]);
}
break;
case 25:
// line 347 "DefaultRubyParser.y"
{
support.checkExpression(((Node)yyVals[0+yyTop]));
if (yyVals[-2+yyTop] != null) {
String name = ((INameNode)yyVals[-2+yyTop]).getName();
if (((String)yyVals[-1+yyTop]).equals("||")) {
((AssignableNode)yyVals[-2+yyTop]).setValueNode(((Node)yyVals[0+yyTop]));
yyVal = new OpAsgnOrNode(getPosition(), support.gettable(name, getPosition()), ((Node)yyVals[-2+yyTop]));
/* XXX
if (is_asgn_or_id(vid)) {
$$->nd_aid = vid;
}
*/
} else if (((String)yyVals[-1+yyTop]).equals("&&")) {
((AssignableNode)yyVals[-2+yyTop]).setValueNode(((Node)yyVals[0+yyTop]));
yyVal = new OpAsgnAndNode(getPosition(), support.gettable(name, getPosition()), ((Node)yyVals[-2+yyTop]));
} else {
yyVal = yyVals[-2+yyTop];
if (yyVal != null) {
((AssignableNode)yyVal).setValueNode(support.getOperatorCallNode(support.gettable(name, getPosition()), ((String)yyVals[-1+yyTop]), ((Node)yyVals[0+yyTop])));
}
}
} else {
yyVal = null;
}
}
break;
case 26:
// line 372 "DefaultRubyParser.y"
{
/* Much smaller than ruby block */
yyVal = new OpElementAsgnNode(getPosition(), ((Node)yyVals[-5+yyTop]), ((String)yyVals[-1+yyTop]), ((Node)yyVals[-3+yyTop]), ((Node)yyVals[0+yyTop]));
}
break;
case 27:
// line 377 "DefaultRubyParser.y"
{
yyVal = new OpAsgnNode(getPosition(), ((Node)yyVals[-4+yyTop]), ((Node)yyVals[0+yyTop]), ((String)yyVals[-2+yyTop]), ((String)yyVals[-1+yyTop]));
}
break;
case 28:
// line 380 "DefaultRubyParser.y"
{
yyVal = new OpAsgnNode(getPosition(), ((Node)yyVals[-4+yyTop]), ((Node)yyVals[0+yyTop]), ((String)yyVals[-2+yyTop]), ((String)yyVals[-1+yyTop]));
}
break;
case 29:
// line 383 "DefaultRubyParser.y"
{
yyVal = new OpAsgnNode(getPosition(), ((Node)yyVals[-4+yyTop]), ((Node)yyVals[0+yyTop]), ((String)yyVals[-2+yyTop]), ((String)yyVals[-1+yyTop]));
}
break;
case 30:
// line 386 "DefaultRubyParser.y"
{
support.backrefAssignError(((Node)yyVals[-2+yyTop]));
yyVal = null;
}
break;
case 31:
// line 390 "DefaultRubyParser.y"
{
yyVal = support.node_assign(((Node)yyVals[-2+yyTop]), new SValueNode(getPosition(), ((Node)yyVals[0+yyTop])));
}
break;
case 32:
// line 393 "DefaultRubyParser.y"
{
if (((MultipleAsgnNode)yyVals[-2+yyTop]).getHeadNode() != null) {
((MultipleAsgnNode)yyVals[-2+yyTop]).setValueNode(new ToAryNode(getPosition(), ((Node)yyVals[0+yyTop])));
} else {
((MultipleAsgnNode)yyVals[-2+yyTop]).setValueNode(new ArrayNode(getPosition()).add(((Node)yyVals[0+yyTop])));
}
yyVal = ((MultipleAsgnNode)yyVals[-2+yyTop]);
}
break;
case 33:
// line 401 "DefaultRubyParser.y"
{
((AssignableNode)yyVals[-2+yyTop]).setValueNode(((Node)yyVals[0+yyTop]));
yyVal = ((MultipleAsgnNode)yyVals[-2+yyTop]);
}
break;
case 36:
// line 408 "DefaultRubyParser.y"
{
yyVal = support.newAndNode(((Node)yyVals[-2+yyTop]), ((Node)yyVals[0+yyTop]));
}
break;
case 37:
// line 411 "DefaultRubyParser.y"
{
yyVal = support.newOrNode(((Node)yyVals[-2+yyTop]), ((Node)yyVals[0+yyTop]));
}
break;
case 38:
// line 414 "DefaultRubyParser.y"
{
yyVal = new NotNode(getPosition(), support.getConditionNode(((Node)yyVals[0+yyTop])));
}
break;
case 39:
// line 417 "DefaultRubyParser.y"
{
yyVal = new NotNode(getPosition(), support.getConditionNode(((Node)yyVals[0+yyTop])));
}
break;
case 41:
// line 422 "DefaultRubyParser.y"
{
support.checkExpression(((Node)yyVals[0+yyTop]));
yyVal = ((Node)yyVals[0+yyTop]); /*Do we really need this set? $1 is $$?*/
}
break;
case 44:
// line 429 "DefaultRubyParser.y"
{
yyVal = new ReturnNode(getPosition(), support.ret_args(((Node)yyVals[0+yyTop]), getPosition()));
}
break;
case 45:
// line 432 "DefaultRubyParser.y"
{
yyVal = new BreakNode(getPosition(), support.ret_args(((Node)yyVals[0+yyTop]), getPosition()));
}
break;
case 46:
// line 435 "DefaultRubyParser.y"
{
yyVal = new NextNode(getPosition(), support.ret_args(((Node)yyVals[0+yyTop]), getPosition()));
}
break;
case 48:
// line 440 "DefaultRubyParser.y"
{
yyVal = support.new_call(((Node)yyVals[-3+yyTop]), ((String)yyVals[-1+yyTop]), ((Node)yyVals[0+yyTop]));
}
break;
case 49:
// line 443 "DefaultRubyParser.y"
{
yyVal = support.new_call(((Node)yyVals[-3+yyTop]), ((String)yyVals[-1+yyTop]), ((Node)yyVals[0+yyTop]));
}
break;
case 50:
// line 447 "DefaultRubyParser.y"
{
support.getBlockNames().push();
}
break;
case 51:
// line 449 "DefaultRubyParser.y"
{
yyVal = new IterNode(getPosition(), ((Node)yyVals[-2+yyTop]), ((Node)yyVals[-1+yyTop]), null);
support.getBlockNames().pop();
}
break;
case 52:
// line 454 "DefaultRubyParser.y"
{
yyVal = support.new_fcall(((String)yyVals[-1+yyTop]), ((Node)yyVals[0+yyTop]), getPosition()); /* .setPosFrom($2);*/
}
break;
case 53:
// line 457 "DefaultRubyParser.y"
{
yyVal = support.new_fcall(((String)yyVals[-2+yyTop]), ((Node)yyVals[-1+yyTop]), getPosition());
if (((IterNode)yyVals[0+yyTop]) != null) {
if (yyVal instanceof BlockPassNode) {
errorHandler.handleError(IErrors.COMPILE_ERROR, null, "Both block arg and actual block given.");
}
((IterNode)yyVals[0+yyTop]).setIterNode(((Node)yyVal));
yyVal = ((Node)yyVals[-1+yyTop]);
}
}
break;
case 54:
// line 467 "DefaultRubyParser.y"
{
yyVal = support.new_call(((Node)yyVals[-3+yyTop]), ((String)yyVals[-1+yyTop]), ((Node)yyVals[0+yyTop])); /*.setPosFrom($1);*/
}
break;
case 55:
// line 470 "DefaultRubyParser.y"
{
yyVal = support.new_call(((Node)yyVals[-4+yyTop]), ((String)yyVals[-2+yyTop]), ((Node)yyVals[-1+yyTop]));
if (((IterNode)yyVals[0+yyTop]) != null) {
if (yyVal instanceof BlockPassNode) {
errorHandler.handleError(IErrors.COMPILE_ERROR, null, "Both block arg and actual block given.");
}
((IterNode)yyVals[0+yyTop]).setIterNode(((Node)yyVal));
yyVal = ((IterNode)yyVals[0+yyTop]);
}
}
break;
case 56:
// line 480 "DefaultRubyParser.y"
{
yyVal = support.new_call(((Node)yyVals[-3+yyTop]), ((String)yyVals[-1+yyTop]), ((Node)yyVals[0+yyTop]));
}
break;
case 57:
// line 483 "DefaultRubyParser.y"
{
yyVal = support.new_call(((Node)yyVals[-4+yyTop]), ((String)yyVals[-2+yyTop]), ((Node)yyVals[-1+yyTop]));
if (((IterNode)yyVals[0+yyTop]) != null) {
if (yyVal instanceof BlockPassNode) {
errorHandler.handleError(IErrors.COMPILE_ERROR, null, "Both block arg and actual block given.");
}
((IterNode)yyVals[0+yyTop]).setIterNode(((Node)yyVal));
yyVal = ((IterNode)yyVals[0+yyTop]);
}
}
break;
case 58:
// line 493 "DefaultRubyParser.y"
{
yyVal = support.new_super(((Node)yyVals[0+yyTop]), getPosition()); /* .setPosFrom($2);*/
}
break;
case 59:
// line 496 "DefaultRubyParser.y"
{
yyVal = support.new_yield(getPosition(), ((Node)yyVals[0+yyTop]));
}
break;
case 61:
// line 501 "DefaultRubyParser.y"
{
yyVal = ((MultipleAsgnNode)yyVals[-1+yyTop]);
}
break;
case 63:
// line 506 "DefaultRubyParser.y"
{
yyVal = new MultipleAsgnNode(getPosition(), new ArrayNode(getPosition()).add(((MultipleAsgnNode)yyVals[-1+yyTop])), null);
}
break;
case 64:
// line 510 "DefaultRubyParser.y"
{
yyVal = new MultipleAsgnNode(getPosition(), ((ListNode)yyVals[0+yyTop]), null);
}
break;
case 65:
// line 513 "DefaultRubyParser.y"
{
yyVal = new MultipleAsgnNode(getPosition(), ((ListNode)yyVals[-1+yyTop]).add(((Node)yyVals[0+yyTop])), null);
}
break;
case 66:
// line 516 "DefaultRubyParser.y"
{
yyVal = new MultipleAsgnNode(getPosition(), ((ListNode)yyVals[-2+yyTop]), ((Node)yyVals[0+yyTop]));
}
break;
case 67:
// line 519 "DefaultRubyParser.y"
{
yyVal = new MultipleAsgnNode(getPosition(), ((ListNode)yyVals[-1+yyTop]), new StarNode());
}
break;
case 68:
// line 522 "DefaultRubyParser.y"
{
yyVal = new MultipleAsgnNode(getPosition(), null, ((Node)yyVals[0+yyTop]));
}
break;
case 69:
// line 525 "DefaultRubyParser.y"
{
yyVal = new MultipleAsgnNode(getPosition(), null, new StarNode());
}
break;
case 71:
// line 530 "DefaultRubyParser.y"
{
yyVal = ((MultipleAsgnNode)yyVals[-1+yyTop]);
}
break;
case 72:
// line 534 "DefaultRubyParser.y"
{
yyVal = new ArrayNode(getPosition()).add(((Node)yyVals[-1+yyTop]));
}
break;
case 73:
// line 537 "DefaultRubyParser.y"
{
yyVal = ((ListNode)yyVals[-2+yyTop]).add(((Node)yyVals[-1+yyTop]));
}
break;
case 74:
// line 541 "DefaultRubyParser.y"
{
yyVal = support.assignable(getPosition(), yyVals[0+yyTop], null);
}
break;
case 75:
// line 544 "DefaultRubyParser.y"
{
yyVal = support.getElementAssignmentNode(((Node)yyVals[-3+yyTop]), ((Node)yyVals[-1+yyTop]));
}
break;
case 76:
// line 547 "DefaultRubyParser.y"
{
yyVal = support.getAttributeAssignmentNode(((Node)yyVals[-2+yyTop]), ((String)yyVals[0+yyTop]));
}
break;
case 77:
// line 550 "DefaultRubyParser.y"
{
yyVal = support.getAttributeAssignmentNode(((Node)yyVals[-2+yyTop]), ((String)yyVals[0+yyTop]));
}
break;
case 78:
// line 553 "DefaultRubyParser.y"
{
yyVal = support.getAttributeAssignmentNode(((Node)yyVals[-2+yyTop]), ((String)yyVals[0+yyTop]));
}
break;
case 79:
// line 556 "DefaultRubyParser.y"
{
if (support.isInDef() || support.isInSingle()) {
yyerror("dynamic constant assignment");
}
yyVal = support.getAttributeAssignmentNode(((Node)yyVals[-2+yyTop]), ((String)yyVals[0+yyTop]));
}
break;
case 80:
// line 563 "DefaultRubyParser.y"
{
if (support.isInDef() || support.isInSingle()) {
yyerror("dynamic constant assignment");
}
/* ERROR: VEry likely a big error. */
yyVal = new Colon3Node(getPosition(), ((String)yyVals[0+yyTop]));
/* ruby $$ = NEW_CDECL(0, 0, NEW_COLON3($2)); */
}
break;
case 81:
// line 573 "DefaultRubyParser.y"
{
support.backrefAssignError(((Node)yyVals[0+yyTop]));
yyVal = null;
}
break;
case 82:
// line 578 "DefaultRubyParser.y"
{
yyVal = support.assignable(getPosition(), yyVals[0+yyTop], null);
}
break;
case 83:
// line 581 "DefaultRubyParser.y"
{
yyVal = support.getElementAssignmentNode(((Node)yyVals[-3+yyTop]), ((Node)yyVals[-1+yyTop]));
}
break;
case 84:
// line 584 "DefaultRubyParser.y"
{
yyVal = support.getAttributeAssignmentNode(((Node)yyVals[-2+yyTop]), ((String)yyVals[0+yyTop]));
}
break;
case 85:
// line 587 "DefaultRubyParser.y"
{
yyVal = support.getAttributeAssignmentNode(((Node)yyVals[-2+yyTop]), ((String)yyVals[0+yyTop]));
}
break;
case 86:
// line 590 "DefaultRubyParser.y"
{
yyVal = support.getAttributeAssignmentNode(((Node)yyVals[-2+yyTop]), ((String)yyVals[0+yyTop]));
}
break;
case 87:
// line 593 "DefaultRubyParser.y"
{
if (support.isInDef() || support.isInSingle()) {
yyerror("dynamic constant assignment");
}
yyVal = support.getAttributeAssignmentNode(((Node)yyVals[-2+yyTop]), ((String)yyVals[0+yyTop]));
}
break;
case 88:
// line 600 "DefaultRubyParser.y"
{
if (support.isInDef() || support.isInSingle()) {
yyerror("dynamic constant assignment");
}
/* ERROR: VEry likely a big error. */
yyVal = new Colon3Node(getPosition(), ((String)yyVals[0+yyTop]));
/* ruby $$ = NEW_CDECL(0, 0, NEW_COLON3($2)); */
}
break;
case 89:
// line 609 "DefaultRubyParser.y"
{
support.backrefAssignError(((Node)yyVals[0+yyTop]));
yyVal = null;
}
break;
case 90:
// line 614 "DefaultRubyParser.y"
{
yyerror("class/module name must be CONSTANT");
}
break;
case 92:
// line 619 "DefaultRubyParser.y"
{
yyVal = new Colon2Node(getPosition(), null, ((String)yyVals[0+yyTop]));
}
break;
case 93:
// line 622 "DefaultRubyParser.y"
{
/* $1 was $$ in ruby?*/
yyVal = new Colon2Node(getPosition(), null, ((String)yyVals[0+yyTop]));
}
break;
case 94:
// line 626 "DefaultRubyParser.y"
{
yyVal = new Colon2Node(getPosition(), ((Node)yyVals[-2+yyTop]), ((String)yyVals[0+yyTop]));
}
break;
case 98:
// line 633 "DefaultRubyParser.y"
{
lexer.setState(LexState.EXPR_END);
yyVal = ((String)yyVals[0+yyTop]);
}
break;
case 99:
// line 637 "DefaultRubyParser.y"
{
lexer.setState(LexState.EXPR_END);
yyVal = yyVals[0+yyTop];
}
break;
case 102:
// line 645 "DefaultRubyParser.y"
{
yyVal = new UndefNode(getPosition(), ((String)yyVals[0+yyTop]));
}
break;
case 103:
// line 648 "DefaultRubyParser.y"
{
lexer.setState(LexState.EXPR_FNAME);
}
break;
case 104:
// line 650 "DefaultRubyParser.y"
{
yyVal = support.appendToBlock(((Node)yyVals[-3+yyTop]), new UndefNode(getPosition(), ((String)yyVals[0+yyTop])));
}
break;
case 105:
// line 654 "DefaultRubyParser.y"
{ yyVal = "|"; }
break;
case 106:
// line 655 "DefaultRubyParser.y"
{ yyVal = "^"; }
break;
case 107:
// line 656 "DefaultRubyParser.y"
{ yyVal = "&"; }
break;
case 108:
// line 657 "DefaultRubyParser.y"
{ yyVal = "<=>"; }
break;
case 109:
// line 658 "DefaultRubyParser.y"
{ yyVal = "=="; }
break;
case 110:
// line 659 "DefaultRubyParser.y"
{ yyVal = "==="; }
break;
case 111:
// line 660 "DefaultRubyParser.y"
{ yyVal = "=~"; }
break;
case 112:
// line 661 "DefaultRubyParser.y"
{ yyVal = ">"; }
break;
case 113:
// line 662 "DefaultRubyParser.y"
{ yyVal = ">="; }
break;
case 114:
// line 663 "DefaultRubyParser.y"
{ yyVal = "<"; }
break;
case 115:
// line 664 "DefaultRubyParser.y"
{ yyVal = "<="; }
break;
case 116:
// line 665 "DefaultRubyParser.y"
{ yyVal = "<<"; }
break;
case 117:
// line 666 "DefaultRubyParser.y"
{ yyVal = ">>"; }
break;
case 118:
// line 667 "DefaultRubyParser.y"
{ yyVal = "+"; }
break;
case 119:
// line 668 "DefaultRubyParser.y"
{ yyVal = "-"; }
break;
case 120:
// line 669 "DefaultRubyParser.y"
{ yyVal = "*"; }
break;
case 121:
// line 670 "DefaultRubyParser.y"
{ yyVal = "*"; }
break;
case 122:
// line 671 "DefaultRubyParser.y"
{ yyVal = "/"; }
break;
case 123:
// line 672 "DefaultRubyParser.y"
{ yyVal = "%"; }
break;
case 124:
// line 673 "DefaultRubyParser.y"
{ yyVal = "**"; }
break;
case 125:
// line 674 "DefaultRubyParser.y"
{ yyVal = "~"; }
break;
case 126:
// line 675 "DefaultRubyParser.y"
{ yyVal = "+@"; }
break;
case 127:
// line 676 "DefaultRubyParser.y"
{ yyVal = "-@"; }
break;
case 128:
// line 677 "DefaultRubyParser.y"
{ yyVal = "[]"; }
break;
case 129:
// line 678 "DefaultRubyParser.y"
{ yyVal = "[]="; }
break;
case 130:
// line 679 "DefaultRubyParser.y"
{ yyVal = "`"; }
break;
case 172:
// line 690 "DefaultRubyParser.y"
{
yyVal = support.node_assign(((Node)yyVals[-2+yyTop]), ((Node)yyVals[0+yyTop]));
}
break;
case 173:
// line 693 "DefaultRubyParser.y"
{
yyVal = support.node_assign(((Node)yyVals[-4+yyTop]), new RescueNode(getPosition(), ((Node)yyVals[-2+yyTop]), new RescueBodyNode(getPosition(), null,((Node)yyVals[0+yyTop]), null), null));
}
break;
case 174:
// line 696 "DefaultRubyParser.y"
{
support.checkExpression(((Node)yyVals[0+yyTop]));
if (yyVals[-2+yyTop] != null) {
String name = ((INameNode)yyVals[-2+yyTop]).getName();
if (((String)yyVals[-1+yyTop]).equals("||")) {
((AssignableNode)yyVals[-2+yyTop]).setValueNode(((Node)yyVals[0+yyTop]));
yyVal = new OpAsgnOrNode(getPosition(), support.gettable(name, getPosition()), ((Node)yyVals[-2+yyTop]));
/* FIXME
if (is_asgn_or_id(vid)) {
$$->nd_aid = vid;
}
*/
} else if (((String)yyVals[-1+yyTop]).equals("&&")) {
((AssignableNode)yyVals[-2+yyTop]).setValueNode(((Node)yyVals[0+yyTop]));
yyVal = new OpAsgnAndNode(getPosition(), support.gettable(name, getPosition()), ((Node)yyVals[-2+yyTop]));
} else {
yyVal = yyVals[-2+yyTop];
if (yyVal != null) {
((AssignableNode)yyVal).setValueNode(support.getOperatorCallNode(support.gettable(name, getPosition()), ((String)yyVals[-1+yyTop]), ((Node)yyVals[0+yyTop])));
}
}
} else {
yyVal = null; /* XXX 0; */
}
}
break;
case 175:
// line 722 "DefaultRubyParser.y"
{
yyVal = new OpElementAsgnNode(getPosition(), ((Node)yyVals[-5+yyTop]), ((String)yyVals[-1+yyTop]), ((Node)yyVals[-3+yyTop]), ((Node)yyVals[0+yyTop]));
}
break;
case 176:
// line 725 "DefaultRubyParser.y"
{
yyVal = new OpAsgnNode(getPosition(), ((Node)yyVals[-4+yyTop]), ((Node)yyVals[0+yyTop]), ((String)yyVals[-2+yyTop]), ((String)yyVals[-1+yyTop]));
}
break;
case 177:
// line 728 "DefaultRubyParser.y"
{
yyVal = new OpAsgnNode(getPosition(), ((Node)yyVals[-4+yyTop]), ((Node)yyVals[0+yyTop]), ((String)yyVals[-2+yyTop]), ((String)yyVals[-1+yyTop]));
}
break;
case 178:
// line 731 "DefaultRubyParser.y"
{
yyVal = new OpAsgnNode(getPosition(), ((Node)yyVals[-4+yyTop]), ((Node)yyVals[0+yyTop]), ((String)yyVals[-2+yyTop]), ((String)yyVals[-1+yyTop]));
}
break;
case 179:
// line 734 "DefaultRubyParser.y"
{
yyerror("constant re-assignment");
yyVal = null;
}
break;
case 180:
// line 738 "DefaultRubyParser.y"
{
yyerror("constant re-assignment");
yyVal = null;
}
break;
case 181:
// line 742 "DefaultRubyParser.y"
{
support.backrefAssignError(((Node)yyVals[-2+yyTop]));
yyVal = null;
}
break;
case 182:
// line 746 "DefaultRubyParser.y"
{
support.checkExpression(((Node)yyVals[-2+yyTop]));
support.checkExpression(((Node)yyVals[0+yyTop]));
yyVal = new DotNode(getPosition(), ((Node)yyVals[-2+yyTop]), ((Node)yyVals[0+yyTop]), false);
}
break;
case 183:
// line 751 "DefaultRubyParser.y"
{
support.checkExpression(((Node)yyVals[-2+yyTop]));
support.checkExpression(((Node)yyVals[0+yyTop]));
yyVal = new DotNode(getPosition(), ((Node)yyVals[-2+yyTop]), ((Node)yyVals[0+yyTop]), true);
}
break;
case 184:
// line 756 "DefaultRubyParser.y"
{
yyVal = support.getOperatorCallNode(((Node)yyVals[-2+yyTop]), "+", ((Node)yyVals[0+yyTop]));
}
break;
case 185:
// line 759 "DefaultRubyParser.y"
{
yyVal = support.getOperatorCallNode(((Node)yyVals[-2+yyTop]), "-", ((Node)yyVals[0+yyTop]));
}
break;
case 186:
// line 762 "DefaultRubyParser.y"
{
yyVal = support.getOperatorCallNode(((Node)yyVals[-2+yyTop]), "*", ((Node)yyVals[0+yyTop]));
}
break;
case 187:
// line 765 "DefaultRubyParser.y"
{
yyVal = support.getOperatorCallNode(((Node)yyVals[-2+yyTop]), "/", ((Node)yyVals[0+yyTop]));
}
break;
case 188:
// line 768 "DefaultRubyParser.y"
{
yyVal = support.getOperatorCallNode(((Node)yyVals[-2+yyTop]), "%", ((Node)yyVals[0+yyTop]));
}
break;
case 189:
// line 771 "DefaultRubyParser.y"
{
yyVal = support.getOperatorCallNode(((Node)yyVals[-2+yyTop]), "**", ((Node)yyVals[0+yyTop]));
/* Covert '- number ** number' to '- (number ** number)'
boolean needNegate = false;
if (($1 instanceof FixnumNode && $<FixnumNode>1.getValue() < 0) ||
($1 instanceof BignumNode && $<BignumNode>1.getValue().compareTo(BigInteger.ZERO) < 0) ||
($1 instanceof FloatNode && $<FloatNode>1.getValue() < 0.0)) {
$<>1 = support.getOperatorCallNode($1, "-@");
needNegate = true;
}
$$ = support.getOperatorCallNode($1, "**", $3);
if (needNegate) {
$$ = support.getOperatorCallNode($<Node>$, "-@");
}
*/
}
break;
case 190:
// line 790 "DefaultRubyParser.y"
{
yyVal = support.getOperatorCallNode(support.getOperatorCallNode((((Number)yyVals[-2+yyTop]) instanceof Long ? (Node) new FixnumNode(getPosition(), ((Long)yyVals[-2+yyTop]).longValue()) : (Node)new BignumNode(getPosition(), ((BigInteger)yyVals[-2+yyTop]))), "**", ((Node)yyVals[0+yyTop])), "-@");
}
break;
case 191:
// line 793 "DefaultRubyParser.y"
{
yyVal = support.getOperatorCallNode(support.getOperatorCallNode(new FloatNode(getPosition(), ((Double)yyVals[-3+yyTop]).doubleValue()), "**", ((Node)yyVals[0+yyTop])), "-@");
}
break;
case 192:
// line 796 "DefaultRubyParser.y"
{
if (((Node)yyVals[0+yyTop]) != null && ((Node)yyVals[0+yyTop]) instanceof ILiteralNode) {
yyVal = ((Node)yyVals[0+yyTop]);
} else {
yyVal = support.getOperatorCallNode(((Node)yyVals[0+yyTop]), "+@");
}
}
break;
case 193:
// line 803 "DefaultRubyParser.y"
{
yyVal = support.getOperatorCallNode(((Node)yyVals[0+yyTop]), "-@");
}
break;
case 194:
// line 806 "DefaultRubyParser.y"
{
yyVal = support.getOperatorCallNode(((Node)yyVals[-2+yyTop]), "|", ((Node)yyVals[0+yyTop]));
}
break;
case 195:
// line 809 "DefaultRubyParser.y"
{
yyVal = support.getOperatorCallNode(((Node)yyVals[-2+yyTop]), "^", ((Node)yyVals[0+yyTop]));
}
break;
case 196:
// line 812 "DefaultRubyParser.y"
{
yyVal = support.getOperatorCallNode(((Node)yyVals[-2+yyTop]), "&", ((Node)yyVals[0+yyTop]));
}
break;
case 197:
// line 815 "DefaultRubyParser.y"
{
yyVal = support.getOperatorCallNode(((Node)yyVals[-2+yyTop]), "<=>", ((Node)yyVals[0+yyTop]));
}
break;
case 198:
// line 818 "DefaultRubyParser.y"
{
yyVal = support.getOperatorCallNode(((Node)yyVals[-2+yyTop]), ">", ((Node)yyVals[0+yyTop]));
}
break;
case 199:
// line 821 "DefaultRubyParser.y"
{
yyVal = support.getOperatorCallNode(((Node)yyVals[-2+yyTop]), ">=", ((Node)yyVals[0+yyTop]));
}
break;
case 200:
// line 824 "DefaultRubyParser.y"
{
yyVal = support.getOperatorCallNode(((Node)yyVals[-2+yyTop]), "<", ((Node)yyVals[0+yyTop]));
}
break;
case 201:
// line 827 "DefaultRubyParser.y"
{
yyVal = support.getOperatorCallNode(((Node)yyVals[-2+yyTop]), "<=", ((Node)yyVals[0+yyTop]));
}
break;
case 202:
// line 830 "DefaultRubyParser.y"
{
yyVal = support.getOperatorCallNode(((Node)yyVals[-2+yyTop]), "==", ((Node)yyVals[0+yyTop]));
}
break;
case 203:
// line 833 "DefaultRubyParser.y"
{
yyVal = support.getOperatorCallNode(((Node)yyVals[-2+yyTop]), "===", ((Node)yyVals[0+yyTop]));
}
break;
case 204:
// line 836 "DefaultRubyParser.y"
{
yyVal = new NotNode(getPosition(), support.getOperatorCallNode(((Node)yyVals[-2+yyTop]), "==", ((Node)yyVals[0+yyTop])));
}
break;
case 205:
// line 839 "DefaultRubyParser.y"
{
yyVal = support.getMatchNode(((Node)yyVals[-2+yyTop]), ((Node)yyVals[0+yyTop]));
}
break;
case 206:
// line 842 "DefaultRubyParser.y"
{
yyVal = new NotNode(getPosition(), support.getMatchNode(((Node)yyVals[-2+yyTop]), ((Node)yyVals[0+yyTop])));
}
break;
case 207:
// line 845 "DefaultRubyParser.y"
{
yyVal = new NotNode(getPosition(), support.getConditionNode(((Node)yyVals[0+yyTop])));
}
break;
case 208:
// line 848 "DefaultRubyParser.y"
{
yyVal = support.getOperatorCallNode(((Node)yyVals[0+yyTop]), "~");
}
break;
case 209:
// line 851 "DefaultRubyParser.y"
{
yyVal = support.getOperatorCallNode(((Node)yyVals[-2+yyTop]), "<<", ((Node)yyVals[0+yyTop]));
}
break;
case 210:
// line 854 "DefaultRubyParser.y"
{
yyVal = support.getOperatorCallNode(((Node)yyVals[-2+yyTop]), ">>", ((Node)yyVals[0+yyTop]));
}
break;
case 211:
// line 857 "DefaultRubyParser.y"
{
yyVal = support.newAndNode(((Node)yyVals[-2+yyTop]), ((Node)yyVals[0+yyTop]));
}
break;
case 212:
// line 860 "DefaultRubyParser.y"
{
yyVal = support.newOrNode(((Node)yyVals[-2+yyTop]), ((Node)yyVals[0+yyTop]));
}
break;
case 213:
// line 863 "DefaultRubyParser.y"
{
support.setInDefined(true);
}
break;
case 214:
// line 865 "DefaultRubyParser.y"
{
support.setInDefined(false);
yyVal = new DefinedNode(getPosition(), ((Node)yyVals[0+yyTop]));
}
break;
case 215:
// line 869 "DefaultRubyParser.y"
{
yyVal = new IfNode(getPosition(), support.getConditionNode(((Node)yyVals[-4+yyTop])), ((Node)yyVals[-2+yyTop]), ((Node)yyVals[0+yyTop]));
}
break;
case 216:
// line 872 "DefaultRubyParser.y"
{
yyVal = ((Node)yyVals[0+yyTop]);
}
break;
case 217:
// line 876 "DefaultRubyParser.y"
{
support.checkExpression(((Node)yyVals[0+yyTop]));
yyVal = ((Node)yyVals[0+yyTop]);
}
break;
case 219:
// line 882 "DefaultRubyParser.y"
{
errorHandler.handleError(IErrors.WARN, null, "parenthesize argument(s) for future version");
yyVal = new ArrayNode(getPosition()).add(((Node)yyVals[-1+yyTop]));
}
break;
case 220:
// line 886 "DefaultRubyParser.y"
{
yyVal = ((ListNode)yyVals[-1+yyTop]);
}
break;
case 221:
// line 889 "DefaultRubyParser.y"
{
support.checkExpression(((Node)yyVals[-1+yyTop]));
yyVal = support.arg_concat(getPosition(), ((ListNode)yyVals[-4+yyTop]), ((Node)yyVals[-1+yyTop]));
}
break;
case 222:
// line 893 "DefaultRubyParser.y"
{
yyVal = new ArrayNode(getPosition()).add(new HashNode(((ListNode)yyVals[-1+yyTop])));
}
break;
case 223:
// line 896 "DefaultRubyParser.y"
{
support.checkExpression(((Node)yyVals[-1+yyTop]));
yyVal = new NewlineNode(getPosition(), new SplatNode(getPosition(), ((Node)yyVals[-1+yyTop])));
}
break;
case 224:
// line 901 "DefaultRubyParser.y"
{
yyVal = ((ListNode)yyVals[-1+yyTop]);
}
break;
case 225:
// line 904 "DefaultRubyParser.y"
{
yyVal = ((Node)yyVals[-2+yyTop]);
}
break;
case 226:
// line 907 "DefaultRubyParser.y"
{
errorHandler.handleError(IErrors.WARN, null, "parenthesize argument(s) for future version");
yyVal = new ArrayNode(getPosition()).add(((Node)yyVals[-2+yyTop]));
}
break;
case 227:
// line 911 "DefaultRubyParser.y"
{
errorHandler.handleError(IErrors.WARN, null, "parenthesize argument(s) for future version");
yyVal = ((ListNode)yyVals[-4+yyTop]).add(((Node)yyVals[-2+yyTop]));
}
break;
case 230:
// line 919 "DefaultRubyParser.y"
{
errorHandler.handleError(IErrors.WARN, null, "parenthesize argument(s) for future version");
yyVal = new ArrayNode(getPosition()).add(((Node)yyVals[0+yyTop]));
}
break;
case 231:
// line 923 "DefaultRubyParser.y"
{
yyVal = support.arg_blk_pass(((ListNode)yyVals[-1+yyTop]), ((BlockPassNode)yyVals[0+yyTop]));
}
break;
case 232:
// line 926 "DefaultRubyParser.y"
{
yyVal = support.arg_concat(getPosition(), ((ListNode)yyVals[-4+yyTop]), ((Node)yyVals[-1+yyTop]));
yyVal = support.arg_blk_pass((Node)yyVal, ((BlockPassNode)yyVals[0+yyTop]));
}
break;
case 233:
// line 930 "DefaultRubyParser.y"
{
yyVal = new ArrayNode(getPosition()).add(new HashNode(((ListNode)yyVals[-1+yyTop])));
yyVal = support.arg_blk_pass((Node)yyVal, ((BlockPassNode)yyVals[0+yyTop]));
}
break;
case 234:
// line 934 "DefaultRubyParser.y"
{
yyVal = support.arg_concat(getPosition(), new ArrayNode(getPosition()).add(new HashNode(((ListNode)yyVals[-4+yyTop]))), ((Node)yyVals[-1+yyTop]));
yyVal = support.arg_blk_pass((Node)yyVal, ((BlockPassNode)yyVals[0+yyTop]));
}
break;
case 235:
// line 938 "DefaultRubyParser.y"
{
yyVal = ((ListNode)yyVals[-3+yyTop]).add(new HashNode(((ListNode)yyVals[-1+yyTop])));
yyVal = support.arg_blk_pass((Node)yyVal, ((BlockPassNode)yyVals[0+yyTop]));
}
break;
case 236:
// line 942 "DefaultRubyParser.y"
{
support.checkExpression(((Node)yyVals[-1+yyTop]));
yyVal = support.arg_concat(getPosition(), ((ListNode)yyVals[-6+yyTop]).add(new HashNode(((ListNode)yyVals[-4+yyTop]))), ((Node)yyVals[-1+yyTop]));
yyVal = support.arg_blk_pass((Node)yyVal, ((BlockPassNode)yyVals[0+yyTop]));
}
break;
case 237:
// line 947 "DefaultRubyParser.y"
{
yyVal = support.arg_blk_pass(new SplatNode(getPosition(), ((Node)yyVals[-1+yyTop])), ((BlockPassNode)yyVals[0+yyTop]));
}
break;
case 238:
// line 950 "DefaultRubyParser.y"
{
}
break;
case 239:
// line 953 "DefaultRubyParser.y"
{
yyVal = support.arg_blk_pass(support.list_concat(new ArrayNode(getPosition()).add(((Node)yyVals[-3+yyTop])), ((ListNode)yyVals[-1+yyTop])), ((BlockPassNode)yyVals[0+yyTop]));
}
break;
case 240:
// line 956 "DefaultRubyParser.y"
{
yyVal = support.arg_blk_pass(new ArrayNode(getPosition()).add(((Node)yyVals[-2+yyTop])), ((BlockPassNode)yyVals[0+yyTop]));
}
break;
case 241:
// line 959 "DefaultRubyParser.y"
{
yyVal = support.arg_concat(getPosition(), new ArrayNode(getPosition()).add(((Node)yyVals[-4+yyTop])), ((Node)yyVals[-1+yyTop]));
yyVal = support.arg_blk_pass((Node)yyVal, ((BlockPassNode)yyVals[0+yyTop]));
}
break;
case 242:
// line 963 "DefaultRubyParser.y"
{
yyVal = support.arg_concat(getPosition(), support.list_concat(new ArrayNode(getPosition()).add(((Node)yyVals[-6+yyTop])), new HashNode(((ListNode)yyVals[-4+yyTop]))), ((Node)yyVals[-1+yyTop]));
yyVal = support.arg_blk_pass((Node)yyVal, ((BlockPassNode)yyVals[0+yyTop]));
}
break;
case 243:
// line 967 "DefaultRubyParser.y"
{
yyVal = new ArrayNode(getPosition()).add(new HashNode(((ListNode)yyVals[-1+yyTop])));
yyVal = support.arg_blk_pass((Node)yyVal, ((BlockPassNode)yyVals[0+yyTop]));
}
break;
case 244:
// line 971 "DefaultRubyParser.y"
{
yyVal = support.arg_concat(getPosition(), new ArrayNode(getPosition()).add(new HashNode(((ListNode)yyVals[-4+yyTop]))), ((Node)yyVals[-1+yyTop]));
yyVal = support.arg_blk_pass((Node)yyVal, ((BlockPassNode)yyVals[0+yyTop]));
}
break;
case 245:
// line 975 "DefaultRubyParser.y"
{
yyVal = new ArrayNode(getPosition()).add(((Node)yyVals[-3+yyTop])).add(new HashNode(((ListNode)yyVals[-1+yyTop])));
yyVal = support.arg_blk_pass((Node)yyVal, ((BlockPassNode)yyVals[0+yyTop]));
}
break;
case 246:
// line 979 "DefaultRubyParser.y"
{
yyVal = support.list_concat(new ArrayNode(getPosition()).add(((Node)yyVals[-5+yyTop])), ((ListNode)yyVals[-3+yyTop])).add(new HashNode(((ListNode)yyVals[-1+yyTop])));
yyVal = support.arg_blk_pass((Node)yyVal, ((BlockPassNode)yyVals[0+yyTop]));
}
break;
case 247:
// line 983 "DefaultRubyParser.y"
{
yyVal = support.arg_concat(getPosition(), new ArrayNode(getPosition()).add(((Node)yyVals[-6+yyTop])).add(new HashNode(((ListNode)yyVals[-4+yyTop]))), ((Node)yyVals[-1+yyTop]));
yyVal = support.arg_blk_pass((Node)yyVal, ((BlockPassNode)yyVals[0+yyTop]));
}
break;
case 248:
// line 987 "DefaultRubyParser.y"
{
yyVal = support.arg_concat(getPosition(), support.list_concat(new ArrayNode(getPosition()).add(((Node)yyVals[-8+yyTop])), ((ListNode)yyVals[-6+yyTop])).add(new HashNode(((ListNode)yyVals[-4+yyTop]))), ((Node)yyVals[-1+yyTop]));
yyVal = support.arg_blk_pass((Node)yyVal, ((BlockPassNode)yyVals[0+yyTop]));
}
break;
case 249:
// line 991 "DefaultRubyParser.y"
{
yyVal = support.arg_blk_pass(new SplatNode(getPosition(), ((Node)yyVals[-1+yyTop])), ((BlockPassNode)yyVals[0+yyTop]));
}
break;
case 250:
// line 994 "DefaultRubyParser.y"
{}
break;
case 251:
// line 996 "DefaultRubyParser.y"
{
yyVal = new Long(lexer.getCmdArgumentState().begin());
}
break;
case 252:
// line 998 "DefaultRubyParser.y"
{
lexer.getCmdArgumentState().reset(((Long)yyVals[-1+yyTop]).longValue());
yyVal = ((Node)yyVals[0+yyTop]);
}
break;
case 254:
// line 1004 "DefaultRubyParser.y"
{
lexer.setState(LexState.EXPR_ENDARG);
}
break;
case 255:
// line 1006 "DefaultRubyParser.y"
{
errorHandler.handleError(IErrors.WARN, null, "don't put space before argument parentheses");
yyVal = null;
}
break;
case 256:
// line 1010 "DefaultRubyParser.y"
{
lexer.setState(LexState.EXPR_ENDARG);
}
break;
case 257:
// line 1012 "DefaultRubyParser.y"
{
errorHandler.handleError(IErrors.WARN, null, "don't put space before argument parentheses");
yyVal = ((Node)yyVals[-2+yyTop]);
}
break;
case 258:
// line 1017 "DefaultRubyParser.y"
{
support.checkExpression(((Node)yyVals[0+yyTop]));
yyVal = new BlockPassNode(getPosition(), ((Node)yyVals[0+yyTop]));
}
break;
case 259:
// line 1022 "DefaultRubyParser.y"
{
yyVal = ((BlockPassNode)yyVals[0+yyTop]);
}
break;
case 261:
// line 1027 "DefaultRubyParser.y"
{
yyVal = new ArrayNode(getPosition()).add(((Node)yyVals[0+yyTop]));
}
break;
case 262:
// line 1030 "DefaultRubyParser.y"
{
yyVal = ((ListNode)yyVals[-2+yyTop]).add(((Node)yyVals[0+yyTop]));
}
break;
case 263:
// line 1034 "DefaultRubyParser.y"
{
yyVal = ((ListNode)yyVals[-2+yyTop]).add(((Node)yyVals[0+yyTop]));
}
break;
case 264:
// line 1037 "DefaultRubyParser.y"
{
yyVal = support.arg_concat(getPosition(), ((ListNode)yyVals[-3+yyTop]), ((Node)yyVals[0+yyTop]));
}
break;
case 265:
// line 1040 "DefaultRubyParser.y"
{
yyVal = new SplatNode(getPosition(), ((Node)yyVals[0+yyTop]));
}
break;
case 274:
// line 1052 "DefaultRubyParser.y"
{
yyVal = new VCallNode(getPosition(), ((String)yyVals[0+yyTop]));
}
break;
case 275:
// line 1056 "DefaultRubyParser.y"
{
yyVal = new BeginNode(getPosition(), ((Node)yyVals[-1+yyTop]));
}
break;
case 276:
// line 1059 "DefaultRubyParser.y"
{
lexer.setState(LexState.EXPR_ENDARG);
errorHandler.handleError(IErrors.WARN, null, "(...) interpreted as grouped expression");
yyVal = ((Node)yyVals[-2+yyTop]);
}
break;
case 277:
// line 1064 "DefaultRubyParser.y"
{
yyVal = ((Node)yyVals[-1+yyTop]);
}
break;
case 278:
// line 1067 "DefaultRubyParser.y"
{
yyVal = new Colon2Node(getPosition(), ((Node)yyVals[-2+yyTop]), ((String)yyVals[0+yyTop]));
}
break;
case 279:
// line 1070 "DefaultRubyParser.y"
{
yyVal = new Colon3Node(getPosition(), ((String)yyVals[0+yyTop]));
}
break;
case 280:
// line 1073 "DefaultRubyParser.y"
{
yyVal = new CallNode(getPosition(), ((Node)yyVals[-3+yyTop]), "[]", ((Node)yyVals[-1+yyTop]));
}
break;
case 281:
// line 1076 "DefaultRubyParser.y"
{
if (((Node)yyVals[-1+yyTop]) == null) {
yyVal = new ZArrayNode(getPosition()); /* zero length array*/
} else {
yyVal = ((Node)yyVals[-1+yyTop]);
}
}
break;
case 282:
// line 1083 "DefaultRubyParser.y"
{
yyVal = new HashNode(getPosition(), ((ListNode)yyVals[-1+yyTop]));
}
break;
case 283:
// line 1086 "DefaultRubyParser.y"
{
yyVal = new ReturnNode(getPosition(), null);
}
break;
case 284:
// line 1089 "DefaultRubyParser.y"
{
yyVal = support.new_yield(getPosition(), ((Node)yyVals[-1+yyTop]));
}
break;
case 285:
// line 1092 "DefaultRubyParser.y"
{
yyVal = new YieldNode(getPosition(), null, false);
}
break;
case 286:
// line 1095 "DefaultRubyParser.y"
{
yyVal = new YieldNode(getPosition(), null, false);
}
break;
case 287:
// line 1098 "DefaultRubyParser.y"
{
support.setInDefined(true);
}
break;
case 288:
// line 1100 "DefaultRubyParser.y"
{
support.setInDefined(false);
yyVal = new DefinedNode(getPosition(), ((Node)yyVals[-1+yyTop]));
}
break;
case 289:
// line 1104 "DefaultRubyParser.y"
{
((IterNode)yyVals[0+yyTop]).setIterNode(new FCallNode(getPosition(), ((String)yyVals[-1+yyTop]), null));
yyVal = ((IterNode)yyVals[0+yyTop]);
}
break;
case 291:
// line 1109 "DefaultRubyParser.y"
{
if (((Node)yyVals[-1+yyTop]) != null && ((Node)yyVals[-1+yyTop]) instanceof BlockPassNode) {
errorHandler.handleError(IErrors.COMPILE_ERROR, null, "Both block arg and actual block given.");
}
((IterNode)yyVals[0+yyTop]).setIterNode(((Node)yyVals[-1+yyTop]));
yyVal = ((IterNode)yyVals[0+yyTop]);
}
break;
case 292:
// line 1116 "DefaultRubyParser.y"
{
yyVal = new IfNode(getPosition(), support.getConditionNode(((Node)yyVals[-4+yyTop])), ((Node)yyVals[-2+yyTop]), ((Node)yyVals[-1+yyTop]));
/* missing from ruby
if (cond_negative(&$$->nd_cond)) {
NODE *tmp = $$->nd_body;
$$->nd_body = $$->nd_else;
$$->nd_else = tmp;
} */
}
break;
case 293:
// line 1125 "DefaultRubyParser.y"
{
yyVal = new IfNode(getPosition(), support.getConditionNode(((Node)yyVals[-4+yyTop])), ((Node)yyVals[-1+yyTop]), ((Node)yyVals[-2+yyTop]));
/* missing from ruby
if (cond_negative(&$$->nd_cond)) {
NODE *tmp = $$->nd_body;
$$->nd_body = $$->nd_else;
$$->nd_else = tmp;
} */
}
break;
case 294:
// line 1134 "DefaultRubyParser.y"
{
lexer.getConditionState().begin();
}
break;
case 295:
// line 1136 "DefaultRubyParser.y"
{
lexer.getConditionState().end();
}
break;
case 296:
// line 1138 "DefaultRubyParser.y"
{
yyVal = new WhileNode(getPosition(), support.getConditionNode(((Node)yyVals[-4+yyTop])), ((Node)yyVals[-1+yyTop]));
/* missing from ruby
if (cond_negative(&$$->nd_cond)) {
nd_set_type($$, NODE_UNTIL);
} */
}
break;
case 297:
// line 1145 "DefaultRubyParser.y"
{
lexer.getConditionState().begin();
}
break;
case 298:
// line 1147 "DefaultRubyParser.y"
{
lexer.getConditionState().end();
}
break;
case 299:
// line 1149 "DefaultRubyParser.y"
{
yyVal = new UntilNode(getPosition(), support.getConditionNode(((Node)yyVals[-4+yyTop])), ((Node)yyVals[-1+yyTop]));
/* missing from ruby
if (cond_negative(&$$->nd_cond)) {
nd_set_type($$, NODE_WHILE);
} */
}
break;
case 300:
// line 1158 "DefaultRubyParser.y"
{
yyVal = new CaseNode(getPosition(), ((Node)yyVals[-3+yyTop]), ((Node)yyVals[-1+yyTop])); /* XXX*/
}
break;
case 301:
// line 1161 "DefaultRubyParser.y"
{
yyVal = new CaseNode(getPosition(), null, ((Node)yyVals[-1+yyTop]));
}
break;
case 302:
// line 1164 "DefaultRubyParser.y"
{
yyVal = ((Node)yyVals[-1+yyTop]);
}
break;
case 303:
// line 1167 "DefaultRubyParser.y"
{
lexer.getConditionState().begin();
}
break;
case 304:
// line 1169 "DefaultRubyParser.y"
{
lexer.getConditionState().end();
}
break;
case 305:
// line 1172 "DefaultRubyParser.y"
{
yyVal = new ForNode(getPosition(), ((Node)yyVals[-7+yyTop]), ((Node)yyVals[-1+yyTop]), ((Node)yyVals[-4+yyTop]));
}
break;
case 306:
// line 1175 "DefaultRubyParser.y"
{
if (support.isInDef() || support.isInSingle()) {
yyerror("class definition in method body");
}
support.setClassNest(support.getClassNest() + 1);
support.getLocalNames().push();
/* $$ = new Integer(ruby.getSourceLine());*/
}
break;
case 307:
// line 1183 "DefaultRubyParser.y"
{
yyVal = new ClassNode(getPosition(), ((Colon2Node)yyVals[-4+yyTop]).getName(), new ScopeNode(support.getLocalNames().getNames(), ((Node)yyVals[-1+yyTop])), ((Node)yyVals[-3+yyTop]));
/* $<Node>$.setLine($<Integer>4.intValue());*/
support.getLocalNames().pop();
support.setClassNest(support.getClassNest() - 1);
}
break;
case 308:
// line 1189 "DefaultRubyParser.y"
{
yyVal = new Boolean(support.isInDef());
support.setInDef(false);
}
break;
case 309:
// line 1192 "DefaultRubyParser.y"
{
yyVal = new Integer(support.getInSingle());
support.setInSingle(0);
support.setClassNest(support.getClassNest() + 1);
support.getLocalNames().push();
}
break;
case 310:
// line 1198 "DefaultRubyParser.y"
{
yyVal = new SClassNode(getPosition(), ((Node)yyVals[-5+yyTop]), new ScopeNode(support.getLocalNames().getNames(), ((Node)yyVals[-1+yyTop])));
support.getLocalNames().pop();
support.setClassNest(support.getClassNest() - 1);
support.setInDef(((Boolean)yyVals[-4+yyTop]).booleanValue());
support.setInSingle(((Integer)yyVals[-2+yyTop]).intValue());
}
break;
case 311:
// line 1205 "DefaultRubyParser.y"
{
if (support.isInDef() || support.isInSingle()) {
yyerror("module definition in method body");
}
support.setClassNest(support.getClassNest() + 1);
support.getLocalNames().push();
/* $$ = new Integer(ruby.getSourceLine());*/
}
break;
case 312:
// line 1213 "DefaultRubyParser.y"
{
yyVal = new ModuleNode(getPosition(), ((Colon2Node)yyVals[-3+yyTop]).getName(), new ScopeNode(support.getLocalNames().getNames(), ((Node)yyVals[-1+yyTop])));
/* $<Node>$.setLine($<Integer>3.intValue());*/
support.getLocalNames().pop();
support.setClassNest(support.getClassNest() - 1);
}
break;
case 313:
// line 1219 "DefaultRubyParser.y"
{
/* missing
$<id>$ = cur_mid;
cur_mid = $2; */
support.setInDef(true);
support.getLocalNames().push();
}
break;
case 314:
// line 1227 "DefaultRubyParser.y"
{
/* was in old jruby grammar support.getClassNest() !=0 || IdUtil.isAttrSet($2) ? Visibility.PUBLIC : Visibility.PRIVATE); */
/* NOEX_PRIVATE for toplevel */
yyVal = new DefnNode(getPosition(), ((String)yyVals[-4+yyTop]), ((Node)yyVals[-2+yyTop]),
new ScopeNode(support.getLocalNames().getNames(), ((Node)yyVals[-1+yyTop])), Visibility.PRIVATE);
/* $<Node>$.setPosFrom($4);*/
support.getLocalNames().pop();
support.setInDef(false);
/* missing cur_mid = $<id>3; */
}
break;
case 315:
// line 1237 "DefaultRubyParser.y"
{
lexer.setState(LexState.EXPR_FNAME);
}
break;
case 316:
// line 1239 "DefaultRubyParser.y"
{
support.setInSingle(support.getInSingle() + 1);
support.getLocalNames().push();
lexer.setState(LexState.EXPR_END); /* force for args */
}
break;
case 317:
// line 1245 "DefaultRubyParser.y"
{
yyVal = new DefsNode(getPosition(), ((Node)yyVals[-7+yyTop]), ((String)yyVals[-4+yyTop]), ((Node)yyVals[-2+yyTop]), new ScopeNode(support.getLocalNames().getNames(), ((Node)yyVals[-1+yyTop])));
/* $<Node>$.setPosFrom($2);*/
support.getLocalNames().pop();
support.setInSingle(support.getInSingle() - 1);
}
break;
case 318:
// line 1251 "DefaultRubyParser.y"
{
yyVal = new BreakNode(getPosition());
}
break;
case 319:
// line 1254 "DefaultRubyParser.y"
{
yyVal = new NextNode(getPosition());
}
break;
case 320:
// line 1257 "DefaultRubyParser.y"
{
yyVal = new RedoNode(getPosition());
}
break;
case 321:
// line 1260 "DefaultRubyParser.y"
{
yyVal = new RetryNode(getPosition());
}
break;
case 322:
// line 1264 "DefaultRubyParser.y"
{
support.checkExpression(((Node)yyVals[0+yyTop]));
yyVal = ((Node)yyVals[0+yyTop]);
}
break;
case 331:
// line 1281 "DefaultRubyParser.y"
{
yyVal = new IfNode(getPosition(), support.getConditionNode(((Node)yyVals[-3+yyTop])), ((Node)yyVals[-1+yyTop]), ((Node)yyVals[0+yyTop]));
}
break;
case 333:
// line 1286 "DefaultRubyParser.y"
{
yyVal = ((Node)yyVals[0+yyTop]);
}
break;
case 335:
// line 1291 "DefaultRubyParser.y"
{}
break;
case 337:
// line 1294 "DefaultRubyParser.y"
{
yyVal = new ZeroArgNode();
}
break;
case 338:
// line 1297 "DefaultRubyParser.y"
{
yyVal = new ZeroArgNode();
}
break;
case 339:
// line 1300 "DefaultRubyParser.y"
{
yyVal = ((Node)yyVals[-1+yyTop]);
}
break;
case 340:
// line 1304 "DefaultRubyParser.y"
{
support.getBlockNames().push();
}
break;
case 341:
// line 1307 "DefaultRubyParser.y"
{
yyVal = new IterNode(getPosition(), ((Node)yyVals[-2+yyTop]), ((Node)yyVals[-1+yyTop]), null);
support.getBlockNames().pop();
}
break;
case 342:
// line 1312 "DefaultRubyParser.y"
{
if (((Node)yyVals[-1+yyTop]) instanceof BlockPassNode) {
errorHandler.handleError(IErrors.COMPILE_ERROR, null, "Both block arg and actual block given.");
}
((IterNode)yyVals[0+yyTop]).setIterNode(((Node)yyVals[-1+yyTop]));
yyVal = ((IterNode)yyVals[0+yyTop]);
}
break;
case 343:
// line 1319 "DefaultRubyParser.y"
{
yyVal = support.new_call(((Node)yyVals[-3+yyTop]), ((String)yyVals[-1+yyTop]), ((Node)yyVals[0+yyTop]));
}
break;
case 344:
// line 1322 "DefaultRubyParser.y"
{
yyVal = support.new_call(((Node)yyVals[-3+yyTop]), ((String)yyVals[-1+yyTop]), ((Node)yyVals[0+yyTop]));
}
break;
case 345:
// line 1326 "DefaultRubyParser.y"
{
yyVal = support.new_fcall(((String)yyVals[-1+yyTop]), ((Node)yyVals[0+yyTop]), getPosition()); /* .setPosFrom($2);*/
}
break;
case 346:
// line 1329 "DefaultRubyParser.y"
{
yyVal = support.new_call(((Node)yyVals[-3+yyTop]), ((String)yyVals[-1+yyTop]), ((Node)yyVals[0+yyTop])); /*.setPosFrom($1);*/
}
break;
case 347:
// line 1332 "DefaultRubyParser.y"
{
yyVal = support.new_call(((Node)yyVals[-3+yyTop]), ((String)yyVals[-1+yyTop]), ((Node)yyVals[0+yyTop])); /*.setPosFrom($1);*/
}
break;
case 348:
// line 1335 "DefaultRubyParser.y"
{
yyVal = support.new_call(((Node)yyVals[-2+yyTop]), ((String)yyVals[0+yyTop]), null);
}
break;
case 349:
// line 1338 "DefaultRubyParser.y"
{
yyVal = support.new_super(((Node)yyVals[0+yyTop]), getPosition());
}
break;
case 350:
// line 1341 "DefaultRubyParser.y"
{
yyVal = new ZSuperNode(getPosition());
}
break;
case 351:
// line 1345 "DefaultRubyParser.y"
{
support.getBlockNames().push();
}
break;
case 352:
// line 1347 "DefaultRubyParser.y"
{
yyVal = new IterNode(getPosition(), ((Node)yyVals[-2+yyTop]), ((Node)yyVals[-1+yyTop]), null);
support.getBlockNames().pop();
}
break;
case 353:
// line 1351 "DefaultRubyParser.y"
{
support.getBlockNames().push();
}
break;
case 354:
// line 1353 "DefaultRubyParser.y"
{
yyVal = new IterNode(getPosition(), ((Node)yyVals[-2+yyTop]), ((Node)yyVals[-1+yyTop]), null);
support.getBlockNames().pop();
}
break;
case 355:
// line 1360 "DefaultRubyParser.y"
{
yyVal = new WhenNode(getPosition(), ((ListNode)yyVals[-3+yyTop]), ((Node)yyVals[-1+yyTop]), ((Node)yyVals[0+yyTop]));
}
break;
case 357:
// line 1365 "DefaultRubyParser.y"
{
yyVal = ((ListNode)yyVals[-3+yyTop]).add(new WhenNode(getPosition(), new ArrayNode(getPosition()).add(((Node)yyVals[0+yyTop])), null, null));
}
break;
case 358:
// line 1368 "DefaultRubyParser.y"
{
yyVal = new ArrayNode(getPosition()).add(new WhenNode(getPosition(), new ArrayNode(getPosition()).add(((Node)yyVals[0+yyTop])), null, null));
}
break;
case 361:
// line 1378 "DefaultRubyParser.y"
{
Node node;
if (((Node)yyVals[-3+yyTop]) != null) {
node = support.appendToBlock(support.node_assign(((Node)yyVals[-3+yyTop]), new GlobalVarNode(getPosition(), "$!")), ((Node)yyVals[-1+yyTop]));
} else {
node = ((Node)yyVals[-1+yyTop]);
}
yyVal = new RescueBodyNode(getPosition(), ((Node)yyVals[-4+yyTop]), node, ((RescueBodyNode)yyVals[0+yyTop]));
}
break;
case 362:
// line 1387 "DefaultRubyParser.y"
{yyVal = null;}
break;
case 363:
// line 1389 "DefaultRubyParser.y"
{
yyVal = new ArrayNode(getPosition()).add(((Node)yyVals[0+yyTop]));
}
break;
case 366:
// line 1395 "DefaultRubyParser.y"
{
yyVal = ((Node)yyVals[0+yyTop]);
}
break;
case 368:
// line 1400 "DefaultRubyParser.y"
{
if (((Node)yyVals[0+yyTop]) != null) {
yyVal = ((Node)yyVals[0+yyTop]);
} else {
yyVal = new NilNode(null);
}
}
break;
case 371:
// line 1410 "DefaultRubyParser.y"
{
yyVal = new SymbolNode(getPosition(), ((String)yyVals[0+yyTop]));
}
break;
case 373:
// line 1415 "DefaultRubyParser.y"
{
if (((Node)yyVals[0+yyTop]) == null) {
yyVal = new StrNode(getPosition(), "");
} else {
if (((Node)yyVals[0+yyTop]) instanceof EvStrNode) {
yyVal = new DStrNode(getPosition()).add(((Node)yyVals[0+yyTop]));
} else {
yyVal = ((Node)yyVals[0+yyTop]);
}
}
}
break;
case 375:
// line 1428 "DefaultRubyParser.y"
{
yyVal = support.literal_concat(getPosition(), ((Node)yyVals[-1+yyTop]), ((Node)yyVals[0+yyTop]));
}
break;
case 376:
// line 1432 "DefaultRubyParser.y"
{
yyVal = ((Node)yyVals[-1+yyTop]);
}
break;
case 377:
// line 1436 "DefaultRubyParser.y"
{
if (((Node)yyVals[-1+yyTop]) == null) {
yyVal = new XStrNode(getPosition(), null);
} else {
if (((Node)yyVals[-1+yyTop]) instanceof StrNode) {
yyVal = new XStrNode(getPosition(), ((StrNode)yyVals[-1+yyTop]).getValue());
} else if (((Node)yyVals[-1+yyTop]) instanceof DStrNode) {
yyVal = new DXStrNode(getPosition()).add(((Node)yyVals[-1+yyTop]));
} else {
yyVal = new DXStrNode(getPosition()).add(new ArrayNode(getPosition()).add(((Node)yyVals[-1+yyTop])));
}
}
}
break;
case 378:
// line 1450 "DefaultRubyParser.y"
{
int options = ((RegexpNode)yyVals[0+yyTop]).getOptions();
Node node = ((Node)yyVals[-1+yyTop]);
if (node == null) {
yyVal = new RegexpNode(getPosition(), "", options & ~ReOptions.RE_OPTION_ONCE);
} else if (node instanceof StrNode) {
yyVal = new RegexpNode(getPosition(), ((StrNode) node).getValue(), options & ~ReOptions.RE_OPTION_ONCE);
} else {
if (node instanceof DStrNode == false) {
node = new DStrNode(getPosition()).add(new ArrayNode(getPosition()).add(node));
}
yyVal = new DRegexpNode(getPosition(), options, (options & ReOptions.RE_OPTION_ONCE) != 0).add(node);
}
}
break;
case 379:
// line 1467 "DefaultRubyParser.y"
{
yyVal = new ZArrayNode(getPosition());
}
break;
case 380:
// line 1470 "DefaultRubyParser.y"
{
yyVal = ((ListNode)yyVals[-1+yyTop]);
}
break;
case 381:
// line 1474 "DefaultRubyParser.y"
{
yyVal = null;
}
break;
case 382:
// line 1477 "DefaultRubyParser.y"
{
Node node = ((Node)yyVals[-1+yyTop]);
if (node instanceof EvStrNode) {
node = new DStrNode(getPosition()).add(node);
}
yyVal = ((ListNode)yyVals[-2+yyTop]).add(node);
}
break;
case 384:
// line 1488 "DefaultRubyParser.y"
{
yyVal = support.literal_concat(getPosition(), ((Node)yyVals[-1+yyTop]), ((Node)yyVals[0+yyTop]));
}
break;
case 385:
// line 1492 "DefaultRubyParser.y"
{
yyVal = new ZArrayNode(getPosition());
}
break;
case 386:
// line 1495 "DefaultRubyParser.y"
{
yyVal = ((ListNode)yyVals[-1+yyTop]);
}
break;
case 387:
// line 1499 "DefaultRubyParser.y"
{
yyVal = null;
}
break;
case 388:
// line 1502 "DefaultRubyParser.y"
{
if (((ListNode)yyVals[-2+yyTop]) == null) {
yyVal = new ArrayNode(getPosition()).add(new StrNode(getPosition(), ((String)yyVals[-1+yyTop])));
} else {
yyVal = ((ListNode)yyVals[-2+yyTop]).add(new StrNode(getPosition(), ((String)yyVals[-1+yyTop])));
}
}
break;
case 389:
// line 1510 "DefaultRubyParser.y"
{
yyVal = null;
}
break;
case 390:
// line 1513 "DefaultRubyParser.y"
{
yyVal = support.literal_concat(getPosition(), ((Node)yyVals[-1+yyTop]), ((Node)yyVals[0+yyTop]));
}
break;
case 391:
// line 1517 "DefaultRubyParser.y"
{
yyVal = null;
}
break;
case 392:
// line 1520 "DefaultRubyParser.y"
{
yyVal = support.literal_concat(getPosition(), ((Node)yyVals[-1+yyTop]), ((Node)yyVals[0+yyTop]));
}
break;
case 393:
// line 1525 "DefaultRubyParser.y"
{
yyVal = new StrNode(getPosition(), ((String)yyVal));
}
break;
case 394:
// line 1528 "DefaultRubyParser.y"
{
yyVal = lexer.strTerm();
lexer.setStrTerm(null);
lexer.setState(LexState.EXPR_BEG);
}
break;
case 395:
// line 1532 "DefaultRubyParser.y"
{
lexer.setStrTerm(((Node)yyVals[-1+yyTop]));
yyVal = new EvStrNode(getPosition(), ((Node)yyVals[0+yyTop]));
}
break;
case 396:
// line 1536 "DefaultRubyParser.y"
{
yyVal = lexer.strTerm();
lexer.setStrTerm(null);
lexer.setState(LexState.EXPR_BEG);
}
break;
case 397:
// line 1540 "DefaultRubyParser.y"
{
lexer.setStrTerm(((Node)yyVals[-2+yyTop]));
Node node = ((Node)yyVals[-1+yyTop]);
if (node instanceof NewlineNode) {
node = ((NewlineNode)node).getNextNode();
}
yyVal = support.newEvStrNode(getPosition(), node);
}
break;
case 398:
// line 1551 "DefaultRubyParser.y"
{
yyVal = new GlobalVarNode(getPosition(), ((String)yyVals[0+yyTop]));
}
break;
case 399:
// line 1554 "DefaultRubyParser.y"
{
yyVal = new InstVarNode(getPosition(), ((String)yyVals[0+yyTop]));
}
break;
case 400:
// line 1557 "DefaultRubyParser.y"
{
yyVal = new ClassVarNode(getPosition(), ((String)yyVals[0+yyTop]));
}
break;
case 402:
// line 1563 "DefaultRubyParser.y"
{
lexer.setState(LexState.EXPR_END);
yyVal = ((String)yyVals[0+yyTop]);
}
break;
case 407:
// line 1573 "DefaultRubyParser.y"
{
lexer.setState(LexState.EXPR_END);
/* In ruby, it seems to be possible to get a*/
/* StrNode (NODE_STR) among other node type. This */
/* is not possible for us. We will always have a */
/* DStrNode (NODE_DSTR).*/
yyVal = new DSymbolNode(getPosition(), ((DStrNode)yyVals[-1+yyTop]));
}
break;
case 408:
// line 1583 "DefaultRubyParser.y"
{
if (((Number)yyVals[0+yyTop]) instanceof Long) {
yyVal = new FixnumNode(getPosition(), ((Long)yyVals[0+yyTop]).longValue());
} else {
yyVal = new BignumNode(getPosition(), ((BigInteger)yyVals[0+yyTop]));
}
}
break;
case 409:
// line 1590 "DefaultRubyParser.y"
{
yyVal = new FloatNode(getPosition(), ((Double)yyVals[0+yyTop]).doubleValue());
}
break;
case 410:
// line 1593 "DefaultRubyParser.y"
{
yyVal = support.getOperatorCallNode((((Number)yyVals[0+yyTop]) instanceof Long ? (Node) new FixnumNode(getPosition(), ((Long)yyVals[0+yyTop]).longValue()) : (Node) new BignumNode(getPosition(), ((BigInteger)yyVals[0+yyTop]))), "-@");
}
break;
case 411:
// line 1596 "DefaultRubyParser.y"
{
yyVal = support.getOperatorCallNode(new FloatNode(getPosition(), ((Double)yyVals[0+yyTop]).doubleValue()), "-@");
}
break;
case 412:
// line 1605 "DefaultRubyParser.y"
{
yyVal = ((String)yyVals[0+yyTop]);
}
break;
case 413:
// line 1608 "DefaultRubyParser.y"
{
yyVal = ((String)yyVals[0+yyTop]);
}
break;
case 414:
// line 1611 "DefaultRubyParser.y"
{
yyVal = ((String)yyVals[0+yyTop]);
}
break;
case 415:
// line 1614 "DefaultRubyParser.y"
{
yyVal = ((String)yyVals[0+yyTop]);
}
break;
case 416:
// line 1617 "DefaultRubyParser.y"
{
yyVal = ((String)yyVals[0+yyTop]);
}
break;
case 417:
// line 1620 "DefaultRubyParser.y"
{
yyVal = new NilNode(getPosition());
}
break;
case 418:
// line 1623 "DefaultRubyParser.y"
{
yyVal = new SelfNode(getPosition());
}
break;
case 419:
// line 1626 "DefaultRubyParser.y"
{
yyVal = new TrueNode(getPosition());
}
break;
case 420:
// line 1629 "DefaultRubyParser.y"
{
yyVal = new FalseNode(getPosition());
}
break;
case 421:
// line 1632 "DefaultRubyParser.y"
{
yyVal = new StrNode(getPosition(), getPosition().getFile());
}
break;
case 422:
// line 1635 "DefaultRubyParser.y"
{
yyVal = new FixnumNode(getPosition(), getPosition().getLine());
}
break;
case 423:
// line 1639 "DefaultRubyParser.y"
{
/* Work around __LINE__ and __FILE__ */
if (yyVals[0+yyTop] instanceof INameNode) {
String name = ((INameNode)yyVals[0+yyTop]).getName();
yyVal = support.gettable(name, getPosition());
} else if (yyVals[0+yyTop] instanceof String) {
yyVal = support.gettable(((String)yyVals[0+yyTop]), getPosition());
} else {
yyVal = yyVals[0+yyTop];
}
}
break;
case 424:
// line 1652 "DefaultRubyParser.y"
{
yyVal = support.assignable(getPosition(), yyVals[0+yyTop], null);
}
break;
case 427:
// line 1659 "DefaultRubyParser.y"
{
yyVal = null;
}
break;
case 428:
// line 1662 "DefaultRubyParser.y"
{
lexer.setState(LexState.EXPR_BEG);
}
break;
case 429:
// line 1664 "DefaultRubyParser.y"
{
yyVal = ((Node)yyVals[-1+yyTop]);
}
break;
case 430:
// line 1667 "DefaultRubyParser.y"
{
yyerrok();
yyVal = null;
}
break;
case 431:
// line 1672 "DefaultRubyParser.y"
{
yyVal = ((Node)yyVals[-2+yyTop]);
lexer.setState(LexState.EXPR_BEG);
}
break;
case 432:
// line 1676 "DefaultRubyParser.y"
{
yyVal = ((Node)yyVals[-1+yyTop]);
}
break;
case 433:
// line 1680 "DefaultRubyParser.y"
{
yyVal = new ArgsNode(getPosition(), ((Integer)yyVals[-5+yyTop]).intValue(), ((ListNode)yyVals[-3+yyTop]), ((Integer)yyVals[-1+yyTop]).intValue(), ((BlockArgNode)yyVals[0+yyTop]));
}
break;
case 434:
// line 1683 "DefaultRubyParser.y"
{
yyVal = new ArgsNode(getPosition(), ((Integer)yyVals[-3+yyTop]).intValue(), ((ListNode)yyVals[-1+yyTop]), -1, ((BlockArgNode)yyVals[0+yyTop]));
}
break;
case 435:
// line 1686 "DefaultRubyParser.y"
{
yyVal = new ArgsNode(getPosition(), ((Integer)yyVals[-3+yyTop]).intValue(), null, ((Integer)yyVals[-1+yyTop]).intValue(), ((BlockArgNode)yyVals[0+yyTop]));
}
break;
case 436:
// line 1689 "DefaultRubyParser.y"
{
int h = ((Integer)yyVals[-1+yyTop]).intValue();
yyVal = new ArgsNode(getPosition(), h, null, -1, ((BlockArgNode)yyVals[0+yyTop]));
}
break;
case 437:
// line 1692 "DefaultRubyParser.y"
{
yyVal = new ArgsNode(getPosition(), 0, ((ListNode)yyVals[-3+yyTop]), ((Integer)yyVals[-1+yyTop]).intValue(), ((BlockArgNode)yyVals[0+yyTop]));
}
break;
case 438:
// line 1695 "DefaultRubyParser.y"
{
yyVal = new ArgsNode(getPosition(), 0, ((ListNode)yyVals[-1+yyTop]), -1, ((BlockArgNode)yyVals[0+yyTop]));
}
break;
case 439:
// line 1698 "DefaultRubyParser.y"
{
yyVal = new ArgsNode(getPosition(), 0, null, ((Integer)yyVals[-1+yyTop]).intValue(), ((BlockArgNode)yyVals[0+yyTop]));
}
break;
case 440:
// line 1701 "DefaultRubyParser.y"
{
yyVal = new ArgsNode(getPosition(), 0, null, -1, ((BlockArgNode)yyVals[0+yyTop]));
}
break;
case 441:
// line 1704 "DefaultRubyParser.y"
{
yyVal = new ArgsNode(getPosition(), 0, null, -1, null);
}
break;
case 442:
// line 1708 "DefaultRubyParser.y"
{
yyerror("formal argument cannot be a constant");
}
break;
case 443:
// line 1711 "DefaultRubyParser.y"
{
yyerror("formal argument cannot be an instance variable");
}
break;
case 444:
// line 1714 "DefaultRubyParser.y"
{
yyerror("formal argument cannot be a class variable");
}
break;
case 445:
// line 1717 "DefaultRubyParser.y"
{
if (!IdUtil.isLocal(((String)yyVals[0+yyTop]))) {
yyerror("formal argument must be local variable");
} else if (support.getLocalNames().isLocalRegistered(((String)yyVals[0+yyTop]))) {
yyerror("duplicate argument name");
}
support.getLocalNames().getLocalIndex(((String)yyVals[0+yyTop]));
yyVal = new Integer(1);
}
break;
case 447:
// line 1728 "DefaultRubyParser.y"
{
yyVal = new Integer(((Integer)yyVal).intValue() + 1);
}
break;
case 448:
// line 1732 "DefaultRubyParser.y"
{
if (!IdUtil.isLocal(((String)yyVals[-2+yyTop]))) {
yyerror("formal argument must be local variable");
} else if (support.getLocalNames().isLocalRegistered(((String)yyVals[-2+yyTop]))) {
yyerror("duplicate optional argument name");
}
support.getLocalNames().getLocalIndex(((String)yyVals[-2+yyTop]));
yyVal = support.assignable(getPosition(), ((String)yyVals[-2+yyTop]), ((Node)yyVals[0+yyTop]));
}
break;
case 449:
// line 1742 "DefaultRubyParser.y"
{
yyVal = new ArrayNode(getPosition()).add(((Node)yyVals[0+yyTop]));
}
break;
case 450:
// line 1745 "DefaultRubyParser.y"
{
yyVal = ((ListNode)yyVals[-2+yyTop]).add(((Node)yyVals[0+yyTop]));
}
break;
case 453:
// line 1752 "DefaultRubyParser.y"
{
if (!IdUtil.isLocal(((String)yyVals[0+yyTop]))) {
yyerror("rest argument must be local variable");
} else if (support.getLocalNames().isLocalRegistered(((String)yyVals[0+yyTop]))) {
yyerror("duplicate rest argument name");
}
yyVal = new Integer(support.getLocalNames().getLocalIndex(((String)yyVals[0+yyTop])));
}
break;
case 454:
// line 1760 "DefaultRubyParser.y"
{
yyVal = new Integer(-2);
}
break;
case 457:
// line 1767 "DefaultRubyParser.y"
{
if (!IdUtil.isLocal(((String)yyVals[0+yyTop]))) {
yyerror("block argument must be local variable");
} else if (support.getLocalNames().isLocalRegistered(((String)yyVals[0+yyTop]))) {
yyerror("duplicate block argument name");
}
yyVal = new BlockArgNode(getPosition(), support.getLocalNames().getLocalIndex(((String)yyVals[0+yyTop])));
}
break;
case 458:
// line 1776 "DefaultRubyParser.y"
{
yyVal = ((BlockArgNode)yyVals[0+yyTop]);
}
break;
case 459:
// line 1779 "DefaultRubyParser.y"
{
yyVal = null;
}
break;
case 460:
// line 1783 "DefaultRubyParser.y"
{
if (((Node)yyVals[0+yyTop]) instanceof SelfNode) {
yyVal = new SelfNode(null);
} else {
support.checkExpression(((Node)yyVals[0+yyTop]));
yyVal = ((Node)yyVals[0+yyTop]);
}
}
break;
case 461:
// line 1791 "DefaultRubyParser.y"
{
lexer.setState(LexState.EXPR_BEG);
}
break;
case 462:
// line 1793 "DefaultRubyParser.y"
{
if (((Node)yyVals[-2+yyTop]) instanceof ILiteralNode) {
/*case Constants.NODE_STR:
case Constants.NODE_DSTR:
case Constants.NODE_XSTR:
case Constants.NODE_DXSTR:
case Constants.NODE_DREGX:
case Constants.NODE_LIT:
case Constants.NODE_ARRAY:
case Constants.NODE_ZARRAY:*/
yyerror("Can't define single method for literals.");
}
support.checkExpression(((Node)yyVals[-2+yyTop]));
yyVal = ((Node)yyVals[-2+yyTop]);
}
break;
case 464:
// line 1810 "DefaultRubyParser.y"
{
yyVal = ((ListNode)yyVals[-1+yyTop]);
}
break;
case 465:
// line 1813 "DefaultRubyParser.y"
{
if (ListNodeUtil.getLength(((ListNode)yyVals[-1+yyTop])) % 2 != 0) {
yyerror("Odd number list for Hash.");
}
yyVal = ((ListNode)yyVals[-1+yyTop]);
}
break;
case 467:
// line 1821 "DefaultRubyParser.y"
{
yyVal = ListNodeUtil.addAll(((ListNode)yyVals[-2+yyTop]), ((ListNode)yyVals[0+yyTop]));
}
break;
case 468:
// line 1825 "DefaultRubyParser.y"
{
yyVal = new ArrayNode(getPosition()).add(((Node)yyVals[-2+yyTop])).add(((Node)yyVals[0+yyTop]));
}
break;
case 488:
// line 1855 "DefaultRubyParser.y"
{
yyerrok();
}
break;
case 491:
// line 1861 "DefaultRubyParser.y"
{
yyerrok();
}
break;
case 492:
// line 1865 "DefaultRubyParser.y"
{
yyVal = null;
}
break;
case 493:
// line 1869 "DefaultRubyParser.y"
{ yyVal = null;
}
break;
case 494:
// line 1872 "DefaultRubyParser.y"
{ yyVal = null;
}
break;
// line 2921 "-"
}
yyTop -= YyLenClass.yyLen[yyN];
yyState = yyStates[yyTop];
int yyM = YyLhsClass.yyLhs[yyN];
if (yyState == 0 && yyM == 0) {
yyState = yyFinal;
if (yyToken < 0) {
yyToken = yyLex.advance() ? yyLex.token() : 0;
}
if (yyToken == 0) {
return yyVal;
}
continue yyLoop;
}
if ((yyN = YyGindexClass.yyGindex[yyM]) != 0 && (yyN += yyState) >= 0
&& yyN < YyTableClass.yyTable.length && YyCheckClass.yyCheck[yyN] == yyState)
yyState = YyTableClass.yyTable[yyN];
else
yyState = YyDgotoClass.yyDgoto[yyM];
continue yyLoop;
}
}
}
protected static final class YyLhsClass {
public static final short yyLhs [] = { -1,
97, 0, 18, 17, 19, 19, 19, 19, 100, 20,
20, 20, 20, 20, 20, 20, 20, 20, 20, 101,
20, 20, 20, 20, 20, 20, 20, 20, 20, 20,
20, 20, 20, 20, 21, 21, 21, 21, 21, 21,
29, 25, 25, 25, 25, 25, 48, 48, 48, 102,
63, 24, 24, 24, 24, 24, 24, 24, 24, 69,
69, 71, 71, 70, 70, 70, 70, 70, 70, 65,
65, 74, 74, 66, 66, 66, 66, 66, 66, 66,
66, 59, 59, 59, 59, 59, 59, 59, 59, 91,
91, 16, 16, 16, 92, 92, 92, 92, 92, 85,
85, 54, 104, 54, 93, 93, 93, 93, 93, 93,
93, 93, 93, 93, 93, 93, 93, 93, 93, 93,
93, 93, 93, 93, 93, 93, 93, 93, 93, 93,
103, 103, 103, 103, 103, 103, 103, 103, 103, 103,
103, 103, 103, 103, 103, 103, 103, 103, 103, 103,
103, 103, 103, 103, 103, 103, 103, 103, 103, 103,
103, 103, 103, 103, 103, 103, 103, 103, 103, 103,
103, 22, 22, 22, 22, 22, 22, 22, 22, 22,
22, 22, 22, 22, 22, 22, 22, 22, 22, 22,
22, 22, 22, 22, 22, 22, 22, 22, 22, 22,
22, 22, 22, 22, 22, 22, 22, 22, 22, 22,
22, 22, 106, 22, 22, 22, 67, 78, 78, 78,
78, 78, 78, 36, 36, 36, 36, 37, 37, 38,
38, 38, 38, 38, 38, 38, 38, 38, 39, 39,
39, 39, 39, 39, 39, 39, 39, 39, 39, 39,
108, 41, 40, 109, 40, 110, 40, 44, 43, 43,
72, 72, 64, 64, 64, 23, 23, 23, 23, 23,
23, 23, 23, 23, 23, 23, 23, 23, 23, 23,
23, 23, 23, 23, 23, 23, 111, 23, 23, 23,
23, 23, 23, 113, 115, 23, 116, 117, 23, 23,
23, 23, 118, 119, 23, 120, 23, 122, 123, 23,
124, 23, 125, 23, 127, 128, 23, 23, 23, 23,
23, 30, 112, 112, 112, 112, 114, 114, 114, 33,
33, 31, 31, 57, 57, 58, 58, 58, 58, 129,
62, 47, 47, 47, 26, 26, 26, 26, 26, 26,
130, 61, 131, 61, 68, 73, 73, 73, 32, 32,
79, 79, 77, 77, 77, 34, 34, 35, 35, 13,
13, 13, 2, 3, 3, 4, 5, 6, 10, 10,
28, 28, 12, 12, 11, 11, 27, 27, 7, 7,
8, 8, 9, 132, 9, 133, 9, 56, 56, 56,
56, 87, 86, 86, 86, 86, 15, 14, 14, 14,
14, 80, 80, 80, 80, 80, 80, 80, 80, 80,
80, 80, 42, 81, 55, 55, 46, 134, 46, 46,
51, 51, 52, 52, 52, 52, 52, 52, 52, 52,
52, 94, 94, 94, 94, 95, 95, 53, 84, 84,
135, 135, 96, 96, 136, 136, 50, 49, 49, 1,
137, 1, 83, 83, 83, 75, 75, 76, 88, 88,
88, 89, 89, 89, 89, 90, 90, 90, 126, 126,
98, 98, 105, 105, 107, 107, 107, 121, 121, 99,
99, 60, 82, 45,
};
} /* End of class YyLhsClass */
protected static final class YyLenClass {
public static final short yyLen [] = { 2,
0, 2, 4, 2, 1, 1, 3, 2, 0, 4,
3, 3, 3, 2, 3, 3, 3, 3, 3, 0,
5, 4, 3, 3, 3, 6, 5, 5, 5, 3,
3, 3, 3, 1, 1, 3, 3, 2, 2, 1,
1, 1, 1, 2, 2, 2, 1, 4, 4, 0,
5, 2, 3, 4, 5, 4, 5, 2, 2, 1,
3, 1, 3, 1, 2, 3, 2, 2, 1, 1,
3, 2, 3, 1, 4, 3, 3, 3, 3, 2,
1, 1, 4, 3, 3, 3, 3, 2, 1, 1,
1, 2, 1, 3, 1, 1, 1, 1, 1, 1,
1, 1, 0, 4, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 3, 5, 3, 6, 5, 5, 5, 5, 4,
3, 3, 3, 3, 3, 3, 3, 3, 3, 4,
4, 2, 2, 3, 3, 3, 3, 3, 3, 3,
3, 3, 3, 3, 3, 3, 2, 2, 3, 3,
3, 3, 0, 4, 5, 1, 1, 1, 2, 2,
5, 2, 3, 3, 4, 4, 6, 1, 1, 1,
2, 5, 2, 5, 4, 7, 3, 1, 4, 3,
5, 7, 2, 5, 4, 6, 7, 9, 3, 1,
0, 2, 1, 0, 3, 0, 4, 2, 2, 1,
1, 3, 3, 4, 2, 1, 1, 1, 1, 1,
1, 1, 1, 1, 3, 4, 3, 3, 2, 4,
3, 3, 1, 4, 3, 1, 0, 6, 2, 1,
2, 6, 6, 0, 0, 7, 0, 0, 7, 5,
4, 5, 0, 0, 9, 0, 6, 0, 0, 8,
0, 5, 0, 6, 0, 0, 9, 1, 1, 1,
1, 1, 1, 1, 1, 2, 1, 1, 1, 1,
5, 1, 2, 1, 1, 1, 2, 1, 3, 0,
5, 2, 4, 4, 2, 4, 4, 3, 2, 1,
0, 5, 0, 5, 5, 1, 4, 2, 1, 1,
6, 0, 1, 1, 1, 2, 1, 2, 1, 1,
1, 1, 1, 1, 2, 3, 3, 3, 3, 3,
0, 3, 1, 2, 3, 3, 0, 3, 0, 2,
0, 2, 1, 0, 3, 0, 4, 1, 1, 1,
1, 2, 1, 1, 1, 1, 3, 1, 1, 2,
2, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 0, 4, 2,
4, 2, 6, 4, 4, 2, 4, 2, 2, 1,
0, 1, 1, 1, 1, 1, 3, 3, 1, 3,
1, 1, 2, 1, 1, 1, 2, 2, 0, 1,
0, 5, 1, 2, 2, 1, 3, 3, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
0, 1, 0, 1, 0, 1, 1, 1, 1, 1,
2, 0, 0, 0,
};
} /* End class YyLenClass */
protected static final class YyDefRedClass {
public static final short yyDefRed [] = { 1,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 294, 297, 0, 0, 0, 320, 321, 0, 0,
0, 418, 417, 419, 420, 0, 0, 0, 20, 0,
422, 421, 0, 0, 414, 413, 0, 416, 408, 409,
425, 426, 0, 0, 0, 0, 0, 0, 0, 0,
0, 389, 391, 391, 0, 0, 0, 0, 0, 267,
0, 374, 268, 269, 270, 271, 266, 370, 372, 2,
0, 0, 0, 0, 0, 0, 35, 0, 0, 272,
0, 43, 0, 0, 5, 0, 70, 0, 60, 0,
0, 0, 371, 0, 0, 318, 319, 283, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 322, 0,
273, 423, 0, 93, 311, 140, 151, 141, 164, 137,
157, 147, 146, 162, 145, 144, 139, 165, 149, 138,
152, 156, 158, 150, 143, 159, 166, 161, 0, 0,
0, 0, 136, 155, 154, 167, 168, 169, 170, 171,
135, 142, 133, 134, 0, 0, 0, 97, 0, 126,
127, 124, 108, 109, 110, 113, 115, 111, 128, 129,
116, 117, 121, 112, 114, 105, 106, 107, 118, 119,
120, 122, 123, 125, 130, 461, 0, 460, 313, 98,
99, 160, 153, 163, 148, 131, 132, 95, 96, 0,
0, 102, 101, 100, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 489, 488, 0, 0, 0,
490, 0, 0, 0, 0, 0, 0, 334, 335, 0,
0, 0, 0, 0, 230, 45, 238, 0, 0, 0,
466, 46, 44, 0, 59, 0, 0, 349, 58, 38,
0, 9, 484, 0, 0, 0, 192, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 218, 0, 0,
0, 0, 0, 463, 0, 0, 0, 0, 68, 0,
405, 404, 406, 0, 402, 403, 0, 0, 0, 0,
0, 0, 0, 0, 0, 207, 39, 208, 375, 4,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 340, 342, 353, 351, 291, 0,
0, 0, 0, 0, 0, 0, 72, 0, 0, 0,
0, 0, 345, 0, 289, 0, 0, 90, 0, 92,
410, 411, 0, 428, 306, 427, 0, 0, 0, 0,
0, 480, 479, 315, 0, 103, 0, 0, 275, 0,
325, 324, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 491, 0, 0, 0, 0,
0, 0, 303, 0, 258, 0, 0, 231, 260, 0,
233, 285, 0, 0, 253, 252, 0, 0, 0, 0,
0, 11, 13, 12, 0, 287, 0, 0, 0, 0,
0, 0, 0, 277, 0, 0, 0, 219, 0, 486,
220, 0, 222, 281, 0, 465, 464, 282, 0, 0,
0, 0, 393, 396, 394, 407, 392, 376, 390, 377,
378, 379, 380, 383, 0, 385, 0, 386, 0, 0,
0, 15, 16, 17, 18, 19, 36, 37, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 348, 0, 0, 0, 474, 0, 0, 475, 472,
473, 0, 0, 0, 30, 0, 0, 23, 31, 261,
0, 24, 33, 0, 0, 66, 73, 0, 25, 50,
53, 0, 430, 0, 0, 0, 0, 0, 94, 0,
0, 0, 0, 0, 0, 443, 442, 444, 452, 456,
455, 451, 0, 440, 0, 0, 449, 0, 446, 0,
0, 0, 0, 0, 365, 364, 0, 0, 0, 0,
332, 0, 326, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 301, 329, 328, 295, 327,
298, 0, 0, 0, 0, 0, 0, 0, 237, 468,
0, 259, 0, 0, 0, 0, 467, 284, 0, 0,
256, 250, 0, 0, 0, 0, 0, 0, 0, 0,
224, 10, 0, 0, 0, 22, 0, 0, 276, 223,
0, 262, 0, 0, 0, 0, 0, 0, 0, 382,
384, 388, 0, 0, 0, 338, 0, 0, 336, 0,
0, 0, 0, 347, 0, 0, 0, 0, 229, 346,
0, 228, 344, 49, 343, 48, 265, 0, 0, 71,
0, 309, 0, 0, 280, 312, 0, 316, 0, 0,
0, 432, 0, 438, 0, 436, 0, 439, 453, 457,
104, 0, 0, 367, 333, 0, 3, 369, 0, 330,
0, 0, 0, 0, 0, 0, 300, 302, 358, 0,
0, 0, 0, 0, 0, 0, 0, 235, 0, 0,
0, 0, 0, 243, 255, 225, 0, 0, 226, 0,
0, 0, 21, 0, 0, 0, 398, 399, 400, 401,
395, 0, 337, 0, 0, 0, 0, 0, 29, 0,
57, 0, 0, 27, 0, 28, 55, 0, 0, 0,
0, 0, 429, 307, 462, 0, 448, 0, 314, 0,
458, 450, 0, 0, 447, 0, 0, 0, 0, 366,
0, 0, 368, 0, 292, 0, 293, 0, 0, 0,
0, 304, 232, 0, 234, 249, 257, 0, 240, 0,
0, 0, 0, 288, 221, 397, 339, 341, 354, 352,
0, 26, 264, 0, 0, 0, 431, 437, 0, 434,
435, 0, 0, 0, 0, 0, 0, 357, 359, 355,
360, 296, 299, 0, 0, 0, 0, 239, 0, 245,
0, 227, 51, 310, 0, 0, 0, 0, 0, 0,
0, 361, 0, 0, 236, 241, 0, 0, 0, 244,
317, 433, 0, 331, 305, 0, 0, 246, 0, 242,
0, 247, 0, 248,
};
} /* End of class YyDefRedClass */
protected static final class YyDgotoClass {
public static final short yyDgoto [] = { 1,
187, 60, 61, 62, 63, 64, 287, 284, 457, 65,
66, 465, 67, 68, 69, 108, 205, 206, 71, 72,
73, 74, 75, 76, 77, 78, 293, 291, 209, 258,
710, 840, 711, 703, 707, 669, 670, 236, 621, 416,
245, 80, 408, 612, 409, 365, 81, 82, 694, 781,
565, 566, 567, 201, 211, 751, 227, 658, 212, 85,
355, 336, 541, 529, 86, 87, 238, 395, 88, 89,
264, 269, 595, 90, 270, 241, 578, 271, 378, 213,
214, 274, 275, 568, 202, 285, 93, 113, 548, 512,
114, 204, 519, 569, 570, 571, 2, 219, 220, 425,
255, 681, 191, 574, 254, 427, 441, 246, 625, 731,
633, 383, 222, 599, 722, 223, 723, 607, 844, 545,
384, 542, 772, 370, 375, 374, 554, 776, 505, 507,
506, 649, 648, 544, 572, 573, 371,
};
} /* End of class YyDgotoClass */
protected static final class YySindexClass {
public static final short yySindex [] = { 0,
0,14064,14483,18684,18972,17554,17256,14064,15827,15827,
6926, 0, 0,18780,14675,14675, 0, 0,14675, 14,
65, 0, 0, 0, 0,15827,17166, 100, 0, 27,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0,16691,16691, -147,14283,15827,15923,16691,19068,
17632, 0, 0, 0, 161, 171, 141,16787,16691, 0,
-117, 0, 0, 0, 0, 0, 0, 0, 0, 0,
86, 723, 206,10550, 0, -35, 0, -47, 94, 0,
7, 0, -80, 204, 0, 233, 0, 275, 0,18876,
0, -44, 0, 44, 723, 0, 0, 0, 14, 65,
100, 0, 0,15827, 187,14064, 217, 202, 0, 103,
0, 0, 44, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 29, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0,17632,
300, 0, 0, 0, 93, 96, 98, 206, 78, 106,
73, 367, 0, 124, 78, 0, 0, 86, -156, 426,
0,15827,15827, 196, 131, 0, 242, 0, 0, 0,
16691,16691,16691,10550, 0, 0, 0, 176, 490, 501,
0, 0, 0,14579, 0,14771,14675, 0, 0, 0,
52, 0, 0, 477, 430,14064, 0, 137, 243, 237,
14283, 545, 0, 551, 154,16691, 100, 0, 121, 156,
512, 235, 156, 0, 498, 321, 153, 0, 0, 0,
0, 0, 0, 339, 0, 0, 403, 505, 250, 280,
613, 283, -263, 324, 332, 0, 0, 0, 0, 0,
14383,15827,15827,15827,15827,14483,15827,15827,16691,16691,
16691,16691,16691,16691,16691,16691,16691,16691,16691,16691,
16691,16691,16691,16691,16691,16691,16691,16691,16691,16691,
16691,16691,16691,16691, 0, 0, 0, 0, 0, 9090,
15923,11110,17677,17677,16787,16019, 0,16019,14283,19068,
611,16787, 0, 315, 0, 477, 206, 0, 0, 0,
0, 0, 86, 0, 0, 0,17975,15923,17677,14064,
15827, 0, 0, 0, 185, 0,16115, 391, 0, 237,
0, 0,14064, 411,18006,15923,18043,16691,16691,16691,
14064, 424,14064,16211, 432, 0, 80, 80, 0,18341,
15923,18372, 0, 658, 0,16691,14867, 0, 0,14963,
0, 0, 662, 5768, 0, 0, -35, 100, 87, 664,
669, 0, 0, 0,17256, 0,16691,14064, 586,18006,
18043,16691, 678, 0, 0, 679, 4721, 0,16307, 0,
0,16691, 0, 0,16691, 0, 0, 0, 0,18409,
15923,18440, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 16, 0, 691, 0,16691,16691,
723, 0, 0, 0, 0, 0, 0, 0, 243, 1576,
1576, 1576, 1576, 530, 530,10688,13379, 1576, 1576,12918,
12918, 238, 238, 5160, 530, 530, 688, 688, 588, 75,
75, 243, 243, 243, -52, -52, -52, 392, 0, 401,
65, 0, 0, 655, 415, 0, 442, 65, 0, 0,
0, 65, 65,10550, 0,16691, 5621, 0, 0, 0,
747, 0, 0, 0, 739, 0, 0,10550, 0, 0,
0, 86, 0,15827,14064, 0, 0, 65, 0, 701,
65, 532, 154,17930, 737, 0, 0, 0, 0, 0,
0, 0, 240, 0,14064, 86, 0, 756, 0, 758,
763, 507, 511,17256, 0, 0, 0, 480,14064, 558,
0, 404, 0, 486, 401, 732, 489, 492, 5621, 391,
575, 580,16691, 789, 78, 0, 0, 0, 0, 0,
0, 0, 0, 748, 0, 0,15827, 502, 0, 0,
16691, 0, 176, 805,16691, 176, 0, 0,16691,10550,
0, 0, 19, 806, 828, 829,17677,17677, 836,15059,
0, 0,15827,10550, 753, 0,10550, 0, 0, 0,
16691, 0, 0, 0, 790, 0, 0,14064, 284, 0,
0, 0, 243, 243,16691, 0,18588,14064, 0,14064,
14064,16787,16691, 0, 315, 547,16787,16787, 0, 0,
315, 0, 0, 0, 0, 0, 0,16691,16403, 0,
-52, 0, 86, 618, 0, 0, 845, 0,16691, 100,
623, 0, 133, 0, 240, 0, -24, 0, 0, 0,
0,19164, 78, 0, 0,14064, 0, 0,15827, 0,
628,16691, 552,16691,16691, 636, 0, 0, 0,16499,
14064,14064,14064, 0, 80, 658,15155, 0, 658, 658,
854,15251,15347, 0, 0, 0, 65, 65, 0, -35,
87, -4, 0, 4721, 0, 776, 0, 0, 0, 0,
0,10550, 0, 781, 645, 651, 792,10550, 0,10550,
0,16787,10550, 0,10550, 0, 0,10550,16691, 0,
14064,14064, 0, 0, 0, 185, 0, 879, 0, 737,
0, 0, 763, 883, 0, 763, 620, 165, 0, 0,
0,14064, 0, 78, 0,16691, 0,16691, 286, 666,
667, 0, 0,16691, 0, 0, 0,16691, 0, 895,
896,16691, 901, 0, 0, 0, 0, 0, 0, 0,
10550, 0, 0, 819, 683,14064, 0, 0, 133, 0,
0, 0,18477,15923,18508, 93,14064, 0, 0, 0,
0, 0, 0,14064, 9494, 658,15443, 0,15539, 0,
658, 0, 0, 0, 684, 763, 0, 0, 859, 0,
0, 0, 404, 689, 0, 0,16691, 911,16691, 0,
0, 0, 0, 0, 0, 658,15635, 0, 658, 0,
16691, 0, 658, 0,
};
} /* End of class YySindexClass */
protected static final class YyRindexClass {
public static final short yyRindex [] = { 0,
0, 210, 0, 0, 0, 0, 0, 726, 0, 0,
343, 0, 0, 0,13267,13352, 0, 0,13455, 4233,
3689, 0, 0, 0, 0, 0, 0,16595, 0, 0,
0, 0, 1897, 2889, 0, 0, 1993, 0, 0, 0,
0, 0, 0, 0, 0, 82, 0, 863, 834, 419,
621, 0, 0, 0, 625, -210, 0, 0, 0, 0,
8212, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1209, 5519, 6088,13915, 8297,14005, 0, 8393, 0, 0,
17121, 0,13830, 0, 0, 0, 0, 0, 0, 464,
13754, 0, 0,15731, 6345, 0, 0, 0, 8696, 7246,
920, 5564, 5876, 0, 0, 82, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 736, 870,
903, 1114, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 1456, 1582, 1669, 0, 1765, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
9428, 0, 0, 0, 406, 0, 0, 7055, 0, 0,
7728, 0, 7335, 0, 0, 0, 0, 690, 0, 348,
0, 0, 0, 0, 0, 55, 0, 0, 0, 525,
0, 0, 0, 1799, 0, 0, 0,12925, 8027, 8027,
0, 0, 0, 0, 0, 0, 922, 0, 0, 0,
0, 0, 0,16883, 0, 49, 0, 0, 9180,13904,
82, 0, 102, 0, 927, 0, 877, 0, 878, 878,
0, 851, 851, 0, 0, 0, 0, 1016, 0, 1617,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 8781, 8877, 0, 0, 0, 0, 0,
1867, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
863, 0, 0, 0, 0, 0, 0, 0, 82, 577,
600, 0, 0, 6735, 0, 0, 119, 0, 6390, 0,
0, 0, 0, 0, 0, 0, 0, 863, 0, 726,
0, 0, 0, 0, 132, 0, 21, 417, 0, 7813,
0, 0, 473, 6497, 0, 863, 0, 0, 0, 0,
463, 0, 68, 0, 0, 0, 0, 0, 794, 0,
863, 0, 0, 8027, 0, 0, 0, 0, 0, 0,
0, 0, 0, 941, 0, 0, 115, 927, 927, 374,
0, 0, 0, 0, 0, 0, 0, 49, 0, 0,
0, 0, 0, 0, 465, 0, 877, 0, 894, 0,
0, 89, 0, 0, 860, 0, 0, 0, 1860, 0,
863, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
6446, 0, 0, 0, 0, 0, 0, 0, 9253, 8116,
8600,11529,11708,11070,11285,11794, 9857,11871,11922,11973,
12011,10497,10570, 0,11362,11435,10920,10993,10647,10122,
10199, 9342, 9584, 9673, 6624, 6624, 6817, 4585, 3241, 5120,
15731, 0, 3337, 0, 4681, 0, 5024, 3785, 0, 0,
0, 5463, 5463,12271, 0, 0,17363, 0, 0, 0,
0, 0, 0, 7546, 0, 0, 0,12309, 0, 0,
0, 0, 0, 0, 726, 5977, 6289, 0, 0, 0,
7425, 0, 927, 0, 569, 0, 0, 0, 0, 0,
0, 0, 377, 0, 726, 0, 0, 209, 0, 209,
209, 913, 0, 0, 0, 0, 60, 232, 550, 727,
0, 727, 0, 2345, 4137, 0, 2441, 2793,13007, 727,
0, 0, 0, 493, 0, 0, 0, 0, 0, 0,
0, 744, 152, 0, 1507, 1736, 0, 0, 0, 0,
0, 0,13167, 8027, 0, 0, 0, 0, 0, 110,
0, 0, 0, 952, 0, 0, 0, 0, 0, 0,
0, 0, 0,12348, 0, 0,12387, 472, 0, 0,
0, 0, 940, 731, 0, 1252, 1482, 49, 0, 0,
0, 0, 9746,10049, 0, 0, 0, 68, 0, 68,
49, 0, 0, 0, 8511,14203, 0, 0, 0, 0,
13847, 0, 0, 0, 0, 0, 0, 0, 0, 0,
6817, 0, 0, 0, 0, 0, 0, 0, 0, 927,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 68, 0, 0, 0, 0,
0, 0, 7909, 0, 0, 0, 0, 0, 0, 0,
337, 68, 68, 1111, 0, 8027, 0, 0, 8027, 952,
0, 0, 0, 0, 0, 0, 48, 48, 0, 0,
927, 0, 0, 877, 2310, 0, 0, 0, 0, 0,
0,12425, 0, 0, 0, 0, 0,12464, 0,12729,
0, 0,12765, 0,12816, 0, 0,12852, 0,11832,
49, 726, 0, 0, 0, 132, 0, 0, 0, 0,
0, 0, 209, 209, 0, 209, 0, 0, 111, 0,
114, 726, 0, 0, 0, 0, 0, 0, 727, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 952,
952, 0, 0, 0, 0, 0, 0, 0, 0, 0,
12889, 0, 0, 0, 0, 726, 0, 0, 0, 0,
0, 149, 0, 863, 0, 406, 473, 0, 0, 0,
0, 0, 0, 68, 8027, 952, 0, 0, 0, 0,
952, 0, 0, 0, 0, 209, 536, 122, 0, 835,
892, 0, 727, 0, 0, 0, 0, 952, 0, 0,
0, 0, 180, 0, 0, 952, 0, 0, 952, 0,
0, 0, 952, 0,
};
} /* End of class YyRindexClass */
protected static final class YyGindexClass {
public static final short yyGindex [] = { 0,
0, 0, 0, 935, 0, 0, 0, 631, -205, 0,
0, 0, 0, 0, 0, 992, 28, -359, 0, 66,
1042, -15, 57, 2, -23, 0, 0, 0, 36, 460,
-366, 0, 135, 0, 0, -13, -256, 857, 0, 0,
1, 997, -189, 26, 0, 0, -207, 0, 216, -362,
231, 445, -608, 0, 663, 0, 352, -318, 1092, 986,
933, 0, -430, -190, 924, -30, 985, -367, -11, 31,
-235, 8, 0, 0, -10, -307, 0, -303, 199, 1024,
1306, 795, 0, 341, -20, 0, 25, 888, -276, 0,
-32, 4, 9, 342, 0, -565, 0, 35, 970, 0,
0, 0, 0, 0, 83, 0, 266, 0, 0, 0,
0, -213, 0, -379, 0, 0, 0, 0, 0, 0,
45, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0,
};
} /* End of class YyGindexClass */
protected static final class YyTableClass {
public static final short[] yyTable = YyTables.yyTable();
} /* End of class YyTableClass */
protected static final class YyCheckClass {
public static final short[] yyCheck = YyTables.yyCheck();
} /* End of class YyCheckClass */
protected static final class YyNameClass {
public static final String yyName [] = {
"end-of-file",null,null,null,null,null,null,null,null,null,"'\\n'",
null,null,null,null,null,null,null,null,null,null,null,null,null,null,
null,null,null,null,null,null,null,"' '","'!'",null,null,null,"'%'",
"'&'",null,"'('","')'","'*'","'+'","','","'-'","'.'","'/'",null,null,
null,null,null,null,null,null,null,null,"':'","';'","'<'","'='","'>'",
"'?'",null,null,null,null,null,null,null,null,null,null,null,null,
null,null,null,null,null,null,null,null,null,null,null,null,null,null,
null,"'['",null,"']'","'^'",null,"'`'",null,null,null,null,null,null,
null,null,null,null,null,null,null,null,null,null,null,null,null,null,
null,null,null,null,null,null,"'{'","'|'","'}'","'~'",null,null,null,
null,null,null,null,null,null,null,null,null,null,null,null,null,null,
null,null,null,null,null,null,null,null,null,null,null,null,null,null,
null,null,null,null,null,null,null,null,null,null,null,null,null,null,
null,null,null,null,null,null,null,null,null,null,null,null,null,null,
null,null,null,null,null,null,null,null,null,null,null,null,null,null,
null,null,null,null,null,null,null,null,null,null,null,null,null,null,
null,null,null,null,null,null,null,null,null,null,null,null,null,null,
null,null,null,null,null,null,null,null,null,null,null,null,null,null,
null,null,null,null,null,null,null,null,null,null,null,null,null,null,
null,"kCLASS","kMODULE","kDEF","kUNDEF","kBEGIN","kRESCUE","kENSURE",
"kEND","kIF","kUNLESS","kTHEN","kELSIF","kELSE","kCASE","kWHEN",
"kWHILE","kUNTIL","kFOR","kBREAK","kNEXT","kREDO","kRETRY","kIN",
"kDO","kDO_COND","kDO_BLOCK","kRETURN","kYIELD","kSUPER","kSELF",
"kNIL","kTRUE","kFALSE","kAND","kOR","kNOT","kIF_MOD","kUNLESS_MOD",
"kWHILE_MOD","kUNTIL_MOD","kRESCUE_MOD","kALIAS","kDEFINED","klBEGIN",
"klEND","k__LINE__","k__FILE__","tIDENTIFIER","tFID","tGVAR","tIVAR",
"tCONSTANT","tCVAR","tINTEGER","tFLOAT","tSTRING_CONTENT","tNTH_REF",
"tBACK_REF","tREGEXP_END","tUPLUS","tUMINUS","tPOW","tCMP","tEQ",
"tEQQ","tNEQ","tGEQ","tLEQ","tANDOP","tOROP","tMATCH","tNMATCH",
"tDOT2","tDOT3","tAREF","tASET","tLSHFT","tRSHFT","tCOLON2","tCOLON3",
"tOP_ASGN","tASSOC","tLPAREN","tLPAREN_ARG","tLBRACK","tLBRACE",
"tLBRACE_ARG","tSTAR","tAMPER","tSYMBEG","tSTRING_BEG","tXSTRING_BEG",
"tREGEXP_BEG","tWORDS_BEG","tQWORDS_BEG","tSTRING_DBEG",
"tSTRING_DVAR","tSTRING_END","tLOWEST","tUMINUS_NUM","tLAST_TOKEN",
};
} /* End of class YyNameClass */
// line 1876 "DefaultRubyParser.y"
/** The parse method use an lexer stream and parse it to an AST node
* structure
*/
public RubyParserResult parse(LexerSource source) {
support.reset();
support.setResult(new RubyParserResult());
lexer.setSource(source);
try {
yyparse(lexer, null);
} catch (Exception excptn) {
excptn.printStackTrace();
}
return support.getResult();
}
public void init(RubyParserConfiguration configuration) {
support.setConfiguration(configuration);
}
// +++
// Helper Methods
void yyerrok() {}
private SourcePosition getPosition() {
return lexer.getPosition();
}
}
// line 7877 "-"
| true | true | public Object yyparse (RubyYaccLexer yyLex)
throws java.io.IOException, yyException {
if (yyMax <= 0) yyMax = 256; // initial size
int yyState = 0, yyStates[] = new int[yyMax]; // state stack
Object yyVal = null, yyVals[] = new Object[yyMax]; // value stack
int yyToken = -1; // current input
int yyErrorFlag = 0; // #tks to shift
yyLoop: for (int yyTop = 0;; ++ yyTop) {
if (yyTop >= yyStates.length) { // dynamically increase
int[] i = new int[yyStates.length+yyMax];
System.arraycopy(yyStates, 0, i, 0, yyStates.length);
yyStates = i;
Object[] o = new Object[yyVals.length+yyMax];
System.arraycopy(yyVals, 0, o, 0, yyVals.length);
yyVals = o;
}
yyStates[yyTop] = yyState;
yyVals[yyTop] = yyVal;
yyDiscarded: for (;;) { // discarding a token does not change stack
int yyN;
if ((yyN = YyDefRedClass.yyDefRed[yyState]) == 0) { // else [default] reduce (yyN)
if (yyToken < 0) {
yyToken = yyLex.advance() ? yyLex.token() : 0;
}
if ((yyN = YySindexClass.yySindex[yyState]) != 0 && (yyN += yyToken) >= 0
&& yyN < YyTableClass.yyTable.length && YyCheckClass.yyCheck[yyN] == yyToken) {
yyState = YyTableClass.yyTable[yyN]; // shift to yyN
yyVal = yyLex.value();
yyToken = -1;
if (yyErrorFlag > 0) -- yyErrorFlag;
continue yyLoop;
}
if ((yyN = YyRindexClass.yyRindex[yyState]) != 0 && (yyN += yyToken) >= 0
&& yyN < YyTableClass.yyTable.length && YyCheckClass.yyCheck[yyN] == yyToken)
yyN = YyTableClass.yyTable[yyN]; // reduce (yyN)
else
switch (yyErrorFlag) {
case 0:
yyerror("syntax error", new SyntaxErrorState(yyExpecting(yyState), YyNameClass.yyName[yyToken]));
case 1: case 2:
yyErrorFlag = 3;
do {
if ((yyN = YySindexClass.yySindex[yyStates[yyTop]]) != 0
&& (yyN += yyErrorCode) >= 0 && yyN < YyTableClass.yyTable.length
&& YyCheckClass.yyCheck[yyN] == yyErrorCode) {
yyState = YyTableClass.yyTable[yyN];
yyVal = yyLex.value();
continue yyLoop;
}
} while (-- yyTop >= 0);
throw new yyException("irrecoverable syntax error");
case 3:
if (yyToken == 0) {
throw new yyException("irrecoverable syntax error at end-of-file");
}
yyToken = -1;
continue yyDiscarded; // leave stack alone
}
}
int yyV = yyTop + 1-YyLenClass.yyLen[yyN];
yyVal = yyDefault(yyV > yyTop ? null : yyVals[yyV]);
switch (yyN) {
case 1:
// line 214 "DefaultRubyParser.y"
{
lexer.setState(LexState.EXPR_BEG);
support.initTopLocalVariables();
/* Fix: Move to ruby runtime....?*/
/*if (ruby.getRubyClass() == ruby.getClasses().getObjectClass()) {*/
/* support.setClassNest(0);*/
/*} else {*/
/* support.setClassNest(1);*/
/*}*/
}
break;
case 2:
// line 224 "DefaultRubyParser.y"
{
if (((Node)yyVals[0+yyTop]) != null && !support.isCompileForEval()) {
/* last expression should not be void */
if (((Node)yyVals[0+yyTop]) instanceof BlockNode) {
support.checkUselessStatement(ListNodeUtil.getLast(((BlockNode)yyVals[0+yyTop])));
} else {
support.checkUselessStatement(((Node)yyVals[0+yyTop]));
}
}
support.getResult().setAST(support.appendToBlock(support.getResult().getAST(), ((Node)yyVals[0+yyTop])));
support.updateTopLocalVariables();
support.setClassNest(0);
}
break;
case 3:
// line 241 "DefaultRubyParser.y"
{
Node node = ((Node)yyVals[-3+yyTop]);
if (((RescueBodyNode)yyVals[-2+yyTop]) != null) {
node = new RescueNode(getPosition(), ((Node)yyVals[-3+yyTop]), ((RescueBodyNode)yyVals[-2+yyTop]), ((Node)yyVals[-1+yyTop]));
} else if (((Node)yyVals[-1+yyTop]) != null) {
errorHandler.handleError(IErrors.WARN, null, "else without rescue is useless");
node = support.appendToBlock(((Node)yyVals[-3+yyTop]), ((Node)yyVals[-1+yyTop]));
}
if (((Node)yyVals[0+yyTop]) != null) {
node = new EnsureNode(getPosition(), node, ((Node)yyVals[0+yyTop]));
}
yyVal = node;
}
break;
case 4:
// line 257 "DefaultRubyParser.y"
{
if (((Node)yyVals[-1+yyTop]) instanceof BlockNode) {
support.checkUselessStatements(((BlockNode)yyVals[-1+yyTop]));
}
yyVal = ((Node)yyVals[-1+yyTop]);
}
break;
case 6:
// line 265 "DefaultRubyParser.y"
{
yyVal = support.newline_node(((Node)yyVals[0+yyTop]), getPosition());
}
break;
case 7:
// line 268 "DefaultRubyParser.y"
{
yyVal = support.appendToBlock(((Node)yyVals[-2+yyTop]), support.newline_node(((Node)yyVals[0+yyTop]), getPosition()));
}
break;
case 8:
// line 271 "DefaultRubyParser.y"
{
yyVal = ((Node)yyVals[0+yyTop]);
}
break;
case 9:
// line 275 "DefaultRubyParser.y"
{
lexer.setState(LexState.EXPR_FNAME);
}
break;
case 10:
// line 277 "DefaultRubyParser.y"
{
yyVal = new AliasNode(getPosition(), ((String)yyVals[-2+yyTop]), ((String)yyVals[0+yyTop]));
}
break;
case 11:
// line 280 "DefaultRubyParser.y"
{
yyVal = new VAliasNode(getPosition(), ((String)yyVals[-1+yyTop]), ((String)yyVals[0+yyTop]));
}
break;
case 12:
// line 283 "DefaultRubyParser.y"
{
yyVal = new VAliasNode(getPosition(), ((String)yyVals[-1+yyTop]), "$" + ((BackRefNode)yyVals[0+yyTop]).getType()); /* XXX*/
}
break;
case 13:
// line 286 "DefaultRubyParser.y"
{
yyerror("can't make alias for the number variables");
yyVal = null; /*XXX 0*/
}
break;
case 14:
// line 290 "DefaultRubyParser.y"
{
yyVal = ((Node)yyVals[0+yyTop]);
}
break;
case 15:
// line 293 "DefaultRubyParser.y"
{
yyVal = new IfNode(getPosition(), support.getConditionNode(((Node)yyVals[0+yyTop])), ((Node)yyVals[-2+yyTop]), null);
}
break;
case 16:
// line 296 "DefaultRubyParser.y"
{
yyVal = new IfNode(getPosition(), support.getConditionNode(((Node)yyVals[0+yyTop])), null, ((Node)yyVals[-2+yyTop]));
}
break;
case 17:
// line 299 "DefaultRubyParser.y"
{
if (((Node)yyVals[-2+yyTop]) != null && ((Node)yyVals[-2+yyTop]) instanceof BeginNode) {
yyVal = new WhileNode(getPosition(), support.getConditionNode(((Node)yyVals[0+yyTop])), ((BeginNode)yyVals[-2+yyTop]).getBodyNode(), false);
} else {
yyVal = new WhileNode(getPosition(), support.getConditionNode(((Node)yyVals[0+yyTop])), ((Node)yyVals[-2+yyTop]), false);
}
}
break;
case 18:
// line 306 "DefaultRubyParser.y"
{
if (((Node)yyVals[-2+yyTop]) != null && ((Node)yyVals[-2+yyTop]) instanceof BeginNode) {
yyVal = new UntilNode(getPosition(), support.getConditionNode(((Node)yyVals[0+yyTop])), ((BeginNode)yyVals[-2+yyTop]).getBodyNode());
} else {
yyVal = new UntilNode(getPosition(), support.getConditionNode(((Node)yyVals[0+yyTop])), ((Node)yyVals[-2+yyTop]));
}
}
break;
case 19:
// line 314 "DefaultRubyParser.y"
{
yyVal = new RescueNode(getPosition(), ((Node)yyVals[-2+yyTop]), new RescueBodyNode(getPosition(), null,((Node)yyVals[0+yyTop]), null), null);
}
break;
case 20:
// line 318 "DefaultRubyParser.y"
{
if (support.isInDef() || support.isInSingle()) {
yyerror("BEGIN in method");
}
support.getLocalNames().push();
}
break;
case 21:
// line 323 "DefaultRubyParser.y"
{
support.getResult().setBeginNodes(support.appendToBlock(support.getResult().getBeginNodes(), new ScopeNode(support.getLocalNames().getNames(), ((Node)yyVals[-1+yyTop]))));
support.getLocalNames().pop();
yyVal = null; /*XXX 0;*/
}
break;
case 22:
// line 328 "DefaultRubyParser.y"
{
if (support.isInDef() || support.isInSingle()) {
yyerror("END in method; use at_exit");
}
yyVal = new IterNode(getPosition(), null, new PostExeNode(getPosition()), ((Node)yyVals[-1+yyTop]));
}
break;
case 23:
// line 334 "DefaultRubyParser.y"
{
support.checkExpression(((Node)yyVals[0+yyTop]));
yyVal = support.node_assign(((Node)yyVals[-2+yyTop]), ((Node)yyVals[0+yyTop]));
}
break;
case 24:
// line 338 "DefaultRubyParser.y"
{
support.checkExpression(((Node)yyVals[0+yyTop]));
if (((MultipleAsgnNode)yyVals[-2+yyTop]).getHeadNode() != null) {
((MultipleAsgnNode)yyVals[-2+yyTop]).setValueNode(new ToAryNode(getPosition(), ((Node)yyVals[0+yyTop])));
} else {
((MultipleAsgnNode)yyVals[-2+yyTop]).setValueNode(new ArrayNode(getPosition()).add(((Node)yyVals[0+yyTop])));
}
yyVal = ((MultipleAsgnNode)yyVals[-2+yyTop]);
}
break;
case 25:
// line 347 "DefaultRubyParser.y"
{
support.checkExpression(((Node)yyVals[0+yyTop]));
if (yyVals[-2+yyTop] != null) {
String name = ((INameNode)yyVals[-2+yyTop]).getName();
if (((String)yyVals[-1+yyTop]).equals("||")) {
((AssignableNode)yyVals[-2+yyTop]).setValueNode(((Node)yyVals[0+yyTop]));
yyVal = new OpAsgnOrNode(getPosition(), support.gettable(name, getPosition()), ((Node)yyVals[-2+yyTop]));
/* XXX
if (is_asgn_or_id(vid)) {
$$->nd_aid = vid;
}
*/
} else if (((String)yyVals[-1+yyTop]).equals("&&")) {
((AssignableNode)yyVals[-2+yyTop]).setValueNode(((Node)yyVals[0+yyTop]));
yyVal = new OpAsgnAndNode(getPosition(), support.gettable(name, getPosition()), ((Node)yyVals[-2+yyTop]));
} else {
yyVal = yyVals[-2+yyTop];
if (yyVal != null) {
((AssignableNode)yyVal).setValueNode(support.getOperatorCallNode(support.gettable(name, getPosition()), ((String)yyVals[-1+yyTop]), ((Node)yyVals[0+yyTop])));
}
}
} else {
yyVal = null;
}
}
break;
case 26:
// line 372 "DefaultRubyParser.y"
{
/* Much smaller than ruby block */
yyVal = new OpElementAsgnNode(getPosition(), ((Node)yyVals[-5+yyTop]), ((String)yyVals[-1+yyTop]), ((Node)yyVals[-3+yyTop]), ((Node)yyVals[0+yyTop]));
}
break;
case 27:
// line 377 "DefaultRubyParser.y"
{
yyVal = new OpAsgnNode(getPosition(), ((Node)yyVals[-4+yyTop]), ((Node)yyVals[0+yyTop]), ((String)yyVals[-2+yyTop]), ((String)yyVals[-1+yyTop]));
}
break;
case 28:
// line 380 "DefaultRubyParser.y"
{
yyVal = new OpAsgnNode(getPosition(), ((Node)yyVals[-4+yyTop]), ((Node)yyVals[0+yyTop]), ((String)yyVals[-2+yyTop]), ((String)yyVals[-1+yyTop]));
}
break;
case 29:
// line 383 "DefaultRubyParser.y"
{
yyVal = new OpAsgnNode(getPosition(), ((Node)yyVals[-4+yyTop]), ((Node)yyVals[0+yyTop]), ((String)yyVals[-2+yyTop]), ((String)yyVals[-1+yyTop]));
}
break;
case 30:
// line 386 "DefaultRubyParser.y"
{
support.backrefAssignError(((Node)yyVals[-2+yyTop]));
yyVal = null;
}
break;
case 31:
// line 390 "DefaultRubyParser.y"
{
yyVal = support.node_assign(((Node)yyVals[-2+yyTop]), new SValueNode(getPosition(), ((Node)yyVals[0+yyTop])));
}
break;
case 32:
// line 393 "DefaultRubyParser.y"
{
if (((MultipleAsgnNode)yyVals[-2+yyTop]).getHeadNode() != null) {
((MultipleAsgnNode)yyVals[-2+yyTop]).setValueNode(new ToAryNode(getPosition(), ((Node)yyVals[0+yyTop])));
} else {
((MultipleAsgnNode)yyVals[-2+yyTop]).setValueNode(new ArrayNode(getPosition()).add(((Node)yyVals[0+yyTop])));
}
yyVal = ((MultipleAsgnNode)yyVals[-2+yyTop]);
}
break;
case 33:
// line 401 "DefaultRubyParser.y"
{
((AssignableNode)yyVals[-2+yyTop]).setValueNode(((Node)yyVals[0+yyTop]));
yyVal = ((MultipleAsgnNode)yyVals[-2+yyTop]);
}
break;
case 36:
// line 408 "DefaultRubyParser.y"
{
yyVal = support.newAndNode(((Node)yyVals[-2+yyTop]), ((Node)yyVals[0+yyTop]));
}
break;
case 37:
// line 411 "DefaultRubyParser.y"
{
yyVal = support.newOrNode(((Node)yyVals[-2+yyTop]), ((Node)yyVals[0+yyTop]));
}
break;
case 38:
// line 414 "DefaultRubyParser.y"
{
yyVal = new NotNode(getPosition(), support.getConditionNode(((Node)yyVals[0+yyTop])));
}
break;
case 39:
// line 417 "DefaultRubyParser.y"
{
yyVal = new NotNode(getPosition(), support.getConditionNode(((Node)yyVals[0+yyTop])));
}
break;
case 41:
// line 422 "DefaultRubyParser.y"
{
support.checkExpression(((Node)yyVals[0+yyTop]));
yyVal = ((Node)yyVals[0+yyTop]); /*Do we really need this set? $1 is $$?*/
}
break;
case 44:
// line 429 "DefaultRubyParser.y"
{
yyVal = new ReturnNode(getPosition(), support.ret_args(((Node)yyVals[0+yyTop]), getPosition()));
}
break;
case 45:
// line 432 "DefaultRubyParser.y"
{
yyVal = new BreakNode(getPosition(), support.ret_args(((Node)yyVals[0+yyTop]), getPosition()));
}
break;
case 46:
// line 435 "DefaultRubyParser.y"
{
yyVal = new NextNode(getPosition(), support.ret_args(((Node)yyVals[0+yyTop]), getPosition()));
}
break;
case 48:
// line 440 "DefaultRubyParser.y"
{
yyVal = support.new_call(((Node)yyVals[-3+yyTop]), ((String)yyVals[-1+yyTop]), ((Node)yyVals[0+yyTop]));
}
break;
case 49:
// line 443 "DefaultRubyParser.y"
{
yyVal = support.new_call(((Node)yyVals[-3+yyTop]), ((String)yyVals[-1+yyTop]), ((Node)yyVals[0+yyTop]));
}
break;
case 50:
// line 447 "DefaultRubyParser.y"
{
support.getBlockNames().push();
}
break;
case 51:
// line 449 "DefaultRubyParser.y"
{
yyVal = new IterNode(getPosition(), ((Node)yyVals[-2+yyTop]), ((Node)yyVals[-1+yyTop]), null);
support.getBlockNames().pop();
}
break;
case 52:
// line 454 "DefaultRubyParser.y"
{
yyVal = support.new_fcall(((String)yyVals[-1+yyTop]), ((Node)yyVals[0+yyTop]), getPosition()); /* .setPosFrom($2);*/
}
break;
case 53:
// line 457 "DefaultRubyParser.y"
{
yyVal = support.new_fcall(((String)yyVals[-2+yyTop]), ((Node)yyVals[-1+yyTop]), getPosition());
if (((IterNode)yyVals[0+yyTop]) != null) {
if (yyVal instanceof BlockPassNode) {
errorHandler.handleError(IErrors.COMPILE_ERROR, null, "Both block arg and actual block given.");
}
((IterNode)yyVals[0+yyTop]).setIterNode(((Node)yyVal));
yyVal = ((Node)yyVals[-1+yyTop]);
}
}
break;
case 54:
// line 467 "DefaultRubyParser.y"
{
yyVal = support.new_call(((Node)yyVals[-3+yyTop]), ((String)yyVals[-1+yyTop]), ((Node)yyVals[0+yyTop])); /*.setPosFrom($1);*/
}
break;
case 55:
// line 470 "DefaultRubyParser.y"
{
yyVal = support.new_call(((Node)yyVals[-4+yyTop]), ((String)yyVals[-2+yyTop]), ((Node)yyVals[-1+yyTop]));
if (((IterNode)yyVals[0+yyTop]) != null) {
if (yyVal instanceof BlockPassNode) {
errorHandler.handleError(IErrors.COMPILE_ERROR, null, "Both block arg and actual block given.");
}
((IterNode)yyVals[0+yyTop]).setIterNode(((Node)yyVal));
yyVal = ((IterNode)yyVals[0+yyTop]);
}
}
break;
case 56:
// line 480 "DefaultRubyParser.y"
{
yyVal = support.new_call(((Node)yyVals[-3+yyTop]), ((String)yyVals[-1+yyTop]), ((Node)yyVals[0+yyTop]));
}
break;
case 57:
// line 483 "DefaultRubyParser.y"
{
yyVal = support.new_call(((Node)yyVals[-4+yyTop]), ((String)yyVals[-2+yyTop]), ((Node)yyVals[-1+yyTop]));
if (((IterNode)yyVals[0+yyTop]) != null) {
if (yyVal instanceof BlockPassNode) {
errorHandler.handleError(IErrors.COMPILE_ERROR, null, "Both block arg and actual block given.");
}
((IterNode)yyVals[0+yyTop]).setIterNode(((Node)yyVal));
yyVal = ((IterNode)yyVals[0+yyTop]);
}
}
break;
case 58:
// line 493 "DefaultRubyParser.y"
{
yyVal = support.new_super(((Node)yyVals[0+yyTop]), getPosition()); /* .setPosFrom($2);*/
}
break;
case 59:
// line 496 "DefaultRubyParser.y"
{
yyVal = support.new_yield(getPosition(), ((Node)yyVals[0+yyTop]));
}
break;
case 61:
// line 501 "DefaultRubyParser.y"
{
yyVal = ((MultipleAsgnNode)yyVals[-1+yyTop]);
}
break;
case 63:
// line 506 "DefaultRubyParser.y"
{
yyVal = new MultipleAsgnNode(getPosition(), new ArrayNode(getPosition()).add(((MultipleAsgnNode)yyVals[-1+yyTop])), null);
}
break;
case 64:
// line 510 "DefaultRubyParser.y"
{
yyVal = new MultipleAsgnNode(getPosition(), ((ListNode)yyVals[0+yyTop]), null);
}
break;
case 65:
// line 513 "DefaultRubyParser.y"
{
yyVal = new MultipleAsgnNode(getPosition(), ((ListNode)yyVals[-1+yyTop]).add(((Node)yyVals[0+yyTop])), null);
}
break;
case 66:
// line 516 "DefaultRubyParser.y"
{
yyVal = new MultipleAsgnNode(getPosition(), ((ListNode)yyVals[-2+yyTop]), ((Node)yyVals[0+yyTop]));
}
break;
case 67:
// line 519 "DefaultRubyParser.y"
{
yyVal = new MultipleAsgnNode(getPosition(), ((ListNode)yyVals[-1+yyTop]), new StarNode());
}
break;
case 68:
// line 522 "DefaultRubyParser.y"
{
yyVal = new MultipleAsgnNode(getPosition(), null, ((Node)yyVals[0+yyTop]));
}
break;
case 69:
// line 525 "DefaultRubyParser.y"
{
yyVal = new MultipleAsgnNode(getPosition(), null, new StarNode());
}
break;
case 71:
// line 530 "DefaultRubyParser.y"
{
yyVal = ((MultipleAsgnNode)yyVals[-1+yyTop]);
}
break;
case 72:
// line 534 "DefaultRubyParser.y"
{
yyVal = new ArrayNode(getPosition()).add(((Node)yyVals[-1+yyTop]));
}
break;
case 73:
// line 537 "DefaultRubyParser.y"
{
yyVal = ((ListNode)yyVals[-2+yyTop]).add(((Node)yyVals[-1+yyTop]));
}
break;
case 74:
// line 541 "DefaultRubyParser.y"
{
yyVal = support.assignable(getPosition(), yyVals[0+yyTop], null);
}
break;
case 75:
// line 544 "DefaultRubyParser.y"
{
yyVal = support.getElementAssignmentNode(((Node)yyVals[-3+yyTop]), ((Node)yyVals[-1+yyTop]));
}
break;
case 76:
// line 547 "DefaultRubyParser.y"
{
yyVal = support.getAttributeAssignmentNode(((Node)yyVals[-2+yyTop]), ((String)yyVals[0+yyTop]));
}
break;
case 77:
// line 550 "DefaultRubyParser.y"
{
yyVal = support.getAttributeAssignmentNode(((Node)yyVals[-2+yyTop]), ((String)yyVals[0+yyTop]));
}
break;
case 78:
// line 553 "DefaultRubyParser.y"
{
yyVal = support.getAttributeAssignmentNode(((Node)yyVals[-2+yyTop]), ((String)yyVals[0+yyTop]));
}
break;
case 79:
// line 556 "DefaultRubyParser.y"
{
if (support.isInDef() || support.isInSingle()) {
yyerror("dynamic constant assignment");
}
yyVal = support.getAttributeAssignmentNode(((Node)yyVals[-2+yyTop]), ((String)yyVals[0+yyTop]));
}
break;
case 80:
// line 563 "DefaultRubyParser.y"
{
if (support.isInDef() || support.isInSingle()) {
yyerror("dynamic constant assignment");
}
/* ERROR: VEry likely a big error. */
yyVal = new Colon3Node(getPosition(), ((String)yyVals[0+yyTop]));
/* ruby $$ = NEW_CDECL(0, 0, NEW_COLON3($2)); */
}
break;
case 81:
// line 573 "DefaultRubyParser.y"
{
support.backrefAssignError(((Node)yyVals[0+yyTop]));
yyVal = null;
}
break;
case 82:
// line 578 "DefaultRubyParser.y"
{
yyVal = support.assignable(getPosition(), yyVals[0+yyTop], null);
}
break;
case 83:
// line 581 "DefaultRubyParser.y"
{
yyVal = support.getElementAssignmentNode(((Node)yyVals[-3+yyTop]), ((Node)yyVals[-1+yyTop]));
}
break;
case 84:
// line 584 "DefaultRubyParser.y"
{
yyVal = support.getAttributeAssignmentNode(((Node)yyVals[-2+yyTop]), ((String)yyVals[0+yyTop]));
}
break;
case 85:
// line 587 "DefaultRubyParser.y"
{
yyVal = support.getAttributeAssignmentNode(((Node)yyVals[-2+yyTop]), ((String)yyVals[0+yyTop]));
}
break;
case 86:
// line 590 "DefaultRubyParser.y"
{
yyVal = support.getAttributeAssignmentNode(((Node)yyVals[-2+yyTop]), ((String)yyVals[0+yyTop]));
}
break;
case 87:
// line 593 "DefaultRubyParser.y"
{
if (support.isInDef() || support.isInSingle()) {
yyerror("dynamic constant assignment");
}
yyVal = support.getAttributeAssignmentNode(((Node)yyVals[-2+yyTop]), ((String)yyVals[0+yyTop]));
}
break;
case 88:
// line 600 "DefaultRubyParser.y"
{
if (support.isInDef() || support.isInSingle()) {
yyerror("dynamic constant assignment");
}
/* ERROR: VEry likely a big error. */
yyVal = new Colon3Node(getPosition(), ((String)yyVals[0+yyTop]));
/* ruby $$ = NEW_CDECL(0, 0, NEW_COLON3($2)); */
}
break;
case 89:
// line 609 "DefaultRubyParser.y"
{
support.backrefAssignError(((Node)yyVals[0+yyTop]));
yyVal = null;
}
break;
case 90:
// line 614 "DefaultRubyParser.y"
{
yyerror("class/module name must be CONSTANT");
}
break;
case 92:
// line 619 "DefaultRubyParser.y"
{
yyVal = new Colon2Node(getPosition(), null, ((String)yyVals[0+yyTop]));
}
break;
case 93:
// line 622 "DefaultRubyParser.y"
{
/* $1 was $$ in ruby?*/
yyVal = new Colon2Node(getPosition(), null, ((String)yyVals[0+yyTop]));
}
break;
case 94:
// line 626 "DefaultRubyParser.y"
{
yyVal = new Colon2Node(getPosition(), ((Node)yyVals[-2+yyTop]), ((String)yyVals[0+yyTop]));
}
break;
case 98:
// line 633 "DefaultRubyParser.y"
{
lexer.setState(LexState.EXPR_END);
yyVal = ((String)yyVals[0+yyTop]);
}
break;
case 99:
// line 637 "DefaultRubyParser.y"
{
lexer.setState(LexState.EXPR_END);
yyVal = yyVals[0+yyTop];
}
break;
case 102:
// line 645 "DefaultRubyParser.y"
{
yyVal = new UndefNode(getPosition(), ((String)yyVals[0+yyTop]));
}
break;
case 103:
// line 648 "DefaultRubyParser.y"
{
lexer.setState(LexState.EXPR_FNAME);
}
break;
case 104:
// line 650 "DefaultRubyParser.y"
{
yyVal = support.appendToBlock(((Node)yyVals[-3+yyTop]), new UndefNode(getPosition(), ((String)yyVals[0+yyTop])));
}
break;
case 105:
// line 654 "DefaultRubyParser.y"
{ yyVal = "|"; }
break;
case 106:
// line 655 "DefaultRubyParser.y"
{ yyVal = "^"; }
break;
case 107:
// line 656 "DefaultRubyParser.y"
{ yyVal = "&"; }
break;
case 108:
// line 657 "DefaultRubyParser.y"
{ yyVal = "<=>"; }
break;
case 109:
// line 658 "DefaultRubyParser.y"
{ yyVal = "=="; }
break;
case 110:
// line 659 "DefaultRubyParser.y"
{ yyVal = "==="; }
break;
case 111:
// line 660 "DefaultRubyParser.y"
{ yyVal = "=~"; }
break;
case 112:
// line 661 "DefaultRubyParser.y"
{ yyVal = ">"; }
break;
case 113:
// line 662 "DefaultRubyParser.y"
{ yyVal = ">="; }
break;
case 114:
// line 663 "DefaultRubyParser.y"
{ yyVal = "<"; }
break;
case 115:
// line 664 "DefaultRubyParser.y"
{ yyVal = "<="; }
break;
case 116:
// line 665 "DefaultRubyParser.y"
{ yyVal = "<<"; }
break;
case 117:
// line 666 "DefaultRubyParser.y"
{ yyVal = ">>"; }
break;
case 118:
// line 667 "DefaultRubyParser.y"
{ yyVal = "+"; }
break;
case 119:
// line 668 "DefaultRubyParser.y"
{ yyVal = "-"; }
break;
case 120:
// line 669 "DefaultRubyParser.y"
{ yyVal = "*"; }
break;
case 121:
// line 670 "DefaultRubyParser.y"
{ yyVal = "*"; }
break;
case 122:
// line 671 "DefaultRubyParser.y"
{ yyVal = "/"; }
break;
case 123:
// line 672 "DefaultRubyParser.y"
{ yyVal = "%"; }
break;
case 124:
// line 673 "DefaultRubyParser.y"
{ yyVal = "**"; }
break;
case 125:
// line 674 "DefaultRubyParser.y"
{ yyVal = "~"; }
break;
case 126:
// line 675 "DefaultRubyParser.y"
{ yyVal = "+@"; }
break;
case 127:
// line 676 "DefaultRubyParser.y"
{ yyVal = "-@"; }
break;
case 128:
// line 677 "DefaultRubyParser.y"
{ yyVal = "[]"; }
break;
case 129:
// line 678 "DefaultRubyParser.y"
{ yyVal = "[]="; }
break;
case 130:
// line 679 "DefaultRubyParser.y"
{ yyVal = "`"; }
break;
case 172:
// line 690 "DefaultRubyParser.y"
{
yyVal = support.node_assign(((Node)yyVals[-2+yyTop]), ((Node)yyVals[0+yyTop]));
}
break;
case 173:
// line 693 "DefaultRubyParser.y"
{
yyVal = support.node_assign(((Node)yyVals[-4+yyTop]), new RescueNode(getPosition(), ((Node)yyVals[-2+yyTop]), new RescueBodyNode(getPosition(), null,((Node)yyVals[0+yyTop]), null), null));
}
break;
case 174:
// line 696 "DefaultRubyParser.y"
{
support.checkExpression(((Node)yyVals[0+yyTop]));
if (yyVals[-2+yyTop] != null) {
String name = ((INameNode)yyVals[-2+yyTop]).getName();
if (((String)yyVals[-1+yyTop]).equals("||")) {
((AssignableNode)yyVals[-2+yyTop]).setValueNode(((Node)yyVals[0+yyTop]));
yyVal = new OpAsgnOrNode(getPosition(), support.gettable(name, getPosition()), ((Node)yyVals[-2+yyTop]));
/* FIXME
if (is_asgn_or_id(vid)) {
$$->nd_aid = vid;
}
*/
} else if (((String)yyVals[-1+yyTop]).equals("&&")) {
((AssignableNode)yyVals[-2+yyTop]).setValueNode(((Node)yyVals[0+yyTop]));
yyVal = new OpAsgnAndNode(getPosition(), support.gettable(name, getPosition()), ((Node)yyVals[-2+yyTop]));
} else {
yyVal = yyVals[-2+yyTop];
if (yyVal != null) {
((AssignableNode)yyVal).setValueNode(support.getOperatorCallNode(support.gettable(name, getPosition()), ((String)yyVals[-1+yyTop]), ((Node)yyVals[0+yyTop])));
}
}
} else {
yyVal = null; /* XXX 0; */
}
}
break;
case 175:
// line 722 "DefaultRubyParser.y"
{
yyVal = new OpElementAsgnNode(getPosition(), ((Node)yyVals[-5+yyTop]), ((String)yyVals[-1+yyTop]), ((Node)yyVals[-3+yyTop]), ((Node)yyVals[0+yyTop]));
}
break;
case 176:
// line 725 "DefaultRubyParser.y"
{
yyVal = new OpAsgnNode(getPosition(), ((Node)yyVals[-4+yyTop]), ((Node)yyVals[0+yyTop]), ((String)yyVals[-2+yyTop]), ((String)yyVals[-1+yyTop]));
}
break;
case 177:
// line 728 "DefaultRubyParser.y"
{
yyVal = new OpAsgnNode(getPosition(), ((Node)yyVals[-4+yyTop]), ((Node)yyVals[0+yyTop]), ((String)yyVals[-2+yyTop]), ((String)yyVals[-1+yyTop]));
}
break;
case 178:
// line 731 "DefaultRubyParser.y"
{
yyVal = new OpAsgnNode(getPosition(), ((Node)yyVals[-4+yyTop]), ((Node)yyVals[0+yyTop]), ((String)yyVals[-2+yyTop]), ((String)yyVals[-1+yyTop]));
}
break;
case 179:
// line 734 "DefaultRubyParser.y"
{
yyerror("constant re-assignment");
yyVal = null;
}
break;
case 180:
// line 738 "DefaultRubyParser.y"
{
yyerror("constant re-assignment");
yyVal = null;
}
break;
case 181:
// line 742 "DefaultRubyParser.y"
{
support.backrefAssignError(((Node)yyVals[-2+yyTop]));
yyVal = null;
}
break;
case 182:
// line 746 "DefaultRubyParser.y"
{
support.checkExpression(((Node)yyVals[-2+yyTop]));
support.checkExpression(((Node)yyVals[0+yyTop]));
yyVal = new DotNode(getPosition(), ((Node)yyVals[-2+yyTop]), ((Node)yyVals[0+yyTop]), false);
}
break;
case 183:
// line 751 "DefaultRubyParser.y"
{
support.checkExpression(((Node)yyVals[-2+yyTop]));
support.checkExpression(((Node)yyVals[0+yyTop]));
yyVal = new DotNode(getPosition(), ((Node)yyVals[-2+yyTop]), ((Node)yyVals[0+yyTop]), true);
}
break;
case 184:
// line 756 "DefaultRubyParser.y"
{
yyVal = support.getOperatorCallNode(((Node)yyVals[-2+yyTop]), "+", ((Node)yyVals[0+yyTop]));
}
break;
case 185:
// line 759 "DefaultRubyParser.y"
{
yyVal = support.getOperatorCallNode(((Node)yyVals[-2+yyTop]), "-", ((Node)yyVals[0+yyTop]));
}
break;
case 186:
// line 762 "DefaultRubyParser.y"
{
yyVal = support.getOperatorCallNode(((Node)yyVals[-2+yyTop]), "*", ((Node)yyVals[0+yyTop]));
}
break;
case 187:
// line 765 "DefaultRubyParser.y"
{
yyVal = support.getOperatorCallNode(((Node)yyVals[-2+yyTop]), "/", ((Node)yyVals[0+yyTop]));
}
break;
case 188:
// line 768 "DefaultRubyParser.y"
{
yyVal = support.getOperatorCallNode(((Node)yyVals[-2+yyTop]), "%", ((Node)yyVals[0+yyTop]));
}
break;
case 189:
// line 771 "DefaultRubyParser.y"
{
yyVal = support.getOperatorCallNode(((Node)yyVals[-2+yyTop]), "**", ((Node)yyVals[0+yyTop]));
/* Covert '- number ** number' to '- (number ** number)'
boolean needNegate = false;
if (($1 instanceof FixnumNode && $<FixnumNode>1.getValue() < 0) ||
($1 instanceof BignumNode && $<BignumNode>1.getValue().compareTo(BigInteger.ZERO) < 0) ||
($1 instanceof FloatNode && $<FloatNode>1.getValue() < 0.0)) {
$<>1 = support.getOperatorCallNode($1, "-@");
needNegate = true;
}
$$ = support.getOperatorCallNode($1, "**", $3);
if (needNegate) {
$$ = support.getOperatorCallNode($<Node>$, "-@");
}
*/
}
break;
case 190:
// line 790 "DefaultRubyParser.y"
{
yyVal = support.getOperatorCallNode(support.getOperatorCallNode((((Number)yyVals[-2+yyTop]) instanceof Long ? (Node) new FixnumNode(getPosition(), ((Long)yyVals[-2+yyTop]).longValue()) : (Node)new BignumNode(getPosition(), ((BigInteger)yyVals[-2+yyTop]))), "**", ((Node)yyVals[0+yyTop])), "-@");
}
break;
case 191:
// line 793 "DefaultRubyParser.y"
{
yyVal = support.getOperatorCallNode(support.getOperatorCallNode(new FloatNode(getPosition(), ((Double)yyVals[-3+yyTop]).doubleValue()), "**", ((Node)yyVals[0+yyTop])), "-@");
}
break;
case 192:
// line 796 "DefaultRubyParser.y"
{
if (((Node)yyVals[0+yyTop]) != null && ((Node)yyVals[0+yyTop]) instanceof ILiteralNode) {
yyVal = ((Node)yyVals[0+yyTop]);
} else {
yyVal = support.getOperatorCallNode(((Node)yyVals[0+yyTop]), "+@");
}
}
break;
case 193:
// line 803 "DefaultRubyParser.y"
{
yyVal = support.getOperatorCallNode(((Node)yyVals[0+yyTop]), "-@");
}
break;
case 194:
// line 806 "DefaultRubyParser.y"
{
yyVal = support.getOperatorCallNode(((Node)yyVals[-2+yyTop]), "|", ((Node)yyVals[0+yyTop]));
}
break;
case 195:
// line 809 "DefaultRubyParser.y"
{
yyVal = support.getOperatorCallNode(((Node)yyVals[-2+yyTop]), "^", ((Node)yyVals[0+yyTop]));
}
break;
case 196:
// line 812 "DefaultRubyParser.y"
{
yyVal = support.getOperatorCallNode(((Node)yyVals[-2+yyTop]), "&", ((Node)yyVals[0+yyTop]));
}
break;
case 197:
// line 815 "DefaultRubyParser.y"
{
yyVal = support.getOperatorCallNode(((Node)yyVals[-2+yyTop]), "<=>", ((Node)yyVals[0+yyTop]));
}
break;
case 198:
// line 818 "DefaultRubyParser.y"
{
yyVal = support.getOperatorCallNode(((Node)yyVals[-2+yyTop]), ">", ((Node)yyVals[0+yyTop]));
}
break;
case 199:
// line 821 "DefaultRubyParser.y"
{
yyVal = support.getOperatorCallNode(((Node)yyVals[-2+yyTop]), ">=", ((Node)yyVals[0+yyTop]));
}
break;
case 200:
// line 824 "DefaultRubyParser.y"
{
yyVal = support.getOperatorCallNode(((Node)yyVals[-2+yyTop]), "<", ((Node)yyVals[0+yyTop]));
}
break;
case 201:
// line 827 "DefaultRubyParser.y"
{
yyVal = support.getOperatorCallNode(((Node)yyVals[-2+yyTop]), "<=", ((Node)yyVals[0+yyTop]));
}
break;
case 202:
// line 830 "DefaultRubyParser.y"
{
yyVal = support.getOperatorCallNode(((Node)yyVals[-2+yyTop]), "==", ((Node)yyVals[0+yyTop]));
}
break;
case 203:
// line 833 "DefaultRubyParser.y"
{
yyVal = support.getOperatorCallNode(((Node)yyVals[-2+yyTop]), "===", ((Node)yyVals[0+yyTop]));
}
break;
case 204:
// line 836 "DefaultRubyParser.y"
{
yyVal = new NotNode(getPosition(), support.getOperatorCallNode(((Node)yyVals[-2+yyTop]), "==", ((Node)yyVals[0+yyTop])));
}
break;
case 205:
// line 839 "DefaultRubyParser.y"
{
yyVal = support.getMatchNode(((Node)yyVals[-2+yyTop]), ((Node)yyVals[0+yyTop]));
}
break;
case 206:
// line 842 "DefaultRubyParser.y"
{
yyVal = new NotNode(getPosition(), support.getMatchNode(((Node)yyVals[-2+yyTop]), ((Node)yyVals[0+yyTop])));
}
break;
case 207:
// line 845 "DefaultRubyParser.y"
{
yyVal = new NotNode(getPosition(), support.getConditionNode(((Node)yyVals[0+yyTop])));
}
break;
case 208:
// line 848 "DefaultRubyParser.y"
{
yyVal = support.getOperatorCallNode(((Node)yyVals[0+yyTop]), "~");
}
break;
case 209:
// line 851 "DefaultRubyParser.y"
{
yyVal = support.getOperatorCallNode(((Node)yyVals[-2+yyTop]), "<<", ((Node)yyVals[0+yyTop]));
}
break;
case 210:
// line 854 "DefaultRubyParser.y"
{
yyVal = support.getOperatorCallNode(((Node)yyVals[-2+yyTop]), ">>", ((Node)yyVals[0+yyTop]));
}
break;
case 211:
// line 857 "DefaultRubyParser.y"
{
yyVal = support.newAndNode(((Node)yyVals[-2+yyTop]), ((Node)yyVals[0+yyTop]));
}
break;
case 212:
// line 860 "DefaultRubyParser.y"
{
yyVal = support.newOrNode(((Node)yyVals[-2+yyTop]), ((Node)yyVals[0+yyTop]));
}
break;
case 213:
// line 863 "DefaultRubyParser.y"
{
support.setInDefined(true);
}
break;
case 214:
// line 865 "DefaultRubyParser.y"
{
support.setInDefined(false);
yyVal = new DefinedNode(getPosition(), ((Node)yyVals[0+yyTop]));
}
break;
case 215:
// line 869 "DefaultRubyParser.y"
{
yyVal = new IfNode(getPosition(), support.getConditionNode(((Node)yyVals[-4+yyTop])), ((Node)yyVals[-2+yyTop]), ((Node)yyVals[0+yyTop]));
}
break;
case 216:
// line 872 "DefaultRubyParser.y"
{
yyVal = ((Node)yyVals[0+yyTop]);
}
break;
case 217:
// line 876 "DefaultRubyParser.y"
{
support.checkExpression(((Node)yyVals[0+yyTop]));
yyVal = ((Node)yyVals[0+yyTop]);
}
break;
case 219:
// line 882 "DefaultRubyParser.y"
{
errorHandler.handleError(IErrors.WARN, null, "parenthesize argument(s) for future version");
yyVal = new ArrayNode(getPosition()).add(((Node)yyVals[-1+yyTop]));
}
break;
case 220:
// line 886 "DefaultRubyParser.y"
{
yyVal = ((ListNode)yyVals[-1+yyTop]);
}
break;
case 221:
// line 889 "DefaultRubyParser.y"
{
support.checkExpression(((Node)yyVals[-1+yyTop]));
yyVal = support.arg_concat(getPosition(), ((ListNode)yyVals[-4+yyTop]), ((Node)yyVals[-1+yyTop]));
}
break;
case 222:
// line 893 "DefaultRubyParser.y"
{
yyVal = new ArrayNode(getPosition()).add(new HashNode(((ListNode)yyVals[-1+yyTop])));
}
break;
case 223:
// line 896 "DefaultRubyParser.y"
{
support.checkExpression(((Node)yyVals[-1+yyTop]));
yyVal = new NewlineNode(getPosition(), new SplatNode(getPosition(), ((Node)yyVals[-1+yyTop])));
}
break;
case 224:
// line 901 "DefaultRubyParser.y"
{
yyVal = ((ListNode)yyVals[-1+yyTop]);
}
break;
case 225:
// line 904 "DefaultRubyParser.y"
{
yyVal = ((Node)yyVals[-2+yyTop]);
}
break;
case 226:
// line 907 "DefaultRubyParser.y"
{
errorHandler.handleError(IErrors.WARN, null, "parenthesize argument(s) for future version");
yyVal = new ArrayNode(getPosition()).add(((Node)yyVals[-2+yyTop]));
}
break;
case 227:
// line 911 "DefaultRubyParser.y"
{
errorHandler.handleError(IErrors.WARN, null, "parenthesize argument(s) for future version");
yyVal = ((ListNode)yyVals[-4+yyTop]).add(((Node)yyVals[-2+yyTop]));
}
break;
case 230:
// line 919 "DefaultRubyParser.y"
{
errorHandler.handleError(IErrors.WARN, null, "parenthesize argument(s) for future version");
yyVal = new ArrayNode(getPosition()).add(((Node)yyVals[0+yyTop]));
}
break;
case 231:
// line 923 "DefaultRubyParser.y"
{
yyVal = support.arg_blk_pass(((ListNode)yyVals[-1+yyTop]), ((BlockPassNode)yyVals[0+yyTop]));
}
break;
case 232:
// line 926 "DefaultRubyParser.y"
{
yyVal = support.arg_concat(getPosition(), ((ListNode)yyVals[-4+yyTop]), ((Node)yyVals[-1+yyTop]));
yyVal = support.arg_blk_pass((Node)yyVal, ((BlockPassNode)yyVals[0+yyTop]));
}
break;
case 233:
// line 930 "DefaultRubyParser.y"
{
yyVal = new ArrayNode(getPosition()).add(new HashNode(((ListNode)yyVals[-1+yyTop])));
yyVal = support.arg_blk_pass((Node)yyVal, ((BlockPassNode)yyVals[0+yyTop]));
}
break;
case 234:
// line 934 "DefaultRubyParser.y"
{
yyVal = support.arg_concat(getPosition(), new ArrayNode(getPosition()).add(new HashNode(((ListNode)yyVals[-4+yyTop]))), ((Node)yyVals[-1+yyTop]));
yyVal = support.arg_blk_pass((Node)yyVal, ((BlockPassNode)yyVals[0+yyTop]));
}
break;
case 235:
// line 938 "DefaultRubyParser.y"
{
yyVal = ((ListNode)yyVals[-3+yyTop]).add(new HashNode(((ListNode)yyVals[-1+yyTop])));
yyVal = support.arg_blk_pass((Node)yyVal, ((BlockPassNode)yyVals[0+yyTop]));
}
break;
case 236:
// line 942 "DefaultRubyParser.y"
{
support.checkExpression(((Node)yyVals[-1+yyTop]));
yyVal = support.arg_concat(getPosition(), ((ListNode)yyVals[-6+yyTop]).add(new HashNode(((ListNode)yyVals[-4+yyTop]))), ((Node)yyVals[-1+yyTop]));
yyVal = support.arg_blk_pass((Node)yyVal, ((BlockPassNode)yyVals[0+yyTop]));
}
break;
case 237:
// line 947 "DefaultRubyParser.y"
{
yyVal = support.arg_blk_pass(new SplatNode(getPosition(), ((Node)yyVals[-1+yyTop])), ((BlockPassNode)yyVals[0+yyTop]));
}
break;
case 238:
// line 950 "DefaultRubyParser.y"
{
}
break;
case 239:
// line 953 "DefaultRubyParser.y"
{
yyVal = support.arg_blk_pass(support.list_concat(new ArrayNode(getPosition()).add(((Node)yyVals[-3+yyTop])), ((ListNode)yyVals[-1+yyTop])), ((BlockPassNode)yyVals[0+yyTop]));
}
break;
case 240:
// line 956 "DefaultRubyParser.y"
{
yyVal = support.arg_blk_pass(new ArrayNode(getPosition()).add(((Node)yyVals[-2+yyTop])), ((BlockPassNode)yyVals[0+yyTop]));
}
break;
case 241:
// line 959 "DefaultRubyParser.y"
{
yyVal = support.arg_concat(getPosition(), new ArrayNode(getPosition()).add(((Node)yyVals[-4+yyTop])), ((Node)yyVals[-1+yyTop]));
yyVal = support.arg_blk_pass((Node)yyVal, ((BlockPassNode)yyVals[0+yyTop]));
}
break;
case 242:
// line 963 "DefaultRubyParser.y"
{
yyVal = support.arg_concat(getPosition(), support.list_concat(new ArrayNode(getPosition()).add(((Node)yyVals[-6+yyTop])), new HashNode(((ListNode)yyVals[-4+yyTop]))), ((Node)yyVals[-1+yyTop]));
yyVal = support.arg_blk_pass((Node)yyVal, ((BlockPassNode)yyVals[0+yyTop]));
}
break;
case 243:
// line 967 "DefaultRubyParser.y"
{
yyVal = new ArrayNode(getPosition()).add(new HashNode(((ListNode)yyVals[-1+yyTop])));
yyVal = support.arg_blk_pass((Node)yyVal, ((BlockPassNode)yyVals[0+yyTop]));
}
break;
case 244:
// line 971 "DefaultRubyParser.y"
{
yyVal = support.arg_concat(getPosition(), new ArrayNode(getPosition()).add(new HashNode(((ListNode)yyVals[-4+yyTop]))), ((Node)yyVals[-1+yyTop]));
yyVal = support.arg_blk_pass((Node)yyVal, ((BlockPassNode)yyVals[0+yyTop]));
}
break;
case 245:
// line 975 "DefaultRubyParser.y"
{
yyVal = new ArrayNode(getPosition()).add(((Node)yyVals[-3+yyTop])).add(new HashNode(((ListNode)yyVals[-1+yyTop])));
yyVal = support.arg_blk_pass((Node)yyVal, ((BlockPassNode)yyVals[0+yyTop]));
}
break;
case 246:
// line 979 "DefaultRubyParser.y"
{
yyVal = support.list_concat(new ArrayNode(getPosition()).add(((Node)yyVals[-5+yyTop])), ((ListNode)yyVals[-3+yyTop])).add(new HashNode(((ListNode)yyVals[-1+yyTop])));
yyVal = support.arg_blk_pass((Node)yyVal, ((BlockPassNode)yyVals[0+yyTop]));
}
break;
case 247:
// line 983 "DefaultRubyParser.y"
{
yyVal = support.arg_concat(getPosition(), new ArrayNode(getPosition()).add(((Node)yyVals[-6+yyTop])).add(new HashNode(((ListNode)yyVals[-4+yyTop]))), ((Node)yyVals[-1+yyTop]));
yyVal = support.arg_blk_pass((Node)yyVal, ((BlockPassNode)yyVals[0+yyTop]));
}
break;
case 248:
// line 987 "DefaultRubyParser.y"
{
yyVal = support.arg_concat(getPosition(), support.list_concat(new ArrayNode(getPosition()).add(((Node)yyVals[-8+yyTop])), ((ListNode)yyVals[-6+yyTop])).add(new HashNode(((ListNode)yyVals[-4+yyTop]))), ((Node)yyVals[-1+yyTop]));
yyVal = support.arg_blk_pass((Node)yyVal, ((BlockPassNode)yyVals[0+yyTop]));
}
break;
case 249:
// line 991 "DefaultRubyParser.y"
{
yyVal = support.arg_blk_pass(new SplatNode(getPosition(), ((Node)yyVals[-1+yyTop])), ((BlockPassNode)yyVals[0+yyTop]));
}
break;
case 250:
// line 994 "DefaultRubyParser.y"
{}
break;
case 251:
// line 996 "DefaultRubyParser.y"
{
yyVal = new Long(lexer.getCmdArgumentState().begin());
}
break;
case 252:
// line 998 "DefaultRubyParser.y"
{
lexer.getCmdArgumentState().reset(((Long)yyVals[-1+yyTop]).longValue());
yyVal = ((Node)yyVals[0+yyTop]);
}
break;
case 254:
// line 1004 "DefaultRubyParser.y"
{
lexer.setState(LexState.EXPR_ENDARG);
}
break;
case 255:
// line 1006 "DefaultRubyParser.y"
{
errorHandler.handleError(IErrors.WARN, null, "don't put space before argument parentheses");
yyVal = null;
}
break;
case 256:
// line 1010 "DefaultRubyParser.y"
{
lexer.setState(LexState.EXPR_ENDARG);
}
break;
case 257:
// line 1012 "DefaultRubyParser.y"
{
errorHandler.handleError(IErrors.WARN, null, "don't put space before argument parentheses");
yyVal = ((Node)yyVals[-2+yyTop]);
}
break;
case 258:
// line 1017 "DefaultRubyParser.y"
{
support.checkExpression(((Node)yyVals[0+yyTop]));
yyVal = new BlockPassNode(getPosition(), ((Node)yyVals[0+yyTop]));
}
break;
case 259:
// line 1022 "DefaultRubyParser.y"
{
yyVal = ((BlockPassNode)yyVals[0+yyTop]);
}
break;
case 261:
// line 1027 "DefaultRubyParser.y"
{
yyVal = new ArrayNode(getPosition()).add(((Node)yyVals[0+yyTop]));
}
break;
case 262:
// line 1030 "DefaultRubyParser.y"
{
yyVal = ((ListNode)yyVals[-2+yyTop]).add(((Node)yyVals[0+yyTop]));
}
break;
case 263:
// line 1034 "DefaultRubyParser.y"
{
yyVal = ((ListNode)yyVals[-2+yyTop]).add(((Node)yyVals[0+yyTop]));
}
break;
case 264:
// line 1037 "DefaultRubyParser.y"
{
yyVal = support.arg_concat(getPosition(), ((ListNode)yyVals[-3+yyTop]), ((Node)yyVals[0+yyTop]));
}
break;
case 265:
// line 1040 "DefaultRubyParser.y"
{
yyVal = new SplatNode(getPosition(), ((Node)yyVals[0+yyTop]));
}
break;
case 274:
// line 1052 "DefaultRubyParser.y"
{
yyVal = new VCallNode(getPosition(), ((String)yyVals[0+yyTop]));
}
break;
case 275:
// line 1056 "DefaultRubyParser.y"
{
yyVal = new BeginNode(getPosition(), ((Node)yyVals[-1+yyTop]));
}
break;
case 276:
// line 1059 "DefaultRubyParser.y"
{
lexer.setState(LexState.EXPR_ENDARG);
errorHandler.handleError(IErrors.WARN, null, "(...) interpreted as grouped expression");
yyVal = ((Node)yyVals[-2+yyTop]);
}
break;
case 277:
// line 1064 "DefaultRubyParser.y"
{
yyVal = ((Node)yyVals[-1+yyTop]);
}
break;
case 278:
// line 1067 "DefaultRubyParser.y"
{
yyVal = new Colon2Node(getPosition(), ((Node)yyVals[-2+yyTop]), ((String)yyVals[0+yyTop]));
}
break;
case 279:
// line 1070 "DefaultRubyParser.y"
{
yyVal = new Colon3Node(getPosition(), ((String)yyVals[0+yyTop]));
}
break;
case 280:
// line 1073 "DefaultRubyParser.y"
{
yyVal = new CallNode(getPosition(), ((Node)yyVals[-3+yyTop]), "[]", ((Node)yyVals[-1+yyTop]));
}
break;
case 281:
// line 1076 "DefaultRubyParser.y"
{
if (((Node)yyVals[-1+yyTop]) == null) {
yyVal = new ZArrayNode(getPosition()); /* zero length array*/
} else {
yyVal = ((Node)yyVals[-1+yyTop]);
}
}
break;
case 282:
// line 1083 "DefaultRubyParser.y"
{
yyVal = new HashNode(getPosition(), ((ListNode)yyVals[-1+yyTop]));
}
break;
case 283:
// line 1086 "DefaultRubyParser.y"
{
yyVal = new ReturnNode(getPosition(), null);
}
break;
case 284:
// line 1089 "DefaultRubyParser.y"
{
yyVal = support.new_yield(getPosition(), ((Node)yyVals[-1+yyTop]));
}
break;
case 285:
// line 1092 "DefaultRubyParser.y"
{
yyVal = new YieldNode(getPosition(), null, false);
}
break;
case 286:
// line 1095 "DefaultRubyParser.y"
{
yyVal = new YieldNode(getPosition(), null, false);
}
break;
case 287:
// line 1098 "DefaultRubyParser.y"
{
support.setInDefined(true);
}
break;
case 288:
// line 1100 "DefaultRubyParser.y"
{
support.setInDefined(false);
yyVal = new DefinedNode(getPosition(), ((Node)yyVals[-1+yyTop]));
}
break;
case 289:
// line 1104 "DefaultRubyParser.y"
{
((IterNode)yyVals[0+yyTop]).setIterNode(new FCallNode(getPosition(), ((String)yyVals[-1+yyTop]), null));
yyVal = ((IterNode)yyVals[0+yyTop]);
}
break;
case 291:
// line 1109 "DefaultRubyParser.y"
{
if (((Node)yyVals[-1+yyTop]) != null && ((Node)yyVals[-1+yyTop]) instanceof BlockPassNode) {
errorHandler.handleError(IErrors.COMPILE_ERROR, null, "Both block arg and actual block given.");
}
((IterNode)yyVals[0+yyTop]).setIterNode(((Node)yyVals[-1+yyTop]));
yyVal = ((IterNode)yyVals[0+yyTop]);
}
break;
case 292:
// line 1116 "DefaultRubyParser.y"
{
yyVal = new IfNode(getPosition(), support.getConditionNode(((Node)yyVals[-4+yyTop])), ((Node)yyVals[-2+yyTop]), ((Node)yyVals[-1+yyTop]));
/* missing from ruby
if (cond_negative(&$$->nd_cond)) {
NODE *tmp = $$->nd_body;
$$->nd_body = $$->nd_else;
$$->nd_else = tmp;
} */
}
break;
case 293:
// line 1125 "DefaultRubyParser.y"
{
yyVal = new IfNode(getPosition(), support.getConditionNode(((Node)yyVals[-4+yyTop])), ((Node)yyVals[-1+yyTop]), ((Node)yyVals[-2+yyTop]));
/* missing from ruby
if (cond_negative(&$$->nd_cond)) {
NODE *tmp = $$->nd_body;
$$->nd_body = $$->nd_else;
$$->nd_else = tmp;
} */
}
break;
case 294:
// line 1134 "DefaultRubyParser.y"
{
lexer.getConditionState().begin();
}
break;
case 295:
// line 1136 "DefaultRubyParser.y"
{
lexer.getConditionState().end();
}
break;
case 296:
// line 1138 "DefaultRubyParser.y"
{
yyVal = new WhileNode(getPosition(), support.getConditionNode(((Node)yyVals[-4+yyTop])), ((Node)yyVals[-1+yyTop]));
/* missing from ruby
if (cond_negative(&$$->nd_cond)) {
nd_set_type($$, NODE_UNTIL);
} */
}
break;
case 297:
// line 1145 "DefaultRubyParser.y"
{
lexer.getConditionState().begin();
}
break;
case 298:
// line 1147 "DefaultRubyParser.y"
{
lexer.getConditionState().end();
}
break;
case 299:
// line 1149 "DefaultRubyParser.y"
{
yyVal = new UntilNode(getPosition(), support.getConditionNode(((Node)yyVals[-4+yyTop])), ((Node)yyVals[-1+yyTop]));
/* missing from ruby
if (cond_negative(&$$->nd_cond)) {
nd_set_type($$, NODE_WHILE);
} */
}
break;
case 300:
// line 1158 "DefaultRubyParser.y"
{
yyVal = new CaseNode(getPosition(), ((Node)yyVals[-3+yyTop]), ((Node)yyVals[-1+yyTop])); /* XXX*/
}
break;
case 301:
// line 1161 "DefaultRubyParser.y"
{
yyVal = new CaseNode(getPosition(), null, ((Node)yyVals[-1+yyTop]));
}
break;
case 302:
// line 1164 "DefaultRubyParser.y"
{
yyVal = ((Node)yyVals[-1+yyTop]);
}
break;
case 303:
// line 1167 "DefaultRubyParser.y"
{
lexer.getConditionState().begin();
}
break;
case 304:
// line 1169 "DefaultRubyParser.y"
{
lexer.getConditionState().end();
}
break;
case 305:
// line 1172 "DefaultRubyParser.y"
{
yyVal = new ForNode(getPosition(), ((Node)yyVals[-7+yyTop]), ((Node)yyVals[-1+yyTop]), ((Node)yyVals[-4+yyTop]));
}
break;
case 306:
// line 1175 "DefaultRubyParser.y"
{
if (support.isInDef() || support.isInSingle()) {
yyerror("class definition in method body");
}
support.setClassNest(support.getClassNest() + 1);
support.getLocalNames().push();
/* $$ = new Integer(ruby.getSourceLine());*/
}
break;
case 307:
// line 1183 "DefaultRubyParser.y"
{
yyVal = new ClassNode(getPosition(), ((Colon2Node)yyVals[-4+yyTop]).getName(), new ScopeNode(support.getLocalNames().getNames(), ((Node)yyVals[-1+yyTop])), ((Node)yyVals[-3+yyTop]));
/* $<Node>$.setLine($<Integer>4.intValue());*/
support.getLocalNames().pop();
support.setClassNest(support.getClassNest() - 1);
}
break;
case 308:
// line 1189 "DefaultRubyParser.y"
{
yyVal = new Boolean(support.isInDef());
support.setInDef(false);
}
break;
case 309:
// line 1192 "DefaultRubyParser.y"
{
yyVal = new Integer(support.getInSingle());
support.setInSingle(0);
support.setClassNest(support.getClassNest() + 1);
support.getLocalNames().push();
}
break;
case 310:
// line 1198 "DefaultRubyParser.y"
{
yyVal = new SClassNode(getPosition(), ((Node)yyVals[-5+yyTop]), new ScopeNode(support.getLocalNames().getNames(), ((Node)yyVals[-1+yyTop])));
support.getLocalNames().pop();
support.setClassNest(support.getClassNest() - 1);
support.setInDef(((Boolean)yyVals[-4+yyTop]).booleanValue());
support.setInSingle(((Integer)yyVals[-2+yyTop]).intValue());
}
break;
case 311:
// line 1205 "DefaultRubyParser.y"
{
if (support.isInDef() || support.isInSingle()) {
yyerror("module definition in method body");
}
support.setClassNest(support.getClassNest() + 1);
support.getLocalNames().push();
/* $$ = new Integer(ruby.getSourceLine());*/
}
break;
case 312:
// line 1213 "DefaultRubyParser.y"
{
yyVal = new ModuleNode(getPosition(), ((Colon2Node)yyVals[-3+yyTop]).getName(), new ScopeNode(support.getLocalNames().getNames(), ((Node)yyVals[-1+yyTop])));
/* $<Node>$.setLine($<Integer>3.intValue());*/
support.getLocalNames().pop();
support.setClassNest(support.getClassNest() - 1);
}
break;
case 313:
// line 1219 "DefaultRubyParser.y"
{
/* missing
$<id>$ = cur_mid;
cur_mid = $2; */
support.setInDef(true);
support.getLocalNames().push();
}
break;
case 314:
// line 1227 "DefaultRubyParser.y"
{
/* was in old jruby grammar support.getClassNest() !=0 || IdUtil.isAttrSet($2) ? Visibility.PUBLIC : Visibility.PRIVATE); */
/* NOEX_PRIVATE for toplevel */
yyVal = new DefnNode(getPosition(), ((String)yyVals[-4+yyTop]), ((Node)yyVals[-2+yyTop]),
new ScopeNode(support.getLocalNames().getNames(), ((Node)yyVals[-1+yyTop])), Visibility.PRIVATE);
/* $<Node>$.setPosFrom($4);*/
support.getLocalNames().pop();
support.setInDef(false);
/* missing cur_mid = $<id>3; */
}
break;
case 315:
// line 1237 "DefaultRubyParser.y"
{
lexer.setState(LexState.EXPR_FNAME);
}
break;
case 316:
// line 1239 "DefaultRubyParser.y"
{
support.setInSingle(support.getInSingle() + 1);
support.getLocalNames().push();
lexer.setState(LexState.EXPR_END); /* force for args */
}
break;
case 317:
// line 1245 "DefaultRubyParser.y"
{
yyVal = new DefsNode(getPosition(), ((Node)yyVals[-7+yyTop]), ((String)yyVals[-4+yyTop]), ((Node)yyVals[-2+yyTop]), new ScopeNode(support.getLocalNames().getNames(), ((Node)yyVals[-1+yyTop])));
/* $<Node>$.setPosFrom($2);*/
support.getLocalNames().pop();
support.setInSingle(support.getInSingle() - 1);
}
break;
case 318:
// line 1251 "DefaultRubyParser.y"
{
yyVal = new BreakNode(getPosition());
}
break;
case 319:
// line 1254 "DefaultRubyParser.y"
{
yyVal = new NextNode(getPosition());
}
break;
case 320:
// line 1257 "DefaultRubyParser.y"
{
yyVal = new RedoNode(getPosition());
}
break;
case 321:
// line 1260 "DefaultRubyParser.y"
{
yyVal = new RetryNode(getPosition());
}
break;
case 322:
// line 1264 "DefaultRubyParser.y"
{
support.checkExpression(((Node)yyVals[0+yyTop]));
yyVal = ((Node)yyVals[0+yyTop]);
}
break;
case 331:
// line 1281 "DefaultRubyParser.y"
{
yyVal = new IfNode(getPosition(), support.getConditionNode(((Node)yyVals[-3+yyTop])), ((Node)yyVals[-1+yyTop]), ((Node)yyVals[0+yyTop]));
}
break;
case 333:
// line 1286 "DefaultRubyParser.y"
{
yyVal = ((Node)yyVals[0+yyTop]);
}
break;
case 335:
// line 1291 "DefaultRubyParser.y"
{}
break;
case 337:
// line 1294 "DefaultRubyParser.y"
{
yyVal = new ZeroArgNode();
}
break;
case 338:
// line 1297 "DefaultRubyParser.y"
{
yyVal = new ZeroArgNode();
}
break;
case 339:
// line 1300 "DefaultRubyParser.y"
{
yyVal = ((Node)yyVals[-1+yyTop]);
}
break;
case 340:
// line 1304 "DefaultRubyParser.y"
{
support.getBlockNames().push();
}
break;
case 341:
// line 1307 "DefaultRubyParser.y"
{
yyVal = new IterNode(getPosition(), ((Node)yyVals[-2+yyTop]), ((Node)yyVals[-1+yyTop]), null);
support.getBlockNames().pop();
}
break;
case 342:
// line 1312 "DefaultRubyParser.y"
{
if (((Node)yyVals[-1+yyTop]) instanceof BlockPassNode) {
errorHandler.handleError(IErrors.COMPILE_ERROR, null, "Both block arg and actual block given.");
}
((IterNode)yyVals[0+yyTop]).setIterNode(((Node)yyVals[-1+yyTop]));
yyVal = ((IterNode)yyVals[0+yyTop]);
}
break;
case 343:
// line 1319 "DefaultRubyParser.y"
{
yyVal = support.new_call(((Node)yyVals[-3+yyTop]), ((String)yyVals[-1+yyTop]), ((Node)yyVals[0+yyTop]));
}
break;
case 344:
// line 1322 "DefaultRubyParser.y"
{
yyVal = support.new_call(((Node)yyVals[-3+yyTop]), ((String)yyVals[-1+yyTop]), ((Node)yyVals[0+yyTop]));
}
break;
case 345:
// line 1326 "DefaultRubyParser.y"
{
yyVal = support.new_fcall(((String)yyVals[-1+yyTop]), ((Node)yyVals[0+yyTop]), getPosition()); /* .setPosFrom($2);*/
}
break;
case 346:
// line 1329 "DefaultRubyParser.y"
{
yyVal = support.new_call(((Node)yyVals[-3+yyTop]), ((String)yyVals[-1+yyTop]), ((Node)yyVals[0+yyTop])); /*.setPosFrom($1);*/
}
break;
case 347:
// line 1332 "DefaultRubyParser.y"
{
yyVal = support.new_call(((Node)yyVals[-3+yyTop]), ((String)yyVals[-1+yyTop]), ((Node)yyVals[0+yyTop])); /*.setPosFrom($1);*/
}
break;
case 348:
// line 1335 "DefaultRubyParser.y"
{
yyVal = support.new_call(((Node)yyVals[-2+yyTop]), ((String)yyVals[0+yyTop]), null);
}
break;
case 349:
// line 1338 "DefaultRubyParser.y"
{
yyVal = support.new_super(((Node)yyVals[0+yyTop]), getPosition());
}
break;
case 350:
// line 1341 "DefaultRubyParser.y"
{
yyVal = new ZSuperNode(getPosition());
}
break;
case 351:
// line 1345 "DefaultRubyParser.y"
{
support.getBlockNames().push();
}
break;
case 352:
// line 1347 "DefaultRubyParser.y"
{
yyVal = new IterNode(getPosition(), ((Node)yyVals[-2+yyTop]), ((Node)yyVals[-1+yyTop]), null);
support.getBlockNames().pop();
}
break;
case 353:
// line 1351 "DefaultRubyParser.y"
{
support.getBlockNames().push();
}
break;
case 354:
// line 1353 "DefaultRubyParser.y"
{
yyVal = new IterNode(getPosition(), ((Node)yyVals[-2+yyTop]), ((Node)yyVals[-1+yyTop]), null);
support.getBlockNames().pop();
}
break;
case 355:
// line 1360 "DefaultRubyParser.y"
{
yyVal = new WhenNode(getPosition(), ((ListNode)yyVals[-3+yyTop]), ((Node)yyVals[-1+yyTop]), ((Node)yyVals[0+yyTop]));
}
break;
case 357:
// line 1365 "DefaultRubyParser.y"
{
yyVal = ((ListNode)yyVals[-3+yyTop]).add(new WhenNode(getPosition(), new ArrayNode(getPosition()).add(((Node)yyVals[0+yyTop])), null, null));
}
break;
case 358:
// line 1368 "DefaultRubyParser.y"
{
yyVal = new ArrayNode(getPosition()).add(new WhenNode(getPosition(), new ArrayNode(getPosition()).add(((Node)yyVals[0+yyTop])), null, null));
}
break;
case 361:
// line 1378 "DefaultRubyParser.y"
{
Node node;
if (((Node)yyVals[-3+yyTop]) != null) {
node = support.appendToBlock(support.node_assign(((Node)yyVals[-3+yyTop]), new GlobalVarNode(getPosition(), "$!")), ((Node)yyVals[-1+yyTop]));
} else {
node = ((Node)yyVals[-1+yyTop]);
}
yyVal = new RescueBodyNode(getPosition(), ((Node)yyVals[-4+yyTop]), node, ((RescueBodyNode)yyVals[0+yyTop]));
}
break;
case 362:
// line 1387 "DefaultRubyParser.y"
{yyVal = null;}
break;
case 363:
// line 1389 "DefaultRubyParser.y"
{
yyVal = new ArrayNode(getPosition()).add(((Node)yyVals[0+yyTop]));
}
break;
case 366:
// line 1395 "DefaultRubyParser.y"
{
yyVal = ((Node)yyVals[0+yyTop]);
}
break;
case 368:
// line 1400 "DefaultRubyParser.y"
{
if (((Node)yyVals[0+yyTop]) != null) {
yyVal = ((Node)yyVals[0+yyTop]);
} else {
yyVal = new NilNode(null);
}
}
break;
case 371:
// line 1410 "DefaultRubyParser.y"
{
yyVal = new SymbolNode(getPosition(), ((String)yyVals[0+yyTop]));
}
break;
case 373:
// line 1415 "DefaultRubyParser.y"
{
if (((Node)yyVals[0+yyTop]) == null) {
yyVal = new StrNode(getPosition(), "");
} else {
if (((Node)yyVals[0+yyTop]) instanceof EvStrNode) {
yyVal = new DStrNode(getPosition()).add(((Node)yyVals[0+yyTop]));
} else {
yyVal = ((Node)yyVals[0+yyTop]);
}
}
}
break;
case 375:
// line 1428 "DefaultRubyParser.y"
{
yyVal = support.literal_concat(getPosition(), ((Node)yyVals[-1+yyTop]), ((Node)yyVals[0+yyTop]));
}
break;
case 376:
// line 1432 "DefaultRubyParser.y"
{
yyVal = ((Node)yyVals[-1+yyTop]);
}
break;
case 377:
// line 1436 "DefaultRubyParser.y"
{
if (((Node)yyVals[-1+yyTop]) == null) {
yyVal = new XStrNode(getPosition(), null);
} else {
if (((Node)yyVals[-1+yyTop]) instanceof StrNode) {
yyVal = new XStrNode(getPosition(), ((StrNode)yyVals[-1+yyTop]).getValue());
} else if (((Node)yyVals[-1+yyTop]) instanceof DStrNode) {
yyVal = new DXStrNode(getPosition()).add(((Node)yyVals[-1+yyTop]));
} else {
yyVal = new DXStrNode(getPosition()).add(new ArrayNode(getPosition()).add(((Node)yyVals[-1+yyTop])));
}
}
}
break;
case 378:
// line 1450 "DefaultRubyParser.y"
{
int options = ((RegexpNode)yyVals[0+yyTop]).getOptions();
Node node = ((Node)yyVals[-1+yyTop]);
if (node == null) {
yyVal = new RegexpNode(getPosition(), "", options & ~ReOptions.RE_OPTION_ONCE);
} else if (node instanceof StrNode) {
yyVal = new RegexpNode(getPosition(), ((StrNode) node).getValue(), options & ~ReOptions.RE_OPTION_ONCE);
} else {
if (node instanceof DStrNode == false) {
node = new DStrNode(getPosition()).add(new ArrayNode(getPosition()).add(node));
}
yyVal = new DRegexpNode(getPosition(), options, (options & ReOptions.RE_OPTION_ONCE) != 0).add(node);
}
}
break;
case 379:
// line 1467 "DefaultRubyParser.y"
{
yyVal = new ZArrayNode(getPosition());
}
break;
case 380:
// line 1470 "DefaultRubyParser.y"
{
yyVal = ((ListNode)yyVals[-1+yyTop]);
}
break;
case 381:
// line 1474 "DefaultRubyParser.y"
{
yyVal = null;
}
break;
case 382:
// line 1477 "DefaultRubyParser.y"
{
Node node = ((Node)yyVals[-1+yyTop]);
if (node instanceof EvStrNode) {
node = new DStrNode(getPosition()).add(node);
}
yyVal = ((ListNode)yyVals[-2+yyTop]).add(node);
}
break;
case 384:
// line 1488 "DefaultRubyParser.y"
{
yyVal = support.literal_concat(getPosition(), ((Node)yyVals[-1+yyTop]), ((Node)yyVals[0+yyTop]));
}
break;
case 385:
// line 1492 "DefaultRubyParser.y"
{
yyVal = new ZArrayNode(getPosition());
}
break;
case 386:
// line 1495 "DefaultRubyParser.y"
{
yyVal = ((ListNode)yyVals[-1+yyTop]);
}
break;
case 387:
// line 1499 "DefaultRubyParser.y"
{
yyVal = null;
}
break;
case 388:
// line 1502 "DefaultRubyParser.y"
{
if (((ListNode)yyVals[-2+yyTop]) == null) {
yyVal = new ArrayNode(getPosition()).add(new StrNode(getPosition(), ((String)yyVals[-1+yyTop])));
} else {
yyVal = ((ListNode)yyVals[-2+yyTop]).add(new StrNode(getPosition(), ((String)yyVals[-1+yyTop])));
}
}
break;
case 389:
// line 1510 "DefaultRubyParser.y"
{
yyVal = null;
}
break;
case 390:
// line 1513 "DefaultRubyParser.y"
{
yyVal = support.literal_concat(getPosition(), ((Node)yyVals[-1+yyTop]), ((Node)yyVals[0+yyTop]));
}
break;
case 391:
// line 1517 "DefaultRubyParser.y"
{
yyVal = null;
}
break;
case 392:
// line 1520 "DefaultRubyParser.y"
{
yyVal = support.literal_concat(getPosition(), ((Node)yyVals[-1+yyTop]), ((Node)yyVals[0+yyTop]));
}
break;
case 393:
// line 1525 "DefaultRubyParser.y"
{
yyVal = new StrNode(getPosition(), ((String)yyVal));
}
break;
case 394:
// line 1528 "DefaultRubyParser.y"
{
yyVal = lexer.strTerm();
lexer.setStrTerm(null);
lexer.setState(LexState.EXPR_BEG);
}
break;
case 395:
// line 1532 "DefaultRubyParser.y"
{
lexer.setStrTerm(((Node)yyVals[-1+yyTop]));
yyVal = new EvStrNode(getPosition(), ((Node)yyVals[0+yyTop]));
}
break;
case 396:
// line 1536 "DefaultRubyParser.y"
{
yyVal = lexer.strTerm();
lexer.setStrTerm(null);
lexer.setState(LexState.EXPR_BEG);
}
break;
case 397:
// line 1540 "DefaultRubyParser.y"
{
lexer.setStrTerm(((Node)yyVals[-2+yyTop]));
Node node = ((Node)yyVals[-1+yyTop]);
if (node instanceof NewlineNode) {
node = ((NewlineNode)node).getNextNode();
}
yyVal = support.newEvStrNode(getPosition(), node);
}
break;
case 398:
// line 1551 "DefaultRubyParser.y"
{
yyVal = new GlobalVarNode(getPosition(), ((String)yyVals[0+yyTop]));
}
break;
case 399:
// line 1554 "DefaultRubyParser.y"
{
yyVal = new InstVarNode(getPosition(), ((String)yyVals[0+yyTop]));
}
break;
case 400:
// line 1557 "DefaultRubyParser.y"
{
yyVal = new ClassVarNode(getPosition(), ((String)yyVals[0+yyTop]));
}
break;
case 402:
// line 1563 "DefaultRubyParser.y"
{
lexer.setState(LexState.EXPR_END);
yyVal = ((String)yyVals[0+yyTop]);
}
break;
case 407:
// line 1573 "DefaultRubyParser.y"
{
lexer.setState(LexState.EXPR_END);
/* In ruby, it seems to be possible to get a*/
/* StrNode (NODE_STR) among other node type. This */
/* is not possible for us. We will always have a */
/* DStrNode (NODE_DSTR).*/
yyVal = new DSymbolNode(getPosition(), ((DStrNode)yyVals[-1+yyTop]));
}
break;
case 408:
// line 1583 "DefaultRubyParser.y"
{
if (((Number)yyVals[0+yyTop]) instanceof Long) {
yyVal = new FixnumNode(getPosition(), ((Long)yyVals[0+yyTop]).longValue());
} else {
yyVal = new BignumNode(getPosition(), ((BigInteger)yyVals[0+yyTop]));
}
}
break;
case 409:
// line 1590 "DefaultRubyParser.y"
{
yyVal = new FloatNode(getPosition(), ((Double)yyVals[0+yyTop]).doubleValue());
}
break;
case 410:
// line 1593 "DefaultRubyParser.y"
{
yyVal = support.getOperatorCallNode((((Number)yyVals[0+yyTop]) instanceof Long ? (Node) new FixnumNode(getPosition(), ((Long)yyVals[0+yyTop]).longValue()) : (Node) new BignumNode(getPosition(), ((BigInteger)yyVals[0+yyTop]))), "-@");
}
break;
case 411:
// line 1596 "DefaultRubyParser.y"
{
yyVal = support.getOperatorCallNode(new FloatNode(getPosition(), ((Double)yyVals[0+yyTop]).doubleValue()), "-@");
}
break;
case 412:
// line 1605 "DefaultRubyParser.y"
{
yyVal = ((String)yyVals[0+yyTop]);
}
break;
case 413:
// line 1608 "DefaultRubyParser.y"
{
yyVal = ((String)yyVals[0+yyTop]);
}
break;
case 414:
// line 1611 "DefaultRubyParser.y"
{
yyVal = ((String)yyVals[0+yyTop]);
}
break;
case 415:
// line 1614 "DefaultRubyParser.y"
{
yyVal = ((String)yyVals[0+yyTop]);
}
break;
case 416:
// line 1617 "DefaultRubyParser.y"
{
yyVal = ((String)yyVals[0+yyTop]);
}
break;
case 417:
// line 1620 "DefaultRubyParser.y"
{
yyVal = new NilNode(getPosition());
}
break;
case 418:
// line 1623 "DefaultRubyParser.y"
{
yyVal = new SelfNode(getPosition());
}
break;
case 419:
// line 1626 "DefaultRubyParser.y"
{
yyVal = new TrueNode(getPosition());
}
break;
case 420:
// line 1629 "DefaultRubyParser.y"
{
yyVal = new FalseNode(getPosition());
}
break;
case 421:
// line 1632 "DefaultRubyParser.y"
{
yyVal = new StrNode(getPosition(), getPosition().getFile());
}
break;
case 422:
// line 1635 "DefaultRubyParser.y"
{
yyVal = new FixnumNode(getPosition(), getPosition().getLine());
}
break;
case 423:
// line 1639 "DefaultRubyParser.y"
{
/* Work around __LINE__ and __FILE__ */
if (yyVals[0+yyTop] instanceof INameNode) {
String name = ((INameNode)yyVals[0+yyTop]).getName();
yyVal = support.gettable(name, getPosition());
} else if (yyVals[0+yyTop] instanceof String) {
yyVal = support.gettable(((String)yyVals[0+yyTop]), getPosition());
} else {
yyVal = yyVals[0+yyTop];
}
}
break;
case 424:
// line 1652 "DefaultRubyParser.y"
{
yyVal = support.assignable(getPosition(), yyVals[0+yyTop], null);
}
break;
case 427:
// line 1659 "DefaultRubyParser.y"
{
yyVal = null;
}
break;
case 428:
// line 1662 "DefaultRubyParser.y"
{
lexer.setState(LexState.EXPR_BEG);
}
break;
case 429:
// line 1664 "DefaultRubyParser.y"
{
yyVal = ((Node)yyVals[-1+yyTop]);
}
break;
case 430:
// line 1667 "DefaultRubyParser.y"
{
yyerrok();
yyVal = null;
}
break;
case 431:
// line 1672 "DefaultRubyParser.y"
{
yyVal = ((Node)yyVals[-2+yyTop]);
lexer.setState(LexState.EXPR_BEG);
}
break;
case 432:
// line 1676 "DefaultRubyParser.y"
{
yyVal = ((Node)yyVals[-1+yyTop]);
}
break;
case 433:
// line 1680 "DefaultRubyParser.y"
{
yyVal = new ArgsNode(getPosition(), ((Integer)yyVals[-5+yyTop]).intValue(), ((ListNode)yyVals[-3+yyTop]), ((Integer)yyVals[-1+yyTop]).intValue(), ((BlockArgNode)yyVals[0+yyTop]));
}
break;
case 434:
// line 1683 "DefaultRubyParser.y"
{
yyVal = new ArgsNode(getPosition(), ((Integer)yyVals[-3+yyTop]).intValue(), ((ListNode)yyVals[-1+yyTop]), -1, ((BlockArgNode)yyVals[0+yyTop]));
}
break;
case 435:
// line 1686 "DefaultRubyParser.y"
{
yyVal = new ArgsNode(getPosition(), ((Integer)yyVals[-3+yyTop]).intValue(), null, ((Integer)yyVals[-1+yyTop]).intValue(), ((BlockArgNode)yyVals[0+yyTop]));
}
break;
case 436:
// line 1689 "DefaultRubyParser.y"
{
int h = ((Integer)yyVals[-1+yyTop]).intValue();
yyVal = new ArgsNode(getPosition(), h, null, -1, ((BlockArgNode)yyVals[0+yyTop]));
}
break;
case 437:
// line 1692 "DefaultRubyParser.y"
{
yyVal = new ArgsNode(getPosition(), 0, ((ListNode)yyVals[-3+yyTop]), ((Integer)yyVals[-1+yyTop]).intValue(), ((BlockArgNode)yyVals[0+yyTop]));
}
break;
case 438:
// line 1695 "DefaultRubyParser.y"
{
yyVal = new ArgsNode(getPosition(), 0, ((ListNode)yyVals[-1+yyTop]), -1, ((BlockArgNode)yyVals[0+yyTop]));
}
break;
case 439:
// line 1698 "DefaultRubyParser.y"
{
yyVal = new ArgsNode(getPosition(), 0, null, ((Integer)yyVals[-1+yyTop]).intValue(), ((BlockArgNode)yyVals[0+yyTop]));
}
break;
case 440:
// line 1701 "DefaultRubyParser.y"
{
yyVal = new ArgsNode(getPosition(), 0, null, -1, ((BlockArgNode)yyVals[0+yyTop]));
}
break;
case 441:
// line 1704 "DefaultRubyParser.y"
{
yyVal = new ArgsNode(getPosition(), 0, null, -1, null);
}
break;
case 442:
// line 1708 "DefaultRubyParser.y"
{
yyerror("formal argument cannot be a constant");
}
break;
case 443:
// line 1711 "DefaultRubyParser.y"
{
yyerror("formal argument cannot be an instance variable");
}
break;
case 444:
// line 1714 "DefaultRubyParser.y"
{
yyerror("formal argument cannot be a class variable");
}
break;
case 445:
// line 1717 "DefaultRubyParser.y"
{
if (!IdUtil.isLocal(((String)yyVals[0+yyTop]))) {
yyerror("formal argument must be local variable");
} else if (support.getLocalNames().isLocalRegistered(((String)yyVals[0+yyTop]))) {
yyerror("duplicate argument name");
}
support.getLocalNames().getLocalIndex(((String)yyVals[0+yyTop]));
yyVal = new Integer(1);
}
break;
case 447:
// line 1728 "DefaultRubyParser.y"
{
yyVal = new Integer(((Integer)yyVal).intValue() + 1);
}
break;
case 448:
// line 1732 "DefaultRubyParser.y"
{
if (!IdUtil.isLocal(((String)yyVals[-2+yyTop]))) {
yyerror("formal argument must be local variable");
} else if (support.getLocalNames().isLocalRegistered(((String)yyVals[-2+yyTop]))) {
yyerror("duplicate optional argument name");
}
support.getLocalNames().getLocalIndex(((String)yyVals[-2+yyTop]));
yyVal = support.assignable(getPosition(), ((String)yyVals[-2+yyTop]), ((Node)yyVals[0+yyTop]));
}
break;
case 449:
// line 1742 "DefaultRubyParser.y"
{
yyVal = new ArrayNode(getPosition()).add(((Node)yyVals[0+yyTop]));
}
break;
case 450:
// line 1745 "DefaultRubyParser.y"
{
yyVal = ((ListNode)yyVals[-2+yyTop]).add(((Node)yyVals[0+yyTop]));
}
break;
case 453:
// line 1752 "DefaultRubyParser.y"
{
if (!IdUtil.isLocal(((String)yyVals[0+yyTop]))) {
yyerror("rest argument must be local variable");
} else if (support.getLocalNames().isLocalRegistered(((String)yyVals[0+yyTop]))) {
yyerror("duplicate rest argument name");
}
yyVal = new Integer(support.getLocalNames().getLocalIndex(((String)yyVals[0+yyTop])));
}
break;
case 454:
// line 1760 "DefaultRubyParser.y"
{
yyVal = new Integer(-2);
}
break;
case 457:
// line 1767 "DefaultRubyParser.y"
{
if (!IdUtil.isLocal(((String)yyVals[0+yyTop]))) {
yyerror("block argument must be local variable");
} else if (support.getLocalNames().isLocalRegistered(((String)yyVals[0+yyTop]))) {
yyerror("duplicate block argument name");
}
yyVal = new BlockArgNode(getPosition(), support.getLocalNames().getLocalIndex(((String)yyVals[0+yyTop])));
}
break;
case 458:
// line 1776 "DefaultRubyParser.y"
{
yyVal = ((BlockArgNode)yyVals[0+yyTop]);
}
break;
case 459:
// line 1779 "DefaultRubyParser.y"
{
yyVal = null;
}
break;
case 460:
// line 1783 "DefaultRubyParser.y"
{
if (((Node)yyVals[0+yyTop]) instanceof SelfNode) {
yyVal = new SelfNode(null);
} else {
support.checkExpression(((Node)yyVals[0+yyTop]));
yyVal = ((Node)yyVals[0+yyTop]);
}
}
break;
case 461:
// line 1791 "DefaultRubyParser.y"
{
lexer.setState(LexState.EXPR_BEG);
}
break;
case 462:
// line 1793 "DefaultRubyParser.y"
{
if (((Node)yyVals[-2+yyTop]) instanceof ILiteralNode) {
/*case Constants.NODE_STR:
case Constants.NODE_DSTR:
case Constants.NODE_XSTR:
case Constants.NODE_DXSTR:
case Constants.NODE_DREGX:
case Constants.NODE_LIT:
case Constants.NODE_ARRAY:
case Constants.NODE_ZARRAY:*/
yyerror("Can't define single method for literals.");
}
support.checkExpression(((Node)yyVals[-2+yyTop]));
yyVal = ((Node)yyVals[-2+yyTop]);
}
break;
case 464:
// line 1810 "DefaultRubyParser.y"
{
yyVal = ((ListNode)yyVals[-1+yyTop]);
}
break;
case 465:
// line 1813 "DefaultRubyParser.y"
{
if (ListNodeUtil.getLength(((ListNode)yyVals[-1+yyTop])) % 2 != 0) {
yyerror("Odd number list for Hash.");
}
yyVal = ((ListNode)yyVals[-1+yyTop]);
}
break;
case 467:
// line 1821 "DefaultRubyParser.y"
{
yyVal = ListNodeUtil.addAll(((ListNode)yyVals[-2+yyTop]), ((ListNode)yyVals[0+yyTop]));
}
break;
case 468:
// line 1825 "DefaultRubyParser.y"
{
yyVal = new ArrayNode(getPosition()).add(((Node)yyVals[-2+yyTop])).add(((Node)yyVals[0+yyTop]));
}
break;
case 488:
// line 1855 "DefaultRubyParser.y"
{
yyerrok();
}
break;
case 491:
// line 1861 "DefaultRubyParser.y"
{
yyerrok();
}
break;
case 492:
// line 1865 "DefaultRubyParser.y"
{
yyVal = null;
}
break;
case 493:
// line 1869 "DefaultRubyParser.y"
{ yyVal = null;
}
break;
case 494:
// line 1872 "DefaultRubyParser.y"
{ yyVal = null;
}
break;
// line 2921 "-"
}
yyTop -= YyLenClass.yyLen[yyN];
yyState = yyStates[yyTop];
int yyM = YyLhsClass.yyLhs[yyN];
if (yyState == 0 && yyM == 0) {
yyState = yyFinal;
if (yyToken < 0) {
yyToken = yyLex.advance() ? yyLex.token() : 0;
}
if (yyToken == 0) {
return yyVal;
}
continue yyLoop;
}
if ((yyN = YyGindexClass.yyGindex[yyM]) != 0 && (yyN += yyState) >= 0
&& yyN < YyTableClass.yyTable.length && YyCheckClass.yyCheck[yyN] == yyState)
yyState = YyTableClass.yyTable[yyN];
else
yyState = YyDgotoClass.yyDgoto[yyM];
continue yyLoop;
}
}
}
| public Object yyparse (RubyYaccLexer yyLex)
throws java.io.IOException, yyException {
if (yyMax <= 0) yyMax = 256; // initial size
int yyState = 0, yyStates[] = new int[yyMax]; // state stack
Object yyVal = null, yyVals[] = new Object[yyMax]; // value stack
int yyToken = -1; // current input
int yyErrorFlag = 0; // #tks to shift
yyLoop: for (int yyTop = 0;; ++ yyTop) {
if (yyTop >= yyStates.length) { // dynamically increase
int[] i = new int[yyStates.length+yyMax];
System.arraycopy(yyStates, 0, i, 0, yyStates.length);
yyStates = i;
Object[] o = new Object[yyVals.length+yyMax];
System.arraycopy(yyVals, 0, o, 0, yyVals.length);
yyVals = o;
}
yyStates[yyTop] = yyState;
yyVals[yyTop] = yyVal;
yyDiscarded: for (;;) { // discarding a token does not change stack
int yyN;
if ((yyN = YyDefRedClass.yyDefRed[yyState]) == 0) { // else [default] reduce (yyN)
if (yyToken < 0) {
yyToken = yyLex.advance() ? yyLex.token() : 0;
}
if ((yyN = YySindexClass.yySindex[yyState]) != 0 && (yyN += yyToken) >= 0
&& yyN < YyTableClass.yyTable.length && YyCheckClass.yyCheck[yyN] == yyToken) {
yyState = YyTableClass.yyTable[yyN]; // shift to yyN
yyVal = yyLex.value();
yyToken = -1;
if (yyErrorFlag > 0) -- yyErrorFlag;
continue yyLoop;
}
if ((yyN = YyRindexClass.yyRindex[yyState]) != 0 && (yyN += yyToken) >= 0
&& yyN < YyTableClass.yyTable.length && YyCheckClass.yyCheck[yyN] == yyToken)
yyN = YyTableClass.yyTable[yyN]; // reduce (yyN)
else
switch (yyErrorFlag) {
case 0:
yyerror("syntax error", new SyntaxErrorState(yyExpecting(yyState), YyNameClass.yyName[yyToken]));
case 1: case 2:
yyErrorFlag = 3;
do {
if ((yyN = YySindexClass.yySindex[yyStates[yyTop]]) != 0
&& (yyN += yyErrorCode) >= 0 && yyN < YyTableClass.yyTable.length
&& YyCheckClass.yyCheck[yyN] == yyErrorCode) {
yyState = YyTableClass.yyTable[yyN];
yyVal = yyLex.value();
continue yyLoop;
}
} while (-- yyTop >= 0);
throw new yyException("irrecoverable syntax error");
case 3:
if (yyToken == 0) {
throw new yyException("irrecoverable syntax error at end-of-file");
}
yyToken = -1;
continue yyDiscarded; // leave stack alone
}
}
int yyV = yyTop + 1-YyLenClass.yyLen[yyN];
yyVal = yyDefault(yyV > yyTop ? null : yyVals[yyV]);
switch (yyN) {
case 1:
// line 214 "DefaultRubyParser.y"
{
lexer.setState(LexState.EXPR_BEG);
support.initTopLocalVariables();
/* Fix: Move to ruby runtime....?*/
/*if (ruby.getRubyClass() == ruby.getClasses().getObjectClass()) {*/
/* support.setClassNest(0);*/
/*} else {*/
/* support.setClassNest(1);*/
/*}*/
}
break;
case 2:
// line 224 "DefaultRubyParser.y"
{
if (((Node)yyVals[0+yyTop]) != null && !support.isCompileForEval()) {
/* last expression should not be void */
if (((Node)yyVals[0+yyTop]) instanceof BlockNode) {
support.checkUselessStatement(ListNodeUtil.getLast(((BlockNode)yyVals[0+yyTop])));
} else {
support.checkUselessStatement(((Node)yyVals[0+yyTop]));
}
}
support.getResult().setAST(support.appendToBlock(support.getResult().getAST(), ((Node)yyVals[0+yyTop])));
support.updateTopLocalVariables();
support.setClassNest(0);
}
break;
case 3:
// line 241 "DefaultRubyParser.y"
{
Node node = ((Node)yyVals[-3+yyTop]);
if (((RescueBodyNode)yyVals[-2+yyTop]) != null) {
node = new RescueNode(getPosition(), ((Node)yyVals[-3+yyTop]), ((RescueBodyNode)yyVals[-2+yyTop]), ((Node)yyVals[-1+yyTop]));
} else if (((Node)yyVals[-1+yyTop]) != null) {
errorHandler.handleError(IErrors.WARN, null, "else without rescue is useless");
node = support.appendToBlock(((Node)yyVals[-3+yyTop]), ((Node)yyVals[-1+yyTop]));
}
if (((Node)yyVals[0+yyTop]) != null) {
node = new EnsureNode(getPosition(), node, ((Node)yyVals[0+yyTop]));
}
yyVal = node;
}
break;
case 4:
// line 257 "DefaultRubyParser.y"
{
if (((Node)yyVals[-1+yyTop]) instanceof BlockNode) {
support.checkUselessStatements(((BlockNode)yyVals[-1+yyTop]));
}
yyVal = ((Node)yyVals[-1+yyTop]);
}
break;
case 6:
// line 265 "DefaultRubyParser.y"
{
yyVal = support.newline_node(((Node)yyVals[0+yyTop]), getPosition());
}
break;
case 7:
// line 268 "DefaultRubyParser.y"
{
yyVal = support.appendToBlock(((Node)yyVals[-2+yyTop]), support.newline_node(((Node)yyVals[0+yyTop]), getPosition()));
}
break;
case 8:
// line 271 "DefaultRubyParser.y"
{
yyVal = ((Node)yyVals[0+yyTop]);
}
break;
case 9:
// line 275 "DefaultRubyParser.y"
{
lexer.setState(LexState.EXPR_FNAME);
}
break;
case 10:
// line 277 "DefaultRubyParser.y"
{
yyVal = new AliasNode(getPosition(), ((String)yyVals[-2+yyTop]), ((String)yyVals[0+yyTop]));
}
break;
case 11:
// line 280 "DefaultRubyParser.y"
{
yyVal = new VAliasNode(getPosition(), ((String)yyVals[-1+yyTop]), ((String)yyVals[0+yyTop]));
}
break;
case 12:
// line 283 "DefaultRubyParser.y"
{
yyVal = new VAliasNode(getPosition(), ((String)yyVals[-1+yyTop]), "$" + ((BackRefNode)yyVals[0+yyTop]).getType()); /* XXX*/
}
break;
case 13:
// line 286 "DefaultRubyParser.y"
{
yyerror("can't make alias for the number variables");
yyVal = null; /*XXX 0*/
}
break;
case 14:
// line 290 "DefaultRubyParser.y"
{
yyVal = ((Node)yyVals[0+yyTop]);
}
break;
case 15:
// line 293 "DefaultRubyParser.y"
{
yyVal = new IfNode(getPosition(), support.getConditionNode(((Node)yyVals[0+yyTop])), ((Node)yyVals[-2+yyTop]), null);
}
break;
case 16:
// line 296 "DefaultRubyParser.y"
{
yyVal = new IfNode(getPosition(), support.getConditionNode(((Node)yyVals[0+yyTop])), null, ((Node)yyVals[-2+yyTop]));
}
break;
case 17:
// line 299 "DefaultRubyParser.y"
{
if (((Node)yyVals[-2+yyTop]) != null && ((Node)yyVals[-2+yyTop]) instanceof BeginNode) {
yyVal = new WhileNode(getPosition(), support.getConditionNode(((Node)yyVals[0+yyTop])), ((BeginNode)yyVals[-2+yyTop]).getBodyNode(), false);
} else {
yyVal = new WhileNode(getPosition(), support.getConditionNode(((Node)yyVals[0+yyTop])), ((Node)yyVals[-2+yyTop]), true);
}
}
break;
case 18:
// line 306 "DefaultRubyParser.y"
{
if (((Node)yyVals[-2+yyTop]) != null && ((Node)yyVals[-2+yyTop]) instanceof BeginNode) {
yyVal = new UntilNode(getPosition(), support.getConditionNode(((Node)yyVals[0+yyTop])), ((BeginNode)yyVals[-2+yyTop]).getBodyNode());
} else {
yyVal = new UntilNode(getPosition(), support.getConditionNode(((Node)yyVals[0+yyTop])), ((Node)yyVals[-2+yyTop]));
}
}
break;
case 19:
// line 314 "DefaultRubyParser.y"
{
yyVal = new RescueNode(getPosition(), ((Node)yyVals[-2+yyTop]), new RescueBodyNode(getPosition(), null,((Node)yyVals[0+yyTop]), null), null);
}
break;
case 20:
// line 318 "DefaultRubyParser.y"
{
if (support.isInDef() || support.isInSingle()) {
yyerror("BEGIN in method");
}
support.getLocalNames().push();
}
break;
case 21:
// line 323 "DefaultRubyParser.y"
{
support.getResult().setBeginNodes(support.appendToBlock(support.getResult().getBeginNodes(), new ScopeNode(support.getLocalNames().getNames(), ((Node)yyVals[-1+yyTop]))));
support.getLocalNames().pop();
yyVal = null; /*XXX 0;*/
}
break;
case 22:
// line 328 "DefaultRubyParser.y"
{
if (support.isInDef() || support.isInSingle()) {
yyerror("END in method; use at_exit");
}
yyVal = new IterNode(getPosition(), null, new PostExeNode(getPosition()), ((Node)yyVals[-1+yyTop]));
}
break;
case 23:
// line 334 "DefaultRubyParser.y"
{
support.checkExpression(((Node)yyVals[0+yyTop]));
yyVal = support.node_assign(((Node)yyVals[-2+yyTop]), ((Node)yyVals[0+yyTop]));
}
break;
case 24:
// line 338 "DefaultRubyParser.y"
{
support.checkExpression(((Node)yyVals[0+yyTop]));
if (((MultipleAsgnNode)yyVals[-2+yyTop]).getHeadNode() != null) {
((MultipleAsgnNode)yyVals[-2+yyTop]).setValueNode(new ToAryNode(getPosition(), ((Node)yyVals[0+yyTop])));
} else {
((MultipleAsgnNode)yyVals[-2+yyTop]).setValueNode(new ArrayNode(getPosition()).add(((Node)yyVals[0+yyTop])));
}
yyVal = ((MultipleAsgnNode)yyVals[-2+yyTop]);
}
break;
case 25:
// line 347 "DefaultRubyParser.y"
{
support.checkExpression(((Node)yyVals[0+yyTop]));
if (yyVals[-2+yyTop] != null) {
String name = ((INameNode)yyVals[-2+yyTop]).getName();
if (((String)yyVals[-1+yyTop]).equals("||")) {
((AssignableNode)yyVals[-2+yyTop]).setValueNode(((Node)yyVals[0+yyTop]));
yyVal = new OpAsgnOrNode(getPosition(), support.gettable(name, getPosition()), ((Node)yyVals[-2+yyTop]));
/* XXX
if (is_asgn_or_id(vid)) {
$$->nd_aid = vid;
}
*/
} else if (((String)yyVals[-1+yyTop]).equals("&&")) {
((AssignableNode)yyVals[-2+yyTop]).setValueNode(((Node)yyVals[0+yyTop]));
yyVal = new OpAsgnAndNode(getPosition(), support.gettable(name, getPosition()), ((Node)yyVals[-2+yyTop]));
} else {
yyVal = yyVals[-2+yyTop];
if (yyVal != null) {
((AssignableNode)yyVal).setValueNode(support.getOperatorCallNode(support.gettable(name, getPosition()), ((String)yyVals[-1+yyTop]), ((Node)yyVals[0+yyTop])));
}
}
} else {
yyVal = null;
}
}
break;
case 26:
// line 372 "DefaultRubyParser.y"
{
/* Much smaller than ruby block */
yyVal = new OpElementAsgnNode(getPosition(), ((Node)yyVals[-5+yyTop]), ((String)yyVals[-1+yyTop]), ((Node)yyVals[-3+yyTop]), ((Node)yyVals[0+yyTop]));
}
break;
case 27:
// line 377 "DefaultRubyParser.y"
{
yyVal = new OpAsgnNode(getPosition(), ((Node)yyVals[-4+yyTop]), ((Node)yyVals[0+yyTop]), ((String)yyVals[-2+yyTop]), ((String)yyVals[-1+yyTop]));
}
break;
case 28:
// line 380 "DefaultRubyParser.y"
{
yyVal = new OpAsgnNode(getPosition(), ((Node)yyVals[-4+yyTop]), ((Node)yyVals[0+yyTop]), ((String)yyVals[-2+yyTop]), ((String)yyVals[-1+yyTop]));
}
break;
case 29:
// line 383 "DefaultRubyParser.y"
{
yyVal = new OpAsgnNode(getPosition(), ((Node)yyVals[-4+yyTop]), ((Node)yyVals[0+yyTop]), ((String)yyVals[-2+yyTop]), ((String)yyVals[-1+yyTop]));
}
break;
case 30:
// line 386 "DefaultRubyParser.y"
{
support.backrefAssignError(((Node)yyVals[-2+yyTop]));
yyVal = null;
}
break;
case 31:
// line 390 "DefaultRubyParser.y"
{
yyVal = support.node_assign(((Node)yyVals[-2+yyTop]), new SValueNode(getPosition(), ((Node)yyVals[0+yyTop])));
}
break;
case 32:
// line 393 "DefaultRubyParser.y"
{
if (((MultipleAsgnNode)yyVals[-2+yyTop]).getHeadNode() != null) {
((MultipleAsgnNode)yyVals[-2+yyTop]).setValueNode(new ToAryNode(getPosition(), ((Node)yyVals[0+yyTop])));
} else {
((MultipleAsgnNode)yyVals[-2+yyTop]).setValueNode(new ArrayNode(getPosition()).add(((Node)yyVals[0+yyTop])));
}
yyVal = ((MultipleAsgnNode)yyVals[-2+yyTop]);
}
break;
case 33:
// line 401 "DefaultRubyParser.y"
{
((AssignableNode)yyVals[-2+yyTop]).setValueNode(((Node)yyVals[0+yyTop]));
yyVal = ((MultipleAsgnNode)yyVals[-2+yyTop]);
}
break;
case 36:
// line 408 "DefaultRubyParser.y"
{
yyVal = support.newAndNode(((Node)yyVals[-2+yyTop]), ((Node)yyVals[0+yyTop]));
}
break;
case 37:
// line 411 "DefaultRubyParser.y"
{
yyVal = support.newOrNode(((Node)yyVals[-2+yyTop]), ((Node)yyVals[0+yyTop]));
}
break;
case 38:
// line 414 "DefaultRubyParser.y"
{
yyVal = new NotNode(getPosition(), support.getConditionNode(((Node)yyVals[0+yyTop])));
}
break;
case 39:
// line 417 "DefaultRubyParser.y"
{
yyVal = new NotNode(getPosition(), support.getConditionNode(((Node)yyVals[0+yyTop])));
}
break;
case 41:
// line 422 "DefaultRubyParser.y"
{
support.checkExpression(((Node)yyVals[0+yyTop]));
yyVal = ((Node)yyVals[0+yyTop]); /*Do we really need this set? $1 is $$?*/
}
break;
case 44:
// line 429 "DefaultRubyParser.y"
{
yyVal = new ReturnNode(getPosition(), support.ret_args(((Node)yyVals[0+yyTop]), getPosition()));
}
break;
case 45:
// line 432 "DefaultRubyParser.y"
{
yyVal = new BreakNode(getPosition(), support.ret_args(((Node)yyVals[0+yyTop]), getPosition()));
}
break;
case 46:
// line 435 "DefaultRubyParser.y"
{
yyVal = new NextNode(getPosition(), support.ret_args(((Node)yyVals[0+yyTop]), getPosition()));
}
break;
case 48:
// line 440 "DefaultRubyParser.y"
{
yyVal = support.new_call(((Node)yyVals[-3+yyTop]), ((String)yyVals[-1+yyTop]), ((Node)yyVals[0+yyTop]));
}
break;
case 49:
// line 443 "DefaultRubyParser.y"
{
yyVal = support.new_call(((Node)yyVals[-3+yyTop]), ((String)yyVals[-1+yyTop]), ((Node)yyVals[0+yyTop]));
}
break;
case 50:
// line 447 "DefaultRubyParser.y"
{
support.getBlockNames().push();
}
break;
case 51:
// line 449 "DefaultRubyParser.y"
{
yyVal = new IterNode(getPosition(), ((Node)yyVals[-2+yyTop]), ((Node)yyVals[-1+yyTop]), null);
support.getBlockNames().pop();
}
break;
case 52:
// line 454 "DefaultRubyParser.y"
{
yyVal = support.new_fcall(((String)yyVals[-1+yyTop]), ((Node)yyVals[0+yyTop]), getPosition()); /* .setPosFrom($2);*/
}
break;
case 53:
// line 457 "DefaultRubyParser.y"
{
yyVal = support.new_fcall(((String)yyVals[-2+yyTop]), ((Node)yyVals[-1+yyTop]), getPosition());
if (((IterNode)yyVals[0+yyTop]) != null) {
if (yyVal instanceof BlockPassNode) {
errorHandler.handleError(IErrors.COMPILE_ERROR, null, "Both block arg and actual block given.");
}
((IterNode)yyVals[0+yyTop]).setIterNode(((Node)yyVal));
yyVal = ((Node)yyVals[-1+yyTop]);
}
}
break;
case 54:
// line 467 "DefaultRubyParser.y"
{
yyVal = support.new_call(((Node)yyVals[-3+yyTop]), ((String)yyVals[-1+yyTop]), ((Node)yyVals[0+yyTop])); /*.setPosFrom($1);*/
}
break;
case 55:
// line 470 "DefaultRubyParser.y"
{
yyVal = support.new_call(((Node)yyVals[-4+yyTop]), ((String)yyVals[-2+yyTop]), ((Node)yyVals[-1+yyTop]));
if (((IterNode)yyVals[0+yyTop]) != null) {
if (yyVal instanceof BlockPassNode) {
errorHandler.handleError(IErrors.COMPILE_ERROR, null, "Both block arg and actual block given.");
}
((IterNode)yyVals[0+yyTop]).setIterNode(((Node)yyVal));
yyVal = ((IterNode)yyVals[0+yyTop]);
}
}
break;
case 56:
// line 480 "DefaultRubyParser.y"
{
yyVal = support.new_call(((Node)yyVals[-3+yyTop]), ((String)yyVals[-1+yyTop]), ((Node)yyVals[0+yyTop]));
}
break;
case 57:
// line 483 "DefaultRubyParser.y"
{
yyVal = support.new_call(((Node)yyVals[-4+yyTop]), ((String)yyVals[-2+yyTop]), ((Node)yyVals[-1+yyTop]));
if (((IterNode)yyVals[0+yyTop]) != null) {
if (yyVal instanceof BlockPassNode) {
errorHandler.handleError(IErrors.COMPILE_ERROR, null, "Both block arg and actual block given.");
}
((IterNode)yyVals[0+yyTop]).setIterNode(((Node)yyVal));
yyVal = ((IterNode)yyVals[0+yyTop]);
}
}
break;
case 58:
// line 493 "DefaultRubyParser.y"
{
yyVal = support.new_super(((Node)yyVals[0+yyTop]), getPosition()); /* .setPosFrom($2);*/
}
break;
case 59:
// line 496 "DefaultRubyParser.y"
{
yyVal = support.new_yield(getPosition(), ((Node)yyVals[0+yyTop]));
}
break;
case 61:
// line 501 "DefaultRubyParser.y"
{
yyVal = ((MultipleAsgnNode)yyVals[-1+yyTop]);
}
break;
case 63:
// line 506 "DefaultRubyParser.y"
{
yyVal = new MultipleAsgnNode(getPosition(), new ArrayNode(getPosition()).add(((MultipleAsgnNode)yyVals[-1+yyTop])), null);
}
break;
case 64:
// line 510 "DefaultRubyParser.y"
{
yyVal = new MultipleAsgnNode(getPosition(), ((ListNode)yyVals[0+yyTop]), null);
}
break;
case 65:
// line 513 "DefaultRubyParser.y"
{
yyVal = new MultipleAsgnNode(getPosition(), ((ListNode)yyVals[-1+yyTop]).add(((Node)yyVals[0+yyTop])), null);
}
break;
case 66:
// line 516 "DefaultRubyParser.y"
{
yyVal = new MultipleAsgnNode(getPosition(), ((ListNode)yyVals[-2+yyTop]), ((Node)yyVals[0+yyTop]));
}
break;
case 67:
// line 519 "DefaultRubyParser.y"
{
yyVal = new MultipleAsgnNode(getPosition(), ((ListNode)yyVals[-1+yyTop]), new StarNode());
}
break;
case 68:
// line 522 "DefaultRubyParser.y"
{
yyVal = new MultipleAsgnNode(getPosition(), null, ((Node)yyVals[0+yyTop]));
}
break;
case 69:
// line 525 "DefaultRubyParser.y"
{
yyVal = new MultipleAsgnNode(getPosition(), null, new StarNode());
}
break;
case 71:
// line 530 "DefaultRubyParser.y"
{
yyVal = ((MultipleAsgnNode)yyVals[-1+yyTop]);
}
break;
case 72:
// line 534 "DefaultRubyParser.y"
{
yyVal = new ArrayNode(getPosition()).add(((Node)yyVals[-1+yyTop]));
}
break;
case 73:
// line 537 "DefaultRubyParser.y"
{
yyVal = ((ListNode)yyVals[-2+yyTop]).add(((Node)yyVals[-1+yyTop]));
}
break;
case 74:
// line 541 "DefaultRubyParser.y"
{
yyVal = support.assignable(getPosition(), yyVals[0+yyTop], null);
}
break;
case 75:
// line 544 "DefaultRubyParser.y"
{
yyVal = support.getElementAssignmentNode(((Node)yyVals[-3+yyTop]), ((Node)yyVals[-1+yyTop]));
}
break;
case 76:
// line 547 "DefaultRubyParser.y"
{
yyVal = support.getAttributeAssignmentNode(((Node)yyVals[-2+yyTop]), ((String)yyVals[0+yyTop]));
}
break;
case 77:
// line 550 "DefaultRubyParser.y"
{
yyVal = support.getAttributeAssignmentNode(((Node)yyVals[-2+yyTop]), ((String)yyVals[0+yyTop]));
}
break;
case 78:
// line 553 "DefaultRubyParser.y"
{
yyVal = support.getAttributeAssignmentNode(((Node)yyVals[-2+yyTop]), ((String)yyVals[0+yyTop]));
}
break;
case 79:
// line 556 "DefaultRubyParser.y"
{
if (support.isInDef() || support.isInSingle()) {
yyerror("dynamic constant assignment");
}
yyVal = support.getAttributeAssignmentNode(((Node)yyVals[-2+yyTop]), ((String)yyVals[0+yyTop]));
}
break;
case 80:
// line 563 "DefaultRubyParser.y"
{
if (support.isInDef() || support.isInSingle()) {
yyerror("dynamic constant assignment");
}
/* ERROR: VEry likely a big error. */
yyVal = new Colon3Node(getPosition(), ((String)yyVals[0+yyTop]));
/* ruby $$ = NEW_CDECL(0, 0, NEW_COLON3($2)); */
}
break;
case 81:
// line 573 "DefaultRubyParser.y"
{
support.backrefAssignError(((Node)yyVals[0+yyTop]));
yyVal = null;
}
break;
case 82:
// line 578 "DefaultRubyParser.y"
{
yyVal = support.assignable(getPosition(), yyVals[0+yyTop], null);
}
break;
case 83:
// line 581 "DefaultRubyParser.y"
{
yyVal = support.getElementAssignmentNode(((Node)yyVals[-3+yyTop]), ((Node)yyVals[-1+yyTop]));
}
break;
case 84:
// line 584 "DefaultRubyParser.y"
{
yyVal = support.getAttributeAssignmentNode(((Node)yyVals[-2+yyTop]), ((String)yyVals[0+yyTop]));
}
break;
case 85:
// line 587 "DefaultRubyParser.y"
{
yyVal = support.getAttributeAssignmentNode(((Node)yyVals[-2+yyTop]), ((String)yyVals[0+yyTop]));
}
break;
case 86:
// line 590 "DefaultRubyParser.y"
{
yyVal = support.getAttributeAssignmentNode(((Node)yyVals[-2+yyTop]), ((String)yyVals[0+yyTop]));
}
break;
case 87:
// line 593 "DefaultRubyParser.y"
{
if (support.isInDef() || support.isInSingle()) {
yyerror("dynamic constant assignment");
}
yyVal = support.getAttributeAssignmentNode(((Node)yyVals[-2+yyTop]), ((String)yyVals[0+yyTop]));
}
break;
case 88:
// line 600 "DefaultRubyParser.y"
{
if (support.isInDef() || support.isInSingle()) {
yyerror("dynamic constant assignment");
}
/* ERROR: VEry likely a big error. */
yyVal = new Colon3Node(getPosition(), ((String)yyVals[0+yyTop]));
/* ruby $$ = NEW_CDECL(0, 0, NEW_COLON3($2)); */
}
break;
case 89:
// line 609 "DefaultRubyParser.y"
{
support.backrefAssignError(((Node)yyVals[0+yyTop]));
yyVal = null;
}
break;
case 90:
// line 614 "DefaultRubyParser.y"
{
yyerror("class/module name must be CONSTANT");
}
break;
case 92:
// line 619 "DefaultRubyParser.y"
{
yyVal = new Colon2Node(getPosition(), null, ((String)yyVals[0+yyTop]));
}
break;
case 93:
// line 622 "DefaultRubyParser.y"
{
/* $1 was $$ in ruby?*/
yyVal = new Colon2Node(getPosition(), null, ((String)yyVals[0+yyTop]));
}
break;
case 94:
// line 626 "DefaultRubyParser.y"
{
yyVal = new Colon2Node(getPosition(), ((Node)yyVals[-2+yyTop]), ((String)yyVals[0+yyTop]));
}
break;
case 98:
// line 633 "DefaultRubyParser.y"
{
lexer.setState(LexState.EXPR_END);
yyVal = ((String)yyVals[0+yyTop]);
}
break;
case 99:
// line 637 "DefaultRubyParser.y"
{
lexer.setState(LexState.EXPR_END);
yyVal = yyVals[0+yyTop];
}
break;
case 102:
// line 645 "DefaultRubyParser.y"
{
yyVal = new UndefNode(getPosition(), ((String)yyVals[0+yyTop]));
}
break;
case 103:
// line 648 "DefaultRubyParser.y"
{
lexer.setState(LexState.EXPR_FNAME);
}
break;
case 104:
// line 650 "DefaultRubyParser.y"
{
yyVal = support.appendToBlock(((Node)yyVals[-3+yyTop]), new UndefNode(getPosition(), ((String)yyVals[0+yyTop])));
}
break;
case 105:
// line 654 "DefaultRubyParser.y"
{ yyVal = "|"; }
break;
case 106:
// line 655 "DefaultRubyParser.y"
{ yyVal = "^"; }
break;
case 107:
// line 656 "DefaultRubyParser.y"
{ yyVal = "&"; }
break;
case 108:
// line 657 "DefaultRubyParser.y"
{ yyVal = "<=>"; }
break;
case 109:
// line 658 "DefaultRubyParser.y"
{ yyVal = "=="; }
break;
case 110:
// line 659 "DefaultRubyParser.y"
{ yyVal = "==="; }
break;
case 111:
// line 660 "DefaultRubyParser.y"
{ yyVal = "=~"; }
break;
case 112:
// line 661 "DefaultRubyParser.y"
{ yyVal = ">"; }
break;
case 113:
// line 662 "DefaultRubyParser.y"
{ yyVal = ">="; }
break;
case 114:
// line 663 "DefaultRubyParser.y"
{ yyVal = "<"; }
break;
case 115:
// line 664 "DefaultRubyParser.y"
{ yyVal = "<="; }
break;
case 116:
// line 665 "DefaultRubyParser.y"
{ yyVal = "<<"; }
break;
case 117:
// line 666 "DefaultRubyParser.y"
{ yyVal = ">>"; }
break;
case 118:
// line 667 "DefaultRubyParser.y"
{ yyVal = "+"; }
break;
case 119:
// line 668 "DefaultRubyParser.y"
{ yyVal = "-"; }
break;
case 120:
// line 669 "DefaultRubyParser.y"
{ yyVal = "*"; }
break;
case 121:
// line 670 "DefaultRubyParser.y"
{ yyVal = "*"; }
break;
case 122:
// line 671 "DefaultRubyParser.y"
{ yyVal = "/"; }
break;
case 123:
// line 672 "DefaultRubyParser.y"
{ yyVal = "%"; }
break;
case 124:
// line 673 "DefaultRubyParser.y"
{ yyVal = "**"; }
break;
case 125:
// line 674 "DefaultRubyParser.y"
{ yyVal = "~"; }
break;
case 126:
// line 675 "DefaultRubyParser.y"
{ yyVal = "+@"; }
break;
case 127:
// line 676 "DefaultRubyParser.y"
{ yyVal = "-@"; }
break;
case 128:
// line 677 "DefaultRubyParser.y"
{ yyVal = "[]"; }
break;
case 129:
// line 678 "DefaultRubyParser.y"
{ yyVal = "[]="; }
break;
case 130:
// line 679 "DefaultRubyParser.y"
{ yyVal = "`"; }
break;
case 172:
// line 690 "DefaultRubyParser.y"
{
yyVal = support.node_assign(((Node)yyVals[-2+yyTop]), ((Node)yyVals[0+yyTop]));
}
break;
case 173:
// line 693 "DefaultRubyParser.y"
{
yyVal = support.node_assign(((Node)yyVals[-4+yyTop]), new RescueNode(getPosition(), ((Node)yyVals[-2+yyTop]), new RescueBodyNode(getPosition(), null,((Node)yyVals[0+yyTop]), null), null));
}
break;
case 174:
// line 696 "DefaultRubyParser.y"
{
support.checkExpression(((Node)yyVals[0+yyTop]));
if (yyVals[-2+yyTop] != null) {
String name = ((INameNode)yyVals[-2+yyTop]).getName();
if (((String)yyVals[-1+yyTop]).equals("||")) {
((AssignableNode)yyVals[-2+yyTop]).setValueNode(((Node)yyVals[0+yyTop]));
yyVal = new OpAsgnOrNode(getPosition(), support.gettable(name, getPosition()), ((Node)yyVals[-2+yyTop]));
/* FIXME
if (is_asgn_or_id(vid)) {
$$->nd_aid = vid;
}
*/
} else if (((String)yyVals[-1+yyTop]).equals("&&")) {
((AssignableNode)yyVals[-2+yyTop]).setValueNode(((Node)yyVals[0+yyTop]));
yyVal = new OpAsgnAndNode(getPosition(), support.gettable(name, getPosition()), ((Node)yyVals[-2+yyTop]));
} else {
yyVal = yyVals[-2+yyTop];
if (yyVal != null) {
((AssignableNode)yyVal).setValueNode(support.getOperatorCallNode(support.gettable(name, getPosition()), ((String)yyVals[-1+yyTop]), ((Node)yyVals[0+yyTop])));
}
}
} else {
yyVal = null; /* XXX 0; */
}
}
break;
case 175:
// line 722 "DefaultRubyParser.y"
{
yyVal = new OpElementAsgnNode(getPosition(), ((Node)yyVals[-5+yyTop]), ((String)yyVals[-1+yyTop]), ((Node)yyVals[-3+yyTop]), ((Node)yyVals[0+yyTop]));
}
break;
case 176:
// line 725 "DefaultRubyParser.y"
{
yyVal = new OpAsgnNode(getPosition(), ((Node)yyVals[-4+yyTop]), ((Node)yyVals[0+yyTop]), ((String)yyVals[-2+yyTop]), ((String)yyVals[-1+yyTop]));
}
break;
case 177:
// line 728 "DefaultRubyParser.y"
{
yyVal = new OpAsgnNode(getPosition(), ((Node)yyVals[-4+yyTop]), ((Node)yyVals[0+yyTop]), ((String)yyVals[-2+yyTop]), ((String)yyVals[-1+yyTop]));
}
break;
case 178:
// line 731 "DefaultRubyParser.y"
{
yyVal = new OpAsgnNode(getPosition(), ((Node)yyVals[-4+yyTop]), ((Node)yyVals[0+yyTop]), ((String)yyVals[-2+yyTop]), ((String)yyVals[-1+yyTop]));
}
break;
case 179:
// line 734 "DefaultRubyParser.y"
{
yyerror("constant re-assignment");
yyVal = null;
}
break;
case 180:
// line 738 "DefaultRubyParser.y"
{
yyerror("constant re-assignment");
yyVal = null;
}
break;
case 181:
// line 742 "DefaultRubyParser.y"
{
support.backrefAssignError(((Node)yyVals[-2+yyTop]));
yyVal = null;
}
break;
case 182:
// line 746 "DefaultRubyParser.y"
{
support.checkExpression(((Node)yyVals[-2+yyTop]));
support.checkExpression(((Node)yyVals[0+yyTop]));
yyVal = new DotNode(getPosition(), ((Node)yyVals[-2+yyTop]), ((Node)yyVals[0+yyTop]), false);
}
break;
case 183:
// line 751 "DefaultRubyParser.y"
{
support.checkExpression(((Node)yyVals[-2+yyTop]));
support.checkExpression(((Node)yyVals[0+yyTop]));
yyVal = new DotNode(getPosition(), ((Node)yyVals[-2+yyTop]), ((Node)yyVals[0+yyTop]), true);
}
break;
case 184:
// line 756 "DefaultRubyParser.y"
{
yyVal = support.getOperatorCallNode(((Node)yyVals[-2+yyTop]), "+", ((Node)yyVals[0+yyTop]));
}
break;
case 185:
// line 759 "DefaultRubyParser.y"
{
yyVal = support.getOperatorCallNode(((Node)yyVals[-2+yyTop]), "-", ((Node)yyVals[0+yyTop]));
}
break;
case 186:
// line 762 "DefaultRubyParser.y"
{
yyVal = support.getOperatorCallNode(((Node)yyVals[-2+yyTop]), "*", ((Node)yyVals[0+yyTop]));
}
break;
case 187:
// line 765 "DefaultRubyParser.y"
{
yyVal = support.getOperatorCallNode(((Node)yyVals[-2+yyTop]), "/", ((Node)yyVals[0+yyTop]));
}
break;
case 188:
// line 768 "DefaultRubyParser.y"
{
yyVal = support.getOperatorCallNode(((Node)yyVals[-2+yyTop]), "%", ((Node)yyVals[0+yyTop]));
}
break;
case 189:
// line 771 "DefaultRubyParser.y"
{
yyVal = support.getOperatorCallNode(((Node)yyVals[-2+yyTop]), "**", ((Node)yyVals[0+yyTop]));
/* Covert '- number ** number' to '- (number ** number)'
boolean needNegate = false;
if (($1 instanceof FixnumNode && $<FixnumNode>1.getValue() < 0) ||
($1 instanceof BignumNode && $<BignumNode>1.getValue().compareTo(BigInteger.ZERO) < 0) ||
($1 instanceof FloatNode && $<FloatNode>1.getValue() < 0.0)) {
$<>1 = support.getOperatorCallNode($1, "-@");
needNegate = true;
}
$$ = support.getOperatorCallNode($1, "**", $3);
if (needNegate) {
$$ = support.getOperatorCallNode($<Node>$, "-@");
}
*/
}
break;
case 190:
// line 790 "DefaultRubyParser.y"
{
yyVal = support.getOperatorCallNode(support.getOperatorCallNode((((Number)yyVals[-2+yyTop]) instanceof Long ? (Node) new FixnumNode(getPosition(), ((Long)yyVals[-2+yyTop]).longValue()) : (Node)new BignumNode(getPosition(), ((BigInteger)yyVals[-2+yyTop]))), "**", ((Node)yyVals[0+yyTop])), "-@");
}
break;
case 191:
// line 793 "DefaultRubyParser.y"
{
yyVal = support.getOperatorCallNode(support.getOperatorCallNode(new FloatNode(getPosition(), ((Double)yyVals[-3+yyTop]).doubleValue()), "**", ((Node)yyVals[0+yyTop])), "-@");
}
break;
case 192:
// line 796 "DefaultRubyParser.y"
{
if (((Node)yyVals[0+yyTop]) != null && ((Node)yyVals[0+yyTop]) instanceof ILiteralNode) {
yyVal = ((Node)yyVals[0+yyTop]);
} else {
yyVal = support.getOperatorCallNode(((Node)yyVals[0+yyTop]), "+@");
}
}
break;
case 193:
// line 803 "DefaultRubyParser.y"
{
yyVal = support.getOperatorCallNode(((Node)yyVals[0+yyTop]), "-@");
}
break;
case 194:
// line 806 "DefaultRubyParser.y"
{
yyVal = support.getOperatorCallNode(((Node)yyVals[-2+yyTop]), "|", ((Node)yyVals[0+yyTop]));
}
break;
case 195:
// line 809 "DefaultRubyParser.y"
{
yyVal = support.getOperatorCallNode(((Node)yyVals[-2+yyTop]), "^", ((Node)yyVals[0+yyTop]));
}
break;
case 196:
// line 812 "DefaultRubyParser.y"
{
yyVal = support.getOperatorCallNode(((Node)yyVals[-2+yyTop]), "&", ((Node)yyVals[0+yyTop]));
}
break;
case 197:
// line 815 "DefaultRubyParser.y"
{
yyVal = support.getOperatorCallNode(((Node)yyVals[-2+yyTop]), "<=>", ((Node)yyVals[0+yyTop]));
}
break;
case 198:
// line 818 "DefaultRubyParser.y"
{
yyVal = support.getOperatorCallNode(((Node)yyVals[-2+yyTop]), ">", ((Node)yyVals[0+yyTop]));
}
break;
case 199:
// line 821 "DefaultRubyParser.y"
{
yyVal = support.getOperatorCallNode(((Node)yyVals[-2+yyTop]), ">=", ((Node)yyVals[0+yyTop]));
}
break;
case 200:
// line 824 "DefaultRubyParser.y"
{
yyVal = support.getOperatorCallNode(((Node)yyVals[-2+yyTop]), "<", ((Node)yyVals[0+yyTop]));
}
break;
case 201:
// line 827 "DefaultRubyParser.y"
{
yyVal = support.getOperatorCallNode(((Node)yyVals[-2+yyTop]), "<=", ((Node)yyVals[0+yyTop]));
}
break;
case 202:
// line 830 "DefaultRubyParser.y"
{
yyVal = support.getOperatorCallNode(((Node)yyVals[-2+yyTop]), "==", ((Node)yyVals[0+yyTop]));
}
break;
case 203:
// line 833 "DefaultRubyParser.y"
{
yyVal = support.getOperatorCallNode(((Node)yyVals[-2+yyTop]), "===", ((Node)yyVals[0+yyTop]));
}
break;
case 204:
// line 836 "DefaultRubyParser.y"
{
yyVal = new NotNode(getPosition(), support.getOperatorCallNode(((Node)yyVals[-2+yyTop]), "==", ((Node)yyVals[0+yyTop])));
}
break;
case 205:
// line 839 "DefaultRubyParser.y"
{
yyVal = support.getMatchNode(((Node)yyVals[-2+yyTop]), ((Node)yyVals[0+yyTop]));
}
break;
case 206:
// line 842 "DefaultRubyParser.y"
{
yyVal = new NotNode(getPosition(), support.getMatchNode(((Node)yyVals[-2+yyTop]), ((Node)yyVals[0+yyTop])));
}
break;
case 207:
// line 845 "DefaultRubyParser.y"
{
yyVal = new NotNode(getPosition(), support.getConditionNode(((Node)yyVals[0+yyTop])));
}
break;
case 208:
// line 848 "DefaultRubyParser.y"
{
yyVal = support.getOperatorCallNode(((Node)yyVals[0+yyTop]), "~");
}
break;
case 209:
// line 851 "DefaultRubyParser.y"
{
yyVal = support.getOperatorCallNode(((Node)yyVals[-2+yyTop]), "<<", ((Node)yyVals[0+yyTop]));
}
break;
case 210:
// line 854 "DefaultRubyParser.y"
{
yyVal = support.getOperatorCallNode(((Node)yyVals[-2+yyTop]), ">>", ((Node)yyVals[0+yyTop]));
}
break;
case 211:
// line 857 "DefaultRubyParser.y"
{
yyVal = support.newAndNode(((Node)yyVals[-2+yyTop]), ((Node)yyVals[0+yyTop]));
}
break;
case 212:
// line 860 "DefaultRubyParser.y"
{
yyVal = support.newOrNode(((Node)yyVals[-2+yyTop]), ((Node)yyVals[0+yyTop]));
}
break;
case 213:
// line 863 "DefaultRubyParser.y"
{
support.setInDefined(true);
}
break;
case 214:
// line 865 "DefaultRubyParser.y"
{
support.setInDefined(false);
yyVal = new DefinedNode(getPosition(), ((Node)yyVals[0+yyTop]));
}
break;
case 215:
// line 869 "DefaultRubyParser.y"
{
yyVal = new IfNode(getPosition(), support.getConditionNode(((Node)yyVals[-4+yyTop])), ((Node)yyVals[-2+yyTop]), ((Node)yyVals[0+yyTop]));
}
break;
case 216:
// line 872 "DefaultRubyParser.y"
{
yyVal = ((Node)yyVals[0+yyTop]);
}
break;
case 217:
// line 876 "DefaultRubyParser.y"
{
support.checkExpression(((Node)yyVals[0+yyTop]));
yyVal = ((Node)yyVals[0+yyTop]);
}
break;
case 219:
// line 882 "DefaultRubyParser.y"
{
errorHandler.handleError(IErrors.WARN, null, "parenthesize argument(s) for future version");
yyVal = new ArrayNode(getPosition()).add(((Node)yyVals[-1+yyTop]));
}
break;
case 220:
// line 886 "DefaultRubyParser.y"
{
yyVal = ((ListNode)yyVals[-1+yyTop]);
}
break;
case 221:
// line 889 "DefaultRubyParser.y"
{
support.checkExpression(((Node)yyVals[-1+yyTop]));
yyVal = support.arg_concat(getPosition(), ((ListNode)yyVals[-4+yyTop]), ((Node)yyVals[-1+yyTop]));
}
break;
case 222:
// line 893 "DefaultRubyParser.y"
{
yyVal = new ArrayNode(getPosition()).add(new HashNode(((ListNode)yyVals[-1+yyTop])));
}
break;
case 223:
// line 896 "DefaultRubyParser.y"
{
support.checkExpression(((Node)yyVals[-1+yyTop]));
yyVal = new NewlineNode(getPosition(), new SplatNode(getPosition(), ((Node)yyVals[-1+yyTop])));
}
break;
case 224:
// line 901 "DefaultRubyParser.y"
{
yyVal = ((ListNode)yyVals[-1+yyTop]);
}
break;
case 225:
// line 904 "DefaultRubyParser.y"
{
yyVal = ((Node)yyVals[-2+yyTop]);
}
break;
case 226:
// line 907 "DefaultRubyParser.y"
{
errorHandler.handleError(IErrors.WARN, null, "parenthesize argument(s) for future version");
yyVal = new ArrayNode(getPosition()).add(((Node)yyVals[-2+yyTop]));
}
break;
case 227:
// line 911 "DefaultRubyParser.y"
{
errorHandler.handleError(IErrors.WARN, null, "parenthesize argument(s) for future version");
yyVal = ((ListNode)yyVals[-4+yyTop]).add(((Node)yyVals[-2+yyTop]));
}
break;
case 230:
// line 919 "DefaultRubyParser.y"
{
errorHandler.handleError(IErrors.WARN, null, "parenthesize argument(s) for future version");
yyVal = new ArrayNode(getPosition()).add(((Node)yyVals[0+yyTop]));
}
break;
case 231:
// line 923 "DefaultRubyParser.y"
{
yyVal = support.arg_blk_pass(((ListNode)yyVals[-1+yyTop]), ((BlockPassNode)yyVals[0+yyTop]));
}
break;
case 232:
// line 926 "DefaultRubyParser.y"
{
yyVal = support.arg_concat(getPosition(), ((ListNode)yyVals[-4+yyTop]), ((Node)yyVals[-1+yyTop]));
yyVal = support.arg_blk_pass((Node)yyVal, ((BlockPassNode)yyVals[0+yyTop]));
}
break;
case 233:
// line 930 "DefaultRubyParser.y"
{
yyVal = new ArrayNode(getPosition()).add(new HashNode(((ListNode)yyVals[-1+yyTop])));
yyVal = support.arg_blk_pass((Node)yyVal, ((BlockPassNode)yyVals[0+yyTop]));
}
break;
case 234:
// line 934 "DefaultRubyParser.y"
{
yyVal = support.arg_concat(getPosition(), new ArrayNode(getPosition()).add(new HashNode(((ListNode)yyVals[-4+yyTop]))), ((Node)yyVals[-1+yyTop]));
yyVal = support.arg_blk_pass((Node)yyVal, ((BlockPassNode)yyVals[0+yyTop]));
}
break;
case 235:
// line 938 "DefaultRubyParser.y"
{
yyVal = ((ListNode)yyVals[-3+yyTop]).add(new HashNode(((ListNode)yyVals[-1+yyTop])));
yyVal = support.arg_blk_pass((Node)yyVal, ((BlockPassNode)yyVals[0+yyTop]));
}
break;
case 236:
// line 942 "DefaultRubyParser.y"
{
support.checkExpression(((Node)yyVals[-1+yyTop]));
yyVal = support.arg_concat(getPosition(), ((ListNode)yyVals[-6+yyTop]).add(new HashNode(((ListNode)yyVals[-4+yyTop]))), ((Node)yyVals[-1+yyTop]));
yyVal = support.arg_blk_pass((Node)yyVal, ((BlockPassNode)yyVals[0+yyTop]));
}
break;
case 237:
// line 947 "DefaultRubyParser.y"
{
yyVal = support.arg_blk_pass(new SplatNode(getPosition(), ((Node)yyVals[-1+yyTop])), ((BlockPassNode)yyVals[0+yyTop]));
}
break;
case 238:
// line 950 "DefaultRubyParser.y"
{
}
break;
case 239:
// line 953 "DefaultRubyParser.y"
{
yyVal = support.arg_blk_pass(support.list_concat(new ArrayNode(getPosition()).add(((Node)yyVals[-3+yyTop])), ((ListNode)yyVals[-1+yyTop])), ((BlockPassNode)yyVals[0+yyTop]));
}
break;
case 240:
// line 956 "DefaultRubyParser.y"
{
yyVal = support.arg_blk_pass(new ArrayNode(getPosition()).add(((Node)yyVals[-2+yyTop])), ((BlockPassNode)yyVals[0+yyTop]));
}
break;
case 241:
// line 959 "DefaultRubyParser.y"
{
yyVal = support.arg_concat(getPosition(), new ArrayNode(getPosition()).add(((Node)yyVals[-4+yyTop])), ((Node)yyVals[-1+yyTop]));
yyVal = support.arg_blk_pass((Node)yyVal, ((BlockPassNode)yyVals[0+yyTop]));
}
break;
case 242:
// line 963 "DefaultRubyParser.y"
{
yyVal = support.arg_concat(getPosition(), support.list_concat(new ArrayNode(getPosition()).add(((Node)yyVals[-6+yyTop])), new HashNode(((ListNode)yyVals[-4+yyTop]))), ((Node)yyVals[-1+yyTop]));
yyVal = support.arg_blk_pass((Node)yyVal, ((BlockPassNode)yyVals[0+yyTop]));
}
break;
case 243:
// line 967 "DefaultRubyParser.y"
{
yyVal = new ArrayNode(getPosition()).add(new HashNode(((ListNode)yyVals[-1+yyTop])));
yyVal = support.arg_blk_pass((Node)yyVal, ((BlockPassNode)yyVals[0+yyTop]));
}
break;
case 244:
// line 971 "DefaultRubyParser.y"
{
yyVal = support.arg_concat(getPosition(), new ArrayNode(getPosition()).add(new HashNode(((ListNode)yyVals[-4+yyTop]))), ((Node)yyVals[-1+yyTop]));
yyVal = support.arg_blk_pass((Node)yyVal, ((BlockPassNode)yyVals[0+yyTop]));
}
break;
case 245:
// line 975 "DefaultRubyParser.y"
{
yyVal = new ArrayNode(getPosition()).add(((Node)yyVals[-3+yyTop])).add(new HashNode(((ListNode)yyVals[-1+yyTop])));
yyVal = support.arg_blk_pass((Node)yyVal, ((BlockPassNode)yyVals[0+yyTop]));
}
break;
case 246:
// line 979 "DefaultRubyParser.y"
{
yyVal = support.list_concat(new ArrayNode(getPosition()).add(((Node)yyVals[-5+yyTop])), ((ListNode)yyVals[-3+yyTop])).add(new HashNode(((ListNode)yyVals[-1+yyTop])));
yyVal = support.arg_blk_pass((Node)yyVal, ((BlockPassNode)yyVals[0+yyTop]));
}
break;
case 247:
// line 983 "DefaultRubyParser.y"
{
yyVal = support.arg_concat(getPosition(), new ArrayNode(getPosition()).add(((Node)yyVals[-6+yyTop])).add(new HashNode(((ListNode)yyVals[-4+yyTop]))), ((Node)yyVals[-1+yyTop]));
yyVal = support.arg_blk_pass((Node)yyVal, ((BlockPassNode)yyVals[0+yyTop]));
}
break;
case 248:
// line 987 "DefaultRubyParser.y"
{
yyVal = support.arg_concat(getPosition(), support.list_concat(new ArrayNode(getPosition()).add(((Node)yyVals[-8+yyTop])), ((ListNode)yyVals[-6+yyTop])).add(new HashNode(((ListNode)yyVals[-4+yyTop]))), ((Node)yyVals[-1+yyTop]));
yyVal = support.arg_blk_pass((Node)yyVal, ((BlockPassNode)yyVals[0+yyTop]));
}
break;
case 249:
// line 991 "DefaultRubyParser.y"
{
yyVal = support.arg_blk_pass(new SplatNode(getPosition(), ((Node)yyVals[-1+yyTop])), ((BlockPassNode)yyVals[0+yyTop]));
}
break;
case 250:
// line 994 "DefaultRubyParser.y"
{}
break;
case 251:
// line 996 "DefaultRubyParser.y"
{
yyVal = new Long(lexer.getCmdArgumentState().begin());
}
break;
case 252:
// line 998 "DefaultRubyParser.y"
{
lexer.getCmdArgumentState().reset(((Long)yyVals[-1+yyTop]).longValue());
yyVal = ((Node)yyVals[0+yyTop]);
}
break;
case 254:
// line 1004 "DefaultRubyParser.y"
{
lexer.setState(LexState.EXPR_ENDARG);
}
break;
case 255:
// line 1006 "DefaultRubyParser.y"
{
errorHandler.handleError(IErrors.WARN, null, "don't put space before argument parentheses");
yyVal = null;
}
break;
case 256:
// line 1010 "DefaultRubyParser.y"
{
lexer.setState(LexState.EXPR_ENDARG);
}
break;
case 257:
// line 1012 "DefaultRubyParser.y"
{
errorHandler.handleError(IErrors.WARN, null, "don't put space before argument parentheses");
yyVal = ((Node)yyVals[-2+yyTop]);
}
break;
case 258:
// line 1017 "DefaultRubyParser.y"
{
support.checkExpression(((Node)yyVals[0+yyTop]));
yyVal = new BlockPassNode(getPosition(), ((Node)yyVals[0+yyTop]));
}
break;
case 259:
// line 1022 "DefaultRubyParser.y"
{
yyVal = ((BlockPassNode)yyVals[0+yyTop]);
}
break;
case 261:
// line 1027 "DefaultRubyParser.y"
{
yyVal = new ArrayNode(getPosition()).add(((Node)yyVals[0+yyTop]));
}
break;
case 262:
// line 1030 "DefaultRubyParser.y"
{
yyVal = ((ListNode)yyVals[-2+yyTop]).add(((Node)yyVals[0+yyTop]));
}
break;
case 263:
// line 1034 "DefaultRubyParser.y"
{
yyVal = ((ListNode)yyVals[-2+yyTop]).add(((Node)yyVals[0+yyTop]));
}
break;
case 264:
// line 1037 "DefaultRubyParser.y"
{
yyVal = support.arg_concat(getPosition(), ((ListNode)yyVals[-3+yyTop]), ((Node)yyVals[0+yyTop]));
}
break;
case 265:
// line 1040 "DefaultRubyParser.y"
{
yyVal = new SplatNode(getPosition(), ((Node)yyVals[0+yyTop]));
}
break;
case 274:
// line 1052 "DefaultRubyParser.y"
{
yyVal = new VCallNode(getPosition(), ((String)yyVals[0+yyTop]));
}
break;
case 275:
// line 1056 "DefaultRubyParser.y"
{
yyVal = new BeginNode(getPosition(), ((Node)yyVals[-1+yyTop]));
}
break;
case 276:
// line 1059 "DefaultRubyParser.y"
{
lexer.setState(LexState.EXPR_ENDARG);
errorHandler.handleError(IErrors.WARN, null, "(...) interpreted as grouped expression");
yyVal = ((Node)yyVals[-2+yyTop]);
}
break;
case 277:
// line 1064 "DefaultRubyParser.y"
{
yyVal = ((Node)yyVals[-1+yyTop]);
}
break;
case 278:
// line 1067 "DefaultRubyParser.y"
{
yyVal = new Colon2Node(getPosition(), ((Node)yyVals[-2+yyTop]), ((String)yyVals[0+yyTop]));
}
break;
case 279:
// line 1070 "DefaultRubyParser.y"
{
yyVal = new Colon3Node(getPosition(), ((String)yyVals[0+yyTop]));
}
break;
case 280:
// line 1073 "DefaultRubyParser.y"
{
yyVal = new CallNode(getPosition(), ((Node)yyVals[-3+yyTop]), "[]", ((Node)yyVals[-1+yyTop]));
}
break;
case 281:
// line 1076 "DefaultRubyParser.y"
{
if (((Node)yyVals[-1+yyTop]) == null) {
yyVal = new ZArrayNode(getPosition()); /* zero length array*/
} else {
yyVal = ((Node)yyVals[-1+yyTop]);
}
}
break;
case 282:
// line 1083 "DefaultRubyParser.y"
{
yyVal = new HashNode(getPosition(), ((ListNode)yyVals[-1+yyTop]));
}
break;
case 283:
// line 1086 "DefaultRubyParser.y"
{
yyVal = new ReturnNode(getPosition(), null);
}
break;
case 284:
// line 1089 "DefaultRubyParser.y"
{
yyVal = support.new_yield(getPosition(), ((Node)yyVals[-1+yyTop]));
}
break;
case 285:
// line 1092 "DefaultRubyParser.y"
{
yyVal = new YieldNode(getPosition(), null, false);
}
break;
case 286:
// line 1095 "DefaultRubyParser.y"
{
yyVal = new YieldNode(getPosition(), null, false);
}
break;
case 287:
// line 1098 "DefaultRubyParser.y"
{
support.setInDefined(true);
}
break;
case 288:
// line 1100 "DefaultRubyParser.y"
{
support.setInDefined(false);
yyVal = new DefinedNode(getPosition(), ((Node)yyVals[-1+yyTop]));
}
break;
case 289:
// line 1104 "DefaultRubyParser.y"
{
((IterNode)yyVals[0+yyTop]).setIterNode(new FCallNode(getPosition(), ((String)yyVals[-1+yyTop]), null));
yyVal = ((IterNode)yyVals[0+yyTop]);
}
break;
case 291:
// line 1109 "DefaultRubyParser.y"
{
if (((Node)yyVals[-1+yyTop]) != null && ((Node)yyVals[-1+yyTop]) instanceof BlockPassNode) {
errorHandler.handleError(IErrors.COMPILE_ERROR, null, "Both block arg and actual block given.");
}
((IterNode)yyVals[0+yyTop]).setIterNode(((Node)yyVals[-1+yyTop]));
yyVal = ((IterNode)yyVals[0+yyTop]);
}
break;
case 292:
// line 1116 "DefaultRubyParser.y"
{
yyVal = new IfNode(getPosition(), support.getConditionNode(((Node)yyVals[-4+yyTop])), ((Node)yyVals[-2+yyTop]), ((Node)yyVals[-1+yyTop]));
/* missing from ruby
if (cond_negative(&$$->nd_cond)) {
NODE *tmp = $$->nd_body;
$$->nd_body = $$->nd_else;
$$->nd_else = tmp;
} */
}
break;
case 293:
// line 1125 "DefaultRubyParser.y"
{
yyVal = new IfNode(getPosition(), support.getConditionNode(((Node)yyVals[-4+yyTop])), ((Node)yyVals[-1+yyTop]), ((Node)yyVals[-2+yyTop]));
/* missing from ruby
if (cond_negative(&$$->nd_cond)) {
NODE *tmp = $$->nd_body;
$$->nd_body = $$->nd_else;
$$->nd_else = tmp;
} */
}
break;
case 294:
// line 1134 "DefaultRubyParser.y"
{
lexer.getConditionState().begin();
}
break;
case 295:
// line 1136 "DefaultRubyParser.y"
{
lexer.getConditionState().end();
}
break;
case 296:
// line 1138 "DefaultRubyParser.y"
{
yyVal = new WhileNode(getPosition(), support.getConditionNode(((Node)yyVals[-4+yyTop])), ((Node)yyVals[-1+yyTop]));
/* missing from ruby
if (cond_negative(&$$->nd_cond)) {
nd_set_type($$, NODE_UNTIL);
} */
}
break;
case 297:
// line 1145 "DefaultRubyParser.y"
{
lexer.getConditionState().begin();
}
break;
case 298:
// line 1147 "DefaultRubyParser.y"
{
lexer.getConditionState().end();
}
break;
case 299:
// line 1149 "DefaultRubyParser.y"
{
yyVal = new UntilNode(getPosition(), support.getConditionNode(((Node)yyVals[-4+yyTop])), ((Node)yyVals[-1+yyTop]));
/* missing from ruby
if (cond_negative(&$$->nd_cond)) {
nd_set_type($$, NODE_WHILE);
} */
}
break;
case 300:
// line 1158 "DefaultRubyParser.y"
{
yyVal = new CaseNode(getPosition(), ((Node)yyVals[-3+yyTop]), ((Node)yyVals[-1+yyTop])); /* XXX*/
}
break;
case 301:
// line 1161 "DefaultRubyParser.y"
{
yyVal = new CaseNode(getPosition(), null, ((Node)yyVals[-1+yyTop]));
}
break;
case 302:
// line 1164 "DefaultRubyParser.y"
{
yyVal = ((Node)yyVals[-1+yyTop]);
}
break;
case 303:
// line 1167 "DefaultRubyParser.y"
{
lexer.getConditionState().begin();
}
break;
case 304:
// line 1169 "DefaultRubyParser.y"
{
lexer.getConditionState().end();
}
break;
case 305:
// line 1172 "DefaultRubyParser.y"
{
yyVal = new ForNode(getPosition(), ((Node)yyVals[-7+yyTop]), ((Node)yyVals[-1+yyTop]), ((Node)yyVals[-4+yyTop]));
}
break;
case 306:
// line 1175 "DefaultRubyParser.y"
{
if (support.isInDef() || support.isInSingle()) {
yyerror("class definition in method body");
}
support.setClassNest(support.getClassNest() + 1);
support.getLocalNames().push();
/* $$ = new Integer(ruby.getSourceLine());*/
}
break;
case 307:
// line 1183 "DefaultRubyParser.y"
{
yyVal = new ClassNode(getPosition(), ((Colon2Node)yyVals[-4+yyTop]).getName(), new ScopeNode(support.getLocalNames().getNames(), ((Node)yyVals[-1+yyTop])), ((Node)yyVals[-3+yyTop]));
/* $<Node>$.setLine($<Integer>4.intValue());*/
support.getLocalNames().pop();
support.setClassNest(support.getClassNest() - 1);
}
break;
case 308:
// line 1189 "DefaultRubyParser.y"
{
yyVal = new Boolean(support.isInDef());
support.setInDef(false);
}
break;
case 309:
// line 1192 "DefaultRubyParser.y"
{
yyVal = new Integer(support.getInSingle());
support.setInSingle(0);
support.setClassNest(support.getClassNest() + 1);
support.getLocalNames().push();
}
break;
case 310:
// line 1198 "DefaultRubyParser.y"
{
yyVal = new SClassNode(getPosition(), ((Node)yyVals[-5+yyTop]), new ScopeNode(support.getLocalNames().getNames(), ((Node)yyVals[-1+yyTop])));
support.getLocalNames().pop();
support.setClassNest(support.getClassNest() - 1);
support.setInDef(((Boolean)yyVals[-4+yyTop]).booleanValue());
support.setInSingle(((Integer)yyVals[-2+yyTop]).intValue());
}
break;
case 311:
// line 1205 "DefaultRubyParser.y"
{
if (support.isInDef() || support.isInSingle()) {
yyerror("module definition in method body");
}
support.setClassNest(support.getClassNest() + 1);
support.getLocalNames().push();
/* $$ = new Integer(ruby.getSourceLine());*/
}
break;
case 312:
// line 1213 "DefaultRubyParser.y"
{
yyVal = new ModuleNode(getPosition(), ((Colon2Node)yyVals[-3+yyTop]).getName(), new ScopeNode(support.getLocalNames().getNames(), ((Node)yyVals[-1+yyTop])));
/* $<Node>$.setLine($<Integer>3.intValue());*/
support.getLocalNames().pop();
support.setClassNest(support.getClassNest() - 1);
}
break;
case 313:
// line 1219 "DefaultRubyParser.y"
{
/* missing
$<id>$ = cur_mid;
cur_mid = $2; */
support.setInDef(true);
support.getLocalNames().push();
}
break;
case 314:
// line 1227 "DefaultRubyParser.y"
{
/* was in old jruby grammar support.getClassNest() !=0 || IdUtil.isAttrSet($2) ? Visibility.PUBLIC : Visibility.PRIVATE); */
/* NOEX_PRIVATE for toplevel */
yyVal = new DefnNode(getPosition(), ((String)yyVals[-4+yyTop]), ((Node)yyVals[-2+yyTop]),
new ScopeNode(support.getLocalNames().getNames(), ((Node)yyVals[-1+yyTop])), Visibility.PRIVATE);
/* $<Node>$.setPosFrom($4);*/
support.getLocalNames().pop();
support.setInDef(false);
/* missing cur_mid = $<id>3; */
}
break;
case 315:
// line 1237 "DefaultRubyParser.y"
{
lexer.setState(LexState.EXPR_FNAME);
}
break;
case 316:
// line 1239 "DefaultRubyParser.y"
{
support.setInSingle(support.getInSingle() + 1);
support.getLocalNames().push();
lexer.setState(LexState.EXPR_END); /* force for args */
}
break;
case 317:
// line 1245 "DefaultRubyParser.y"
{
yyVal = new DefsNode(getPosition(), ((Node)yyVals[-7+yyTop]), ((String)yyVals[-4+yyTop]), ((Node)yyVals[-2+yyTop]), new ScopeNode(support.getLocalNames().getNames(), ((Node)yyVals[-1+yyTop])));
/* $<Node>$.setPosFrom($2);*/
support.getLocalNames().pop();
support.setInSingle(support.getInSingle() - 1);
}
break;
case 318:
// line 1251 "DefaultRubyParser.y"
{
yyVal = new BreakNode(getPosition());
}
break;
case 319:
// line 1254 "DefaultRubyParser.y"
{
yyVal = new NextNode(getPosition());
}
break;
case 320:
// line 1257 "DefaultRubyParser.y"
{
yyVal = new RedoNode(getPosition());
}
break;
case 321:
// line 1260 "DefaultRubyParser.y"
{
yyVal = new RetryNode(getPosition());
}
break;
case 322:
// line 1264 "DefaultRubyParser.y"
{
support.checkExpression(((Node)yyVals[0+yyTop]));
yyVal = ((Node)yyVals[0+yyTop]);
}
break;
case 331:
// line 1281 "DefaultRubyParser.y"
{
yyVal = new IfNode(getPosition(), support.getConditionNode(((Node)yyVals[-3+yyTop])), ((Node)yyVals[-1+yyTop]), ((Node)yyVals[0+yyTop]));
}
break;
case 333:
// line 1286 "DefaultRubyParser.y"
{
yyVal = ((Node)yyVals[0+yyTop]);
}
break;
case 335:
// line 1291 "DefaultRubyParser.y"
{}
break;
case 337:
// line 1294 "DefaultRubyParser.y"
{
yyVal = new ZeroArgNode();
}
break;
case 338:
// line 1297 "DefaultRubyParser.y"
{
yyVal = new ZeroArgNode();
}
break;
case 339:
// line 1300 "DefaultRubyParser.y"
{
yyVal = ((Node)yyVals[-1+yyTop]);
}
break;
case 340:
// line 1304 "DefaultRubyParser.y"
{
support.getBlockNames().push();
}
break;
case 341:
// line 1307 "DefaultRubyParser.y"
{
yyVal = new IterNode(getPosition(), ((Node)yyVals[-2+yyTop]), ((Node)yyVals[-1+yyTop]), null);
support.getBlockNames().pop();
}
break;
case 342:
// line 1312 "DefaultRubyParser.y"
{
if (((Node)yyVals[-1+yyTop]) instanceof BlockPassNode) {
errorHandler.handleError(IErrors.COMPILE_ERROR, null, "Both block arg and actual block given.");
}
((IterNode)yyVals[0+yyTop]).setIterNode(((Node)yyVals[-1+yyTop]));
yyVal = ((IterNode)yyVals[0+yyTop]);
}
break;
case 343:
// line 1319 "DefaultRubyParser.y"
{
yyVal = support.new_call(((Node)yyVals[-3+yyTop]), ((String)yyVals[-1+yyTop]), ((Node)yyVals[0+yyTop]));
}
break;
case 344:
// line 1322 "DefaultRubyParser.y"
{
yyVal = support.new_call(((Node)yyVals[-3+yyTop]), ((String)yyVals[-1+yyTop]), ((Node)yyVals[0+yyTop]));
}
break;
case 345:
// line 1326 "DefaultRubyParser.y"
{
yyVal = support.new_fcall(((String)yyVals[-1+yyTop]), ((Node)yyVals[0+yyTop]), getPosition()); /* .setPosFrom($2);*/
}
break;
case 346:
// line 1329 "DefaultRubyParser.y"
{
yyVal = support.new_call(((Node)yyVals[-3+yyTop]), ((String)yyVals[-1+yyTop]), ((Node)yyVals[0+yyTop])); /*.setPosFrom($1);*/
}
break;
case 347:
// line 1332 "DefaultRubyParser.y"
{
yyVal = support.new_call(((Node)yyVals[-3+yyTop]), ((String)yyVals[-1+yyTop]), ((Node)yyVals[0+yyTop])); /*.setPosFrom($1);*/
}
break;
case 348:
// line 1335 "DefaultRubyParser.y"
{
yyVal = support.new_call(((Node)yyVals[-2+yyTop]), ((String)yyVals[0+yyTop]), null);
}
break;
case 349:
// line 1338 "DefaultRubyParser.y"
{
yyVal = support.new_super(((Node)yyVals[0+yyTop]), getPosition());
}
break;
case 350:
// line 1341 "DefaultRubyParser.y"
{
yyVal = new ZSuperNode(getPosition());
}
break;
case 351:
// line 1345 "DefaultRubyParser.y"
{
support.getBlockNames().push();
}
break;
case 352:
// line 1347 "DefaultRubyParser.y"
{
yyVal = new IterNode(getPosition(), ((Node)yyVals[-2+yyTop]), ((Node)yyVals[-1+yyTop]), null);
support.getBlockNames().pop();
}
break;
case 353:
// line 1351 "DefaultRubyParser.y"
{
support.getBlockNames().push();
}
break;
case 354:
// line 1353 "DefaultRubyParser.y"
{
yyVal = new IterNode(getPosition(), ((Node)yyVals[-2+yyTop]), ((Node)yyVals[-1+yyTop]), null);
support.getBlockNames().pop();
}
break;
case 355:
// line 1360 "DefaultRubyParser.y"
{
yyVal = new WhenNode(getPosition(), ((ListNode)yyVals[-3+yyTop]), ((Node)yyVals[-1+yyTop]), ((Node)yyVals[0+yyTop]));
}
break;
case 357:
// line 1365 "DefaultRubyParser.y"
{
yyVal = ((ListNode)yyVals[-3+yyTop]).add(new WhenNode(getPosition(), new ArrayNode(getPosition()).add(((Node)yyVals[0+yyTop])), null, null));
}
break;
case 358:
// line 1368 "DefaultRubyParser.y"
{
yyVal = new ArrayNode(getPosition()).add(new WhenNode(getPosition(), new ArrayNode(getPosition()).add(((Node)yyVals[0+yyTop])), null, null));
}
break;
case 361:
// line 1378 "DefaultRubyParser.y"
{
Node node;
if (((Node)yyVals[-3+yyTop]) != null) {
node = support.appendToBlock(support.node_assign(((Node)yyVals[-3+yyTop]), new GlobalVarNode(getPosition(), "$!")), ((Node)yyVals[-1+yyTop]));
} else {
node = ((Node)yyVals[-1+yyTop]);
}
yyVal = new RescueBodyNode(getPosition(), ((Node)yyVals[-4+yyTop]), node, ((RescueBodyNode)yyVals[0+yyTop]));
}
break;
case 362:
// line 1387 "DefaultRubyParser.y"
{yyVal = null;}
break;
case 363:
// line 1389 "DefaultRubyParser.y"
{
yyVal = new ArrayNode(getPosition()).add(((Node)yyVals[0+yyTop]));
}
break;
case 366:
// line 1395 "DefaultRubyParser.y"
{
yyVal = ((Node)yyVals[0+yyTop]);
}
break;
case 368:
// line 1400 "DefaultRubyParser.y"
{
if (((Node)yyVals[0+yyTop]) != null) {
yyVal = ((Node)yyVals[0+yyTop]);
} else {
yyVal = new NilNode(null);
}
}
break;
case 371:
// line 1410 "DefaultRubyParser.y"
{
yyVal = new SymbolNode(getPosition(), ((String)yyVals[0+yyTop]));
}
break;
case 373:
// line 1415 "DefaultRubyParser.y"
{
if (((Node)yyVals[0+yyTop]) == null) {
yyVal = new StrNode(getPosition(), "");
} else {
if (((Node)yyVals[0+yyTop]) instanceof EvStrNode) {
yyVal = new DStrNode(getPosition()).add(((Node)yyVals[0+yyTop]));
} else {
yyVal = ((Node)yyVals[0+yyTop]);
}
}
}
break;
case 375:
// line 1428 "DefaultRubyParser.y"
{
yyVal = support.literal_concat(getPosition(), ((Node)yyVals[-1+yyTop]), ((Node)yyVals[0+yyTop]));
}
break;
case 376:
// line 1432 "DefaultRubyParser.y"
{
yyVal = ((Node)yyVals[-1+yyTop]);
}
break;
case 377:
// line 1436 "DefaultRubyParser.y"
{
if (((Node)yyVals[-1+yyTop]) == null) {
yyVal = new XStrNode(getPosition(), null);
} else {
if (((Node)yyVals[-1+yyTop]) instanceof StrNode) {
yyVal = new XStrNode(getPosition(), ((StrNode)yyVals[-1+yyTop]).getValue());
} else if (((Node)yyVals[-1+yyTop]) instanceof DStrNode) {
yyVal = new DXStrNode(getPosition()).add(((Node)yyVals[-1+yyTop]));
} else {
yyVal = new DXStrNode(getPosition()).add(new ArrayNode(getPosition()).add(((Node)yyVals[-1+yyTop])));
}
}
}
break;
case 378:
// line 1450 "DefaultRubyParser.y"
{
int options = ((RegexpNode)yyVals[0+yyTop]).getOptions();
Node node = ((Node)yyVals[-1+yyTop]);
if (node == null) {
yyVal = new RegexpNode(getPosition(), "", options & ~ReOptions.RE_OPTION_ONCE);
} else if (node instanceof StrNode) {
yyVal = new RegexpNode(getPosition(), ((StrNode) node).getValue(), options & ~ReOptions.RE_OPTION_ONCE);
} else {
if (node instanceof DStrNode == false) {
node = new DStrNode(getPosition()).add(new ArrayNode(getPosition()).add(node));
}
yyVal = new DRegexpNode(getPosition(), options, (options & ReOptions.RE_OPTION_ONCE) != 0).add(node);
}
}
break;
case 379:
// line 1467 "DefaultRubyParser.y"
{
yyVal = new ZArrayNode(getPosition());
}
break;
case 380:
// line 1470 "DefaultRubyParser.y"
{
yyVal = ((ListNode)yyVals[-1+yyTop]);
}
break;
case 381:
// line 1474 "DefaultRubyParser.y"
{
yyVal = null;
}
break;
case 382:
// line 1477 "DefaultRubyParser.y"
{
Node node = ((Node)yyVals[-1+yyTop]);
if (node instanceof EvStrNode) {
node = new DStrNode(getPosition()).add(node);
}
yyVal = ((ListNode)yyVals[-2+yyTop]).add(node);
}
break;
case 384:
// line 1488 "DefaultRubyParser.y"
{
yyVal = support.literal_concat(getPosition(), ((Node)yyVals[-1+yyTop]), ((Node)yyVals[0+yyTop]));
}
break;
case 385:
// line 1492 "DefaultRubyParser.y"
{
yyVal = new ZArrayNode(getPosition());
}
break;
case 386:
// line 1495 "DefaultRubyParser.y"
{
yyVal = ((ListNode)yyVals[-1+yyTop]);
}
break;
case 387:
// line 1499 "DefaultRubyParser.y"
{
yyVal = null;
}
break;
case 388:
// line 1502 "DefaultRubyParser.y"
{
if (((ListNode)yyVals[-2+yyTop]) == null) {
yyVal = new ArrayNode(getPosition()).add(new StrNode(getPosition(), ((String)yyVals[-1+yyTop])));
} else {
yyVal = ((ListNode)yyVals[-2+yyTop]).add(new StrNode(getPosition(), ((String)yyVals[-1+yyTop])));
}
}
break;
case 389:
// line 1510 "DefaultRubyParser.y"
{
yyVal = null;
}
break;
case 390:
// line 1513 "DefaultRubyParser.y"
{
yyVal = support.literal_concat(getPosition(), ((Node)yyVals[-1+yyTop]), ((Node)yyVals[0+yyTop]));
}
break;
case 391:
// line 1517 "DefaultRubyParser.y"
{
yyVal = null;
}
break;
case 392:
// line 1520 "DefaultRubyParser.y"
{
yyVal = support.literal_concat(getPosition(), ((Node)yyVals[-1+yyTop]), ((Node)yyVals[0+yyTop]));
}
break;
case 393:
// line 1525 "DefaultRubyParser.y"
{
yyVal = new StrNode(getPosition(), ((String)yyVal));
}
break;
case 394:
// line 1528 "DefaultRubyParser.y"
{
yyVal = lexer.strTerm();
lexer.setStrTerm(null);
lexer.setState(LexState.EXPR_BEG);
}
break;
case 395:
// line 1532 "DefaultRubyParser.y"
{
lexer.setStrTerm(((Node)yyVals[-1+yyTop]));
yyVal = new EvStrNode(getPosition(), ((Node)yyVals[0+yyTop]));
}
break;
case 396:
// line 1536 "DefaultRubyParser.y"
{
yyVal = lexer.strTerm();
lexer.setStrTerm(null);
lexer.setState(LexState.EXPR_BEG);
}
break;
case 397:
// line 1540 "DefaultRubyParser.y"
{
lexer.setStrTerm(((Node)yyVals[-2+yyTop]));
Node node = ((Node)yyVals[-1+yyTop]);
if (node instanceof NewlineNode) {
node = ((NewlineNode)node).getNextNode();
}
yyVal = support.newEvStrNode(getPosition(), node);
}
break;
case 398:
// line 1551 "DefaultRubyParser.y"
{
yyVal = new GlobalVarNode(getPosition(), ((String)yyVals[0+yyTop]));
}
break;
case 399:
// line 1554 "DefaultRubyParser.y"
{
yyVal = new InstVarNode(getPosition(), ((String)yyVals[0+yyTop]));
}
break;
case 400:
// line 1557 "DefaultRubyParser.y"
{
yyVal = new ClassVarNode(getPosition(), ((String)yyVals[0+yyTop]));
}
break;
case 402:
// line 1563 "DefaultRubyParser.y"
{
lexer.setState(LexState.EXPR_END);
yyVal = ((String)yyVals[0+yyTop]);
}
break;
case 407:
// line 1573 "DefaultRubyParser.y"
{
lexer.setState(LexState.EXPR_END);
/* In ruby, it seems to be possible to get a*/
/* StrNode (NODE_STR) among other node type. This */
/* is not possible for us. We will always have a */
/* DStrNode (NODE_DSTR).*/
yyVal = new DSymbolNode(getPosition(), ((DStrNode)yyVals[-1+yyTop]));
}
break;
case 408:
// line 1583 "DefaultRubyParser.y"
{
if (((Number)yyVals[0+yyTop]) instanceof Long) {
yyVal = new FixnumNode(getPosition(), ((Long)yyVals[0+yyTop]).longValue());
} else {
yyVal = new BignumNode(getPosition(), ((BigInteger)yyVals[0+yyTop]));
}
}
break;
case 409:
// line 1590 "DefaultRubyParser.y"
{
yyVal = new FloatNode(getPosition(), ((Double)yyVals[0+yyTop]).doubleValue());
}
break;
case 410:
// line 1593 "DefaultRubyParser.y"
{
yyVal = support.getOperatorCallNode((((Number)yyVals[0+yyTop]) instanceof Long ? (Node) new FixnumNode(getPosition(), ((Long)yyVals[0+yyTop]).longValue()) : (Node) new BignumNode(getPosition(), ((BigInteger)yyVals[0+yyTop]))), "-@");
}
break;
case 411:
// line 1596 "DefaultRubyParser.y"
{
yyVal = support.getOperatorCallNode(new FloatNode(getPosition(), ((Double)yyVals[0+yyTop]).doubleValue()), "-@");
}
break;
case 412:
// line 1605 "DefaultRubyParser.y"
{
yyVal = ((String)yyVals[0+yyTop]);
}
break;
case 413:
// line 1608 "DefaultRubyParser.y"
{
yyVal = ((String)yyVals[0+yyTop]);
}
break;
case 414:
// line 1611 "DefaultRubyParser.y"
{
yyVal = ((String)yyVals[0+yyTop]);
}
break;
case 415:
// line 1614 "DefaultRubyParser.y"
{
yyVal = ((String)yyVals[0+yyTop]);
}
break;
case 416:
// line 1617 "DefaultRubyParser.y"
{
yyVal = ((String)yyVals[0+yyTop]);
}
break;
case 417:
// line 1620 "DefaultRubyParser.y"
{
yyVal = new NilNode(getPosition());
}
break;
case 418:
// line 1623 "DefaultRubyParser.y"
{
yyVal = new SelfNode(getPosition());
}
break;
case 419:
// line 1626 "DefaultRubyParser.y"
{
yyVal = new TrueNode(getPosition());
}
break;
case 420:
// line 1629 "DefaultRubyParser.y"
{
yyVal = new FalseNode(getPosition());
}
break;
case 421:
// line 1632 "DefaultRubyParser.y"
{
yyVal = new StrNode(getPosition(), getPosition().getFile());
}
break;
case 422:
// line 1635 "DefaultRubyParser.y"
{
yyVal = new FixnumNode(getPosition(), getPosition().getLine());
}
break;
case 423:
// line 1639 "DefaultRubyParser.y"
{
/* Work around __LINE__ and __FILE__ */
if (yyVals[0+yyTop] instanceof INameNode) {
String name = ((INameNode)yyVals[0+yyTop]).getName();
yyVal = support.gettable(name, getPosition());
} else if (yyVals[0+yyTop] instanceof String) {
yyVal = support.gettable(((String)yyVals[0+yyTop]), getPosition());
} else {
yyVal = yyVals[0+yyTop];
}
}
break;
case 424:
// line 1652 "DefaultRubyParser.y"
{
yyVal = support.assignable(getPosition(), yyVals[0+yyTop], null);
}
break;
case 427:
// line 1659 "DefaultRubyParser.y"
{
yyVal = null;
}
break;
case 428:
// line 1662 "DefaultRubyParser.y"
{
lexer.setState(LexState.EXPR_BEG);
}
break;
case 429:
// line 1664 "DefaultRubyParser.y"
{
yyVal = ((Node)yyVals[-1+yyTop]);
}
break;
case 430:
// line 1667 "DefaultRubyParser.y"
{
yyerrok();
yyVal = null;
}
break;
case 431:
// line 1672 "DefaultRubyParser.y"
{
yyVal = ((Node)yyVals[-2+yyTop]);
lexer.setState(LexState.EXPR_BEG);
}
break;
case 432:
// line 1676 "DefaultRubyParser.y"
{
yyVal = ((Node)yyVals[-1+yyTop]);
}
break;
case 433:
// line 1680 "DefaultRubyParser.y"
{
yyVal = new ArgsNode(getPosition(), ((Integer)yyVals[-5+yyTop]).intValue(), ((ListNode)yyVals[-3+yyTop]), ((Integer)yyVals[-1+yyTop]).intValue(), ((BlockArgNode)yyVals[0+yyTop]));
}
break;
case 434:
// line 1683 "DefaultRubyParser.y"
{
yyVal = new ArgsNode(getPosition(), ((Integer)yyVals[-3+yyTop]).intValue(), ((ListNode)yyVals[-1+yyTop]), -1, ((BlockArgNode)yyVals[0+yyTop]));
}
break;
case 435:
// line 1686 "DefaultRubyParser.y"
{
yyVal = new ArgsNode(getPosition(), ((Integer)yyVals[-3+yyTop]).intValue(), null, ((Integer)yyVals[-1+yyTop]).intValue(), ((BlockArgNode)yyVals[0+yyTop]));
}
break;
case 436:
// line 1689 "DefaultRubyParser.y"
{
int h = ((Integer)yyVals[-1+yyTop]).intValue();
yyVal = new ArgsNode(getPosition(), h, null, -1, ((BlockArgNode)yyVals[0+yyTop]));
}
break;
case 437:
// line 1692 "DefaultRubyParser.y"
{
yyVal = new ArgsNode(getPosition(), 0, ((ListNode)yyVals[-3+yyTop]), ((Integer)yyVals[-1+yyTop]).intValue(), ((BlockArgNode)yyVals[0+yyTop]));
}
break;
case 438:
// line 1695 "DefaultRubyParser.y"
{
yyVal = new ArgsNode(getPosition(), 0, ((ListNode)yyVals[-1+yyTop]), -1, ((BlockArgNode)yyVals[0+yyTop]));
}
break;
case 439:
// line 1698 "DefaultRubyParser.y"
{
yyVal = new ArgsNode(getPosition(), 0, null, ((Integer)yyVals[-1+yyTop]).intValue(), ((BlockArgNode)yyVals[0+yyTop]));
}
break;
case 440:
// line 1701 "DefaultRubyParser.y"
{
yyVal = new ArgsNode(getPosition(), 0, null, -1, ((BlockArgNode)yyVals[0+yyTop]));
}
break;
case 441:
// line 1704 "DefaultRubyParser.y"
{
yyVal = new ArgsNode(getPosition(), 0, null, -1, null);
}
break;
case 442:
// line 1708 "DefaultRubyParser.y"
{
yyerror("formal argument cannot be a constant");
}
break;
case 443:
// line 1711 "DefaultRubyParser.y"
{
yyerror("formal argument cannot be an instance variable");
}
break;
case 444:
// line 1714 "DefaultRubyParser.y"
{
yyerror("formal argument cannot be a class variable");
}
break;
case 445:
// line 1717 "DefaultRubyParser.y"
{
if (!IdUtil.isLocal(((String)yyVals[0+yyTop]))) {
yyerror("formal argument must be local variable");
} else if (support.getLocalNames().isLocalRegistered(((String)yyVals[0+yyTop]))) {
yyerror("duplicate argument name");
}
support.getLocalNames().getLocalIndex(((String)yyVals[0+yyTop]));
yyVal = new Integer(1);
}
break;
case 447:
// line 1728 "DefaultRubyParser.y"
{
yyVal = new Integer(((Integer)yyVal).intValue() + 1);
}
break;
case 448:
// line 1732 "DefaultRubyParser.y"
{
if (!IdUtil.isLocal(((String)yyVals[-2+yyTop]))) {
yyerror("formal argument must be local variable");
} else if (support.getLocalNames().isLocalRegistered(((String)yyVals[-2+yyTop]))) {
yyerror("duplicate optional argument name");
}
support.getLocalNames().getLocalIndex(((String)yyVals[-2+yyTop]));
yyVal = support.assignable(getPosition(), ((String)yyVals[-2+yyTop]), ((Node)yyVals[0+yyTop]));
}
break;
case 449:
// line 1742 "DefaultRubyParser.y"
{
yyVal = new ArrayNode(getPosition()).add(((Node)yyVals[0+yyTop]));
}
break;
case 450:
// line 1745 "DefaultRubyParser.y"
{
yyVal = ((ListNode)yyVals[-2+yyTop]).add(((Node)yyVals[0+yyTop]));
}
break;
case 453:
// line 1752 "DefaultRubyParser.y"
{
if (!IdUtil.isLocal(((String)yyVals[0+yyTop]))) {
yyerror("rest argument must be local variable");
} else if (support.getLocalNames().isLocalRegistered(((String)yyVals[0+yyTop]))) {
yyerror("duplicate rest argument name");
}
yyVal = new Integer(support.getLocalNames().getLocalIndex(((String)yyVals[0+yyTop])));
}
break;
case 454:
// line 1760 "DefaultRubyParser.y"
{
yyVal = new Integer(-2);
}
break;
case 457:
// line 1767 "DefaultRubyParser.y"
{
if (!IdUtil.isLocal(((String)yyVals[0+yyTop]))) {
yyerror("block argument must be local variable");
} else if (support.getLocalNames().isLocalRegistered(((String)yyVals[0+yyTop]))) {
yyerror("duplicate block argument name");
}
yyVal = new BlockArgNode(getPosition(), support.getLocalNames().getLocalIndex(((String)yyVals[0+yyTop])));
}
break;
case 458:
// line 1776 "DefaultRubyParser.y"
{
yyVal = ((BlockArgNode)yyVals[0+yyTop]);
}
break;
case 459:
// line 1779 "DefaultRubyParser.y"
{
yyVal = null;
}
break;
case 460:
// line 1783 "DefaultRubyParser.y"
{
if (((Node)yyVals[0+yyTop]) instanceof SelfNode) {
yyVal = new SelfNode(null);
} else {
support.checkExpression(((Node)yyVals[0+yyTop]));
yyVal = ((Node)yyVals[0+yyTop]);
}
}
break;
case 461:
// line 1791 "DefaultRubyParser.y"
{
lexer.setState(LexState.EXPR_BEG);
}
break;
case 462:
// line 1793 "DefaultRubyParser.y"
{
if (((Node)yyVals[-2+yyTop]) instanceof ILiteralNode) {
/*case Constants.NODE_STR:
case Constants.NODE_DSTR:
case Constants.NODE_XSTR:
case Constants.NODE_DXSTR:
case Constants.NODE_DREGX:
case Constants.NODE_LIT:
case Constants.NODE_ARRAY:
case Constants.NODE_ZARRAY:*/
yyerror("Can't define single method for literals.");
}
support.checkExpression(((Node)yyVals[-2+yyTop]));
yyVal = ((Node)yyVals[-2+yyTop]);
}
break;
case 464:
// line 1810 "DefaultRubyParser.y"
{
yyVal = ((ListNode)yyVals[-1+yyTop]);
}
break;
case 465:
// line 1813 "DefaultRubyParser.y"
{
if (ListNodeUtil.getLength(((ListNode)yyVals[-1+yyTop])) % 2 != 0) {
yyerror("Odd number list for Hash.");
}
yyVal = ((ListNode)yyVals[-1+yyTop]);
}
break;
case 467:
// line 1821 "DefaultRubyParser.y"
{
yyVal = ListNodeUtil.addAll(((ListNode)yyVals[-2+yyTop]), ((ListNode)yyVals[0+yyTop]));
}
break;
case 468:
// line 1825 "DefaultRubyParser.y"
{
yyVal = new ArrayNode(getPosition()).add(((Node)yyVals[-2+yyTop])).add(((Node)yyVals[0+yyTop]));
}
break;
case 488:
// line 1855 "DefaultRubyParser.y"
{
yyerrok();
}
break;
case 491:
// line 1861 "DefaultRubyParser.y"
{
yyerrok();
}
break;
case 492:
// line 1865 "DefaultRubyParser.y"
{
yyVal = null;
}
break;
case 493:
// line 1869 "DefaultRubyParser.y"
{ yyVal = null;
}
break;
case 494:
// line 1872 "DefaultRubyParser.y"
{ yyVal = null;
}
break;
// line 2921 "-"
}
yyTop -= YyLenClass.yyLen[yyN];
yyState = yyStates[yyTop];
int yyM = YyLhsClass.yyLhs[yyN];
if (yyState == 0 && yyM == 0) {
yyState = yyFinal;
if (yyToken < 0) {
yyToken = yyLex.advance() ? yyLex.token() : 0;
}
if (yyToken == 0) {
return yyVal;
}
continue yyLoop;
}
if ((yyN = YyGindexClass.yyGindex[yyM]) != 0 && (yyN += yyState) >= 0
&& yyN < YyTableClass.yyTable.length && YyCheckClass.yyCheck[yyN] == yyState)
yyState = YyTableClass.yyTable[yyN];
else
yyState = YyDgotoClass.yyDgoto[yyM];
continue yyLoop;
}
}
}
|
diff --git a/beam-core/src/test/java/org/esa/beam/framework/datamodel/PlacemarkTest.java b/beam-core/src/test/java/org/esa/beam/framework/datamodel/PlacemarkTest.java
index dcb1bb1a7..9bfeedbfd 100644
--- a/beam-core/src/test/java/org/esa/beam/framework/datamodel/PlacemarkTest.java
+++ b/beam-core/src/test/java/org/esa/beam/framework/datamodel/PlacemarkTest.java
@@ -1,307 +1,307 @@
/*
* Copyright (C) 2010 Brockmann Consult GmbH ([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/
*/
package org.esa.beam.framework.datamodel;
import junit.framework.TestCase;
import org.esa.beam.dataio.dimap.DimapProductConstants;
import org.esa.beam.dataio.placemark.PlacemarkIO;
import org.esa.beam.util.SystemUtils;
import org.esa.beam.util.XmlWriter;
import org.jdom.Element;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.List;
public class PlacemarkTest extends TestCase {
private static final String _NODE_ADDED = "nodeAdded";
private static final String _NODE_CHANGED = "nodeChanged";
private static final String _NODE_DATA_CHANGED = "ndc";
private static final String _NODE_REMOVED = "nodeRemoved";
private static final String _ls = SystemUtils.LS;
private Product product;
private List<String> eventTypes;
private List<ProductNodeEvent> events;
@Override
public void setUp() {
product = new Product("product", "t", 10, 10);
eventTypes = new ArrayList<String>();
events = new ArrayList<ProductNodeEvent>();
product.addProductNodeListener(new ProductNodeListener() {
@Override
public void nodeChanged(ProductNodeEvent event) {
if (event.getSource() instanceof Placemark) {
eventTypes.add(_NODE_CHANGED);
events.add(event);
}
}
@Override
public void nodeDataChanged(ProductNodeEvent event) {
if (event.getSource() instanceof Placemark) {
eventTypes.add(_NODE_DATA_CHANGED);
events.add(event);
}
}
@Override
public void nodeAdded(ProductNodeEvent event) {
if (event.getSource() instanceof Placemark) {
eventTypes.add(_NODE_ADDED);
events.add(event);
}
}
@Override
public void nodeRemoved(ProductNodeEvent event) {
if (event.getSource() instanceof Placemark) {
eventTypes.add(_NODE_REMOVED);
events.add(event);
}
}
});
}
public void testPinEvents() {
final Placemark placemark1 = Placemark.createPointPlacemark(PinDescriptor.getInstance(), "pinName", "pinLabel", "", null, new GeoPos(),
product.getGeoCoding());
assertEquals(0, product.getPinGroup().getNodeCount());
assertEquals(0, events.size());
assertEquals(0, eventTypes.size());
product.getPinGroup().add(placemark1);
assertEquals(1, product.getPinGroup().getNodeCount());
assertEquals(1, events.size());
assertEquals(1, eventTypes.size());
placemark1.setDescription("descPin1");
assertEquals(1, product.getPinGroup().getNodeCount());
assertEquals(2, events.size());
assertEquals(2, eventTypes.size());
placemark1.setGeoPos(new GeoPos(4, 4));
assertEquals(1, product.getPinGroup().getNodeCount());
assertEquals(4, events.size());
assertEquals(4, eventTypes.size());
placemark1.setStyleCss("fill:#CAFEBABE");
assertEquals(1, product.getPinGroup().getNodeCount());
assertEquals(5, events.size());
assertEquals(5, eventTypes.size());
product.getPinGroup().remove(placemark1);
assertEquals(0, product.getPinGroup().getNodeCount());
assertEquals(6, events.size());
assertEquals(6, eventTypes.size());
final String[] expectedEventTypes = new String[]{
_NODE_ADDED,
_NODE_CHANGED,
_NODE_CHANGED,
_NODE_CHANGED,
_NODE_CHANGED,
_NODE_REMOVED
};
final String[] currentEventTypes = eventTypes.toArray(new String[eventTypes.size()]);
for (int i = 0; i < currentEventTypes.length; i++) {
assertEquals("event number: " + i, expectedEventTypes[i], currentEventTypes[i]);
}
final String[] expectedPropertyNames = new String[]{
null,
ProductNode.PROPERTY_NAME_DESCRIPTION,
Placemark.PROPERTY_NAME_PIXELPOS,
Placemark.PROPERTY_NAME_GEOPOS,
Placemark.PROPERTY_NAME_STYLE_CSS,
null
};
final ProductNodeEvent[] currentProductNodeEvents = events.toArray(new ProductNodeEvent[events.size()]);
for (int i = 0; i < currentProductNodeEvents.length; i++) {
final ProductNodeEvent currentProductNodeEvent = currentProductNodeEvents[i];
assertEquals("event number: " + i, placemark1, currentProductNodeEvent.getSourceNode());
assertEquals("event number: " + i, expectedPropertyNames[i], currentProductNodeEvent.getPropertyName());
}
}
public void testWriteXML_XmlWriterIsNull() {
Placemark placemark = Placemark.createPointPlacemark(PinDescriptor.getInstance(), "pinName", "pinLabel", "", null, new GeoPos(),
product.getGeoCoding());
try {
PlacemarkIO.writeXML(placemark, null, 1);
fail("IllegalArgumentException expected");
} catch (IllegalArgumentException e) {
// expected IllegalArgumentException
} catch (Exception e) {
fail("IllegalArgumentException expected");
}
}
public void testWriteXML_IndentIsSmallerThanZero() {
Placemark placemark = Placemark.createPointPlacemark(PinDescriptor.getInstance(), "pinName", "pinLabel", "", null, new GeoPos(), product.getGeoCoding());
try {
int indent = -1;
PlacemarkIO.writeXML(placemark, new XmlWriter(new StringWriter(), false), indent);
fail("IllegalArgumentException expected");
} catch (IllegalArgumentException e) {
// expected IllegalArgumentException
} catch (Exception e) {
fail("IllegalArgumentException expected");
}
}
public void testWriteXML_DifferentValidIndent() {
Placemark placemark = Placemark.createPointPlacemark(PinDescriptor.getInstance(), "pinName", "pinLabel", "", null, new GeoPos(4f, 87f),
product.getGeoCoding());
placemark.setDescription("pinDescription");
StringWriter stringWriter = new StringWriter();
PlacemarkIO.writeXML(placemark, new XmlWriter(stringWriter, false), 0);
String expected = "" +
"<Placemark name=\"pinName\">" + _ls +
" <LABEL>pinLabel</LABEL>" + _ls +
" <DESCRIPTION>pinDescription</DESCRIPTION>" + _ls +
" <LATITUDE>4.0</LATITUDE>" + _ls +
" <LONGITUDE>87.0</LONGITUDE>" + _ls +
"</Placemark>" + _ls;
assertEquals(expected, stringWriter.toString());
stringWriter = new StringWriter();
PlacemarkIO.writeXML(placemark, new XmlWriter(stringWriter, false), 3);
expected = "" +
" <Placemark name=\"pinName\">" + _ls +
" <LABEL>pinLabel</LABEL>" + _ls +
" <DESCRIPTION>pinDescription</DESCRIPTION>" + _ls +
" <LATITUDE>4.0</LATITUDE>" + _ls +
" <LONGITUDE>87.0</LONGITUDE>" + _ls +
" </Placemark>" + _ls;
assertEquals(expected, stringWriter.toString());
}
public void testCreatePin_FromJDOMElement() {
final String pinName = "pin14";
final String pinDesc = "descr";
final float pinLat = 5.7f;
final float pinLon = 23.4f;
try {
PlacemarkIO.createPlacemark(null, null, null);
fail("NullPointerException expected");
} catch (NullPointerException e) {
// OK
}
Element pinElem = new Element(DimapProductConstants.TAG_PLACEMARK);
try {
PlacemarkIO.createPlacemark(pinElem, PinDescriptor.getInstance(), null);
fail("IllegalArgumentException expected");
} catch (IllegalArgumentException e) {
// OK
}
pinElem.setAttribute(DimapProductConstants.ATTRIB_NAME, pinName);
try {
PlacemarkIO.createPlacemark(pinElem, null, null);
fail("IllegalArgumentException expected");
} catch (IllegalArgumentException e) {
// OK
}
final Element latElem = new Element(DimapProductConstants.TAG_PLACEMARK_LATITUDE);
latElem.setText(String.valueOf(pinLat));
pinElem.addContent(latElem);
try {
PlacemarkIO.createPlacemark(pinElem, null, null);
fail("IllegalArgumentException expected");
} catch (Exception e) {
// OK
}
final Element lonElem = new Element(DimapProductConstants.TAG_PLACEMARK_LONGITUDE);
lonElem.setText(String.valueOf(pinLon));
pinElem.addContent(lonElem);
Placemark placemark = PlacemarkIO.createPlacemark(pinElem, PinDescriptor.getInstance(), null);
assertNotNull("pin must be not null", placemark);
assertEquals(pinName, placemark.getName());
assertEquals("", placemark.getDescription());
assertEquals(pinLat, placemark.getGeoPos().lat, 1e-15f);
assertEquals(pinLon, placemark.getGeoPos().lon, 1e-15f);
final Element descElem = new Element(DimapProductConstants.TAG_PLACEMARK_DESCRIPTION);
descElem.setText(pinDesc);
pinElem.addContent(descElem);
placemark = PlacemarkIO.createPlacemark(pinElem, PinDescriptor.getInstance(), null);
assertNotNull("pin must be not null", placemark);
assertEquals(pinName, placemark.getName());
assertEquals(pinDesc, placemark.getDescription());
assertEquals(pinLat, placemark.getGeoPos().lat, 1e-15f);
assertEquals(pinLon, placemark.getGeoPos().lon, 1e-15f);
final Element fillElem = new Element(DimapProductConstants.TAG_PLACEMARK_FILL_COLOR);
Element colorElem = new Element(DimapProductConstants.TAG_COLOR);
colorElem.setAttribute(DimapProductConstants.ATTRIB_RED, "255");
colorElem.setAttribute(DimapProductConstants.ATTRIB_GREEN, "0");
colorElem.setAttribute(DimapProductConstants.ATTRIB_BLUE, "0");
colorElem.setAttribute(DimapProductConstants.ATTRIB_ALPHA, "255");
fillElem.addContent(colorElem);
pinElem.addContent(fillElem);
final Element outlineElem = new Element(DimapProductConstants.TAG_PLACEMARK_OUTLINE_COLOR);
colorElem = new Element(DimapProductConstants.TAG_COLOR);
colorElem.setAttribute(DimapProductConstants.ATTRIB_RED, "0");
colorElem.setAttribute(DimapProductConstants.ATTRIB_GREEN, "0");
colorElem.setAttribute(DimapProductConstants.ATTRIB_BLUE, "255");
colorElem.setAttribute(DimapProductConstants.ATTRIB_ALPHA, "255");
outlineElem.addContent(colorElem);
pinElem.addContent(outlineElem);
placemark = PlacemarkIO.createPlacemark(pinElem, PinDescriptor.getInstance(), null);
assertNotNull("pin must be not null", placemark);
assertEquals(pinName, placemark.getName());
assertEquals(pinDesc, placemark.getDescription());
assertEquals(pinLat, placemark.getGeoPos().lat, 1e-15f);
assertEquals(pinLon, placemark.getGeoPos().lon, 1e-15f);
- assertEquals("fill:255,0,0;stroke:0,0,255", placemark.getStyleCss());
+ assertEquals("", placemark.getStyleCss());
}
public void testLabelSettings() {
Placemark p = Placemark.createPointPlacemark(PinDescriptor.getInstance(), "rallamann", "rallamann", "", null, new GeoPos(), product.getGeoCoding());
assertEquals("rallamann", p.getName());
assertEquals("rallamann", p.getLabel());
p.setLabel("schanteri");
assertEquals("rallamann", p.getName());
assertEquals("schanteri", p.getLabel());
p.setLabel(null);
assertEquals("", p.getLabel());
p.setLabel("");
assertEquals("", p.getLabel());
}
}
| true | true | public void testCreatePin_FromJDOMElement() {
final String pinName = "pin14";
final String pinDesc = "descr";
final float pinLat = 5.7f;
final float pinLon = 23.4f;
try {
PlacemarkIO.createPlacemark(null, null, null);
fail("NullPointerException expected");
} catch (NullPointerException e) {
// OK
}
Element pinElem = new Element(DimapProductConstants.TAG_PLACEMARK);
try {
PlacemarkIO.createPlacemark(pinElem, PinDescriptor.getInstance(), null);
fail("IllegalArgumentException expected");
} catch (IllegalArgumentException e) {
// OK
}
pinElem.setAttribute(DimapProductConstants.ATTRIB_NAME, pinName);
try {
PlacemarkIO.createPlacemark(pinElem, null, null);
fail("IllegalArgumentException expected");
} catch (IllegalArgumentException e) {
// OK
}
final Element latElem = new Element(DimapProductConstants.TAG_PLACEMARK_LATITUDE);
latElem.setText(String.valueOf(pinLat));
pinElem.addContent(latElem);
try {
PlacemarkIO.createPlacemark(pinElem, null, null);
fail("IllegalArgumentException expected");
} catch (Exception e) {
// OK
}
final Element lonElem = new Element(DimapProductConstants.TAG_PLACEMARK_LONGITUDE);
lonElem.setText(String.valueOf(pinLon));
pinElem.addContent(lonElem);
Placemark placemark = PlacemarkIO.createPlacemark(pinElem, PinDescriptor.getInstance(), null);
assertNotNull("pin must be not null", placemark);
assertEquals(pinName, placemark.getName());
assertEquals("", placemark.getDescription());
assertEquals(pinLat, placemark.getGeoPos().lat, 1e-15f);
assertEquals(pinLon, placemark.getGeoPos().lon, 1e-15f);
final Element descElem = new Element(DimapProductConstants.TAG_PLACEMARK_DESCRIPTION);
descElem.setText(pinDesc);
pinElem.addContent(descElem);
placemark = PlacemarkIO.createPlacemark(pinElem, PinDescriptor.getInstance(), null);
assertNotNull("pin must be not null", placemark);
assertEquals(pinName, placemark.getName());
assertEquals(pinDesc, placemark.getDescription());
assertEquals(pinLat, placemark.getGeoPos().lat, 1e-15f);
assertEquals(pinLon, placemark.getGeoPos().lon, 1e-15f);
final Element fillElem = new Element(DimapProductConstants.TAG_PLACEMARK_FILL_COLOR);
Element colorElem = new Element(DimapProductConstants.TAG_COLOR);
colorElem.setAttribute(DimapProductConstants.ATTRIB_RED, "255");
colorElem.setAttribute(DimapProductConstants.ATTRIB_GREEN, "0");
colorElem.setAttribute(DimapProductConstants.ATTRIB_BLUE, "0");
colorElem.setAttribute(DimapProductConstants.ATTRIB_ALPHA, "255");
fillElem.addContent(colorElem);
pinElem.addContent(fillElem);
final Element outlineElem = new Element(DimapProductConstants.TAG_PLACEMARK_OUTLINE_COLOR);
colorElem = new Element(DimapProductConstants.TAG_COLOR);
colorElem.setAttribute(DimapProductConstants.ATTRIB_RED, "0");
colorElem.setAttribute(DimapProductConstants.ATTRIB_GREEN, "0");
colorElem.setAttribute(DimapProductConstants.ATTRIB_BLUE, "255");
colorElem.setAttribute(DimapProductConstants.ATTRIB_ALPHA, "255");
outlineElem.addContent(colorElem);
pinElem.addContent(outlineElem);
placemark = PlacemarkIO.createPlacemark(pinElem, PinDescriptor.getInstance(), null);
assertNotNull("pin must be not null", placemark);
assertEquals(pinName, placemark.getName());
assertEquals(pinDesc, placemark.getDescription());
assertEquals(pinLat, placemark.getGeoPos().lat, 1e-15f);
assertEquals(pinLon, placemark.getGeoPos().lon, 1e-15f);
assertEquals("fill:255,0,0;stroke:0,0,255", placemark.getStyleCss());
}
| public void testCreatePin_FromJDOMElement() {
final String pinName = "pin14";
final String pinDesc = "descr";
final float pinLat = 5.7f;
final float pinLon = 23.4f;
try {
PlacemarkIO.createPlacemark(null, null, null);
fail("NullPointerException expected");
} catch (NullPointerException e) {
// OK
}
Element pinElem = new Element(DimapProductConstants.TAG_PLACEMARK);
try {
PlacemarkIO.createPlacemark(pinElem, PinDescriptor.getInstance(), null);
fail("IllegalArgumentException expected");
} catch (IllegalArgumentException e) {
// OK
}
pinElem.setAttribute(DimapProductConstants.ATTRIB_NAME, pinName);
try {
PlacemarkIO.createPlacemark(pinElem, null, null);
fail("IllegalArgumentException expected");
} catch (IllegalArgumentException e) {
// OK
}
final Element latElem = new Element(DimapProductConstants.TAG_PLACEMARK_LATITUDE);
latElem.setText(String.valueOf(pinLat));
pinElem.addContent(latElem);
try {
PlacemarkIO.createPlacemark(pinElem, null, null);
fail("IllegalArgumentException expected");
} catch (Exception e) {
// OK
}
final Element lonElem = new Element(DimapProductConstants.TAG_PLACEMARK_LONGITUDE);
lonElem.setText(String.valueOf(pinLon));
pinElem.addContent(lonElem);
Placemark placemark = PlacemarkIO.createPlacemark(pinElem, PinDescriptor.getInstance(), null);
assertNotNull("pin must be not null", placemark);
assertEquals(pinName, placemark.getName());
assertEquals("", placemark.getDescription());
assertEquals(pinLat, placemark.getGeoPos().lat, 1e-15f);
assertEquals(pinLon, placemark.getGeoPos().lon, 1e-15f);
final Element descElem = new Element(DimapProductConstants.TAG_PLACEMARK_DESCRIPTION);
descElem.setText(pinDesc);
pinElem.addContent(descElem);
placemark = PlacemarkIO.createPlacemark(pinElem, PinDescriptor.getInstance(), null);
assertNotNull("pin must be not null", placemark);
assertEquals(pinName, placemark.getName());
assertEquals(pinDesc, placemark.getDescription());
assertEquals(pinLat, placemark.getGeoPos().lat, 1e-15f);
assertEquals(pinLon, placemark.getGeoPos().lon, 1e-15f);
final Element fillElem = new Element(DimapProductConstants.TAG_PLACEMARK_FILL_COLOR);
Element colorElem = new Element(DimapProductConstants.TAG_COLOR);
colorElem.setAttribute(DimapProductConstants.ATTRIB_RED, "255");
colorElem.setAttribute(DimapProductConstants.ATTRIB_GREEN, "0");
colorElem.setAttribute(DimapProductConstants.ATTRIB_BLUE, "0");
colorElem.setAttribute(DimapProductConstants.ATTRIB_ALPHA, "255");
fillElem.addContent(colorElem);
pinElem.addContent(fillElem);
final Element outlineElem = new Element(DimapProductConstants.TAG_PLACEMARK_OUTLINE_COLOR);
colorElem = new Element(DimapProductConstants.TAG_COLOR);
colorElem.setAttribute(DimapProductConstants.ATTRIB_RED, "0");
colorElem.setAttribute(DimapProductConstants.ATTRIB_GREEN, "0");
colorElem.setAttribute(DimapProductConstants.ATTRIB_BLUE, "255");
colorElem.setAttribute(DimapProductConstants.ATTRIB_ALPHA, "255");
outlineElem.addContent(colorElem);
pinElem.addContent(outlineElem);
placemark = PlacemarkIO.createPlacemark(pinElem, PinDescriptor.getInstance(), null);
assertNotNull("pin must be not null", placemark);
assertEquals(pinName, placemark.getName());
assertEquals(pinDesc, placemark.getDescription());
assertEquals(pinLat, placemark.getGeoPos().lat, 1e-15f);
assertEquals(pinLon, placemark.getGeoPos().lon, 1e-15f);
assertEquals("", placemark.getStyleCss());
}
|
diff --git a/missionSINF1121/m3/RevueParser.java b/missionSINF1121/m3/RevueParser.java
index c0056f5..fc2a11d 100644
--- a/missionSINF1121/m3/RevueParser.java
+++ b/missionSINF1121/m3/RevueParser.java
@@ -1,80 +1,80 @@
import java.util.HashMap;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;
// WORKING IN PROGRESS
public class RevueParser {
private String filePathIn;
private InOut handler;
private HashMap<String,Revue> map;
public RevueParser(String filePathIn){
this.filePathIn = filePathIn;
this.handler = new InOut(filePathIn,"");
map = new HashMap<String,Revue>();
}
public void start(){
try {
// TODO code application logic here
handler.initReader();
String line = handler.readLine();
if (line.equals("Rank,Title,FoR1,FoR1 Name,FoR2,FoR2 Name,FoR3,FoR3 Name")) {
System.out.println("Wait for the application init....");
while (!handler.isEndOfFile()) {
line = handler.readLine();
if(line == null) break;
else{
- Revue revueRead=constructRevue(handler.readLine());
+ Revue revueRead=constructRevue(line);
map.put(revueRead.getTitle(), revueRead);
}
}
handler.closeReader();
} else {
System.out.println("Entete du fichier incorrecte! Veuillez verifier le fichier de donnée et recommencer.");
}
handler.closeReader();
} catch (InOutException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}
}
public void commandLine(){
Scanner clavierIn = new Scanner(System.in);
String cmd = "";
while (!cmd.equals("exit")) {
System.out.println("Welcome to the librairy application.");
System.out.println("Type a review name to access the informations or exit to leave.");
cmd = clavierIn.nextLine();
if(!cmd.equals("exit")){
Revue tmp=map.get(cmd);
if(tmp==null){
System.out.println("la revue "+cmd+" n'existe pas dans la base de donnée");
}else{
System.out.println(tmp);
}
}
}
}
public Revue constructRevue(String line){
String[] tab = line.split(",");
Revue revue = new Revue();
int i;
for(i = 0; i<tab.length; i++){
revue.setValue(tab[i],i);
}
if(i<7){
do{
revue.setValue("", i);
i++;
}while(i<7);
}
return revue;
}
}
| true | true | public void start(){
try {
// TODO code application logic here
handler.initReader();
String line = handler.readLine();
if (line.equals("Rank,Title,FoR1,FoR1 Name,FoR2,FoR2 Name,FoR3,FoR3 Name")) {
System.out.println("Wait for the application init....");
while (!handler.isEndOfFile()) {
line = handler.readLine();
if(line == null) break;
else{
Revue revueRead=constructRevue(handler.readLine());
map.put(revueRead.getTitle(), revueRead);
}
}
handler.closeReader();
} else {
System.out.println("Entete du fichier incorrecte! Veuillez verifier le fichier de donnée et recommencer.");
}
handler.closeReader();
} catch (InOutException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}
}
| public void start(){
try {
// TODO code application logic here
handler.initReader();
String line = handler.readLine();
if (line.equals("Rank,Title,FoR1,FoR1 Name,FoR2,FoR2 Name,FoR3,FoR3 Name")) {
System.out.println("Wait for the application init....");
while (!handler.isEndOfFile()) {
line = handler.readLine();
if(line == null) break;
else{
Revue revueRead=constructRevue(line);
map.put(revueRead.getTitle(), revueRead);
}
}
handler.closeReader();
} else {
System.out.println("Entete du fichier incorrecte! Veuillez verifier le fichier de donnée et recommencer.");
}
handler.closeReader();
} catch (InOutException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}
}
|
diff --git a/src/main/java/com/cwoodson/pigaddons/rpig/RFunction.java b/src/main/java/com/cwoodson/pigaddons/rpig/RFunction.java
index 5e1e351..5331162 100644
--- a/src/main/java/com/cwoodson/pigaddons/rpig/RFunction.java
+++ b/src/main/java/com/cwoodson/pigaddons/rpig/RFunction.java
@@ -1,132 +1,132 @@
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.cwoodson.pigaddons.rpig;
import com.cwoodson.pigaddons.rpig.rtypes.RDataFrame;
import com.cwoodson.pigaddons.rpig.rtypes.RList;
import com.cwoodson.pigaddons.rpig.rtypes.RPrimitive;
import com.cwoodson.pigaddons.rpig.rtypes.RType;
import com.cwoodson.pigaddons.rpig.rutils.RConnector;
import com.cwoodson.pigaddons.rpig.rutils.RException;
import com.cwoodson.pigaddons.rpig.rutils.RUtils;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import org.apache.pig.EvalFunc;
import org.apache.pig.data.DataType;
import org.apache.pig.data.Tuple;
import org.apache.pig.impl.logicalLayer.schema.Schema;
import org.apache.pig.impl.logicalLayer.schema.Schema.FieldSchema;
import org.apache.pig.impl.util.UDFContext;
import org.apache.pig.impl.util.Utils;
import org.apache.pig.parser.ParserException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
*
* @author connor-woodson
*/
public class RFunction extends EvalFunc<Object> {
private static final Logger logger = LoggerFactory.getLogger(RFunction.class);
private final String functionName;
private final RConnector rEngine;
private Schema inputSchema;
private Schema outputSchema;
public RFunction(String functionName) {
this.rEngine = RScriptEngine.getEngine();
this.functionName = functionName;
try {
RType schemaObj = rEngine.eval("attributes(" + functionName + ")$outputSchema");
if (schemaObj != null && schemaObj instanceof RPrimitive) {
String outputSchemaStr = (String)((RPrimitive)schemaObj).getValue();
logger.info("Output Schema Attribute for RFunction '" + functionName + "' detected: " + outputSchemaStr);
try {
this.outputSchema = Utils.getSchemaFromString(outputSchemaStr);
logger.info("Output Schema created for RFunction '" + functionName + "'");
} catch (ParserException pe) {
throw new IllegalArgumentException("RFunction " + functionName + " has invalid output schema: " + outputSchemaStr, pe);
}
} else {
logger.warn("Output Schema Attribute for RFunction '" + functionName + "' missing or improperly declared");
this.outputSchema = null;
}
} catch (RException re) {
throw new IllegalArgumentException("Failed to access attributes of R function '" + functionName + "'", re);
}
}
@Override
public Object exec(Tuple tuple) throws IOException {
getInputSchema();
RList result_list;
try {
List<RType> params = RUtils.pigTupleToR(tuple, inputSchema, 0).expand();
String paramStr = params.isEmpty() ? "" : params.get(0).toRString();
for(int i = 1; i < params.size(); i++) {
paramStr += ", " + params.get(i).toRString();
}
RType result = rEngine.eval(functionName + "(" + paramStr + ")");
if(result instanceof RDataFrame) {
throw new UnsupportedOperationException("rPig does not currently support DataFrames");
} else if(!(result instanceof RList)) { // wrap any other RType
result_list = new RList(getFieldNames(outputSchema.getFields()), result.asList());
} else {
result_list = (RList) result;
}
} catch (RException ex) {
throw new IOException("R Function Execution failed", ex);
}
Schema out = outputSchema;
if(out.size() == 1 && out.getField(0).type == DataType.TUPLE) {
out = out.getField(0).schema;
}
Tuple evalTuple = RUtils.rToPigTuple(result_list, out, 0);
- Object eval = outputSchema.size() == 1 ? evalTuple.get(0) : evalTuple; // Not sure about this
+ Object eval = out.size() == 1 ? evalTuple.get(0) : evalTuple; // Not sure about this
return eval;
}
@Override
public Schema outputSchema(Schema input) {
this.setInputSchema(input);
return this.outputSchema;
}
/**
* *****************************************
*/
/* Required for compatibility prior to 0.11 */
/**
* *****************************************
*/
private Schema getInputSchema() {
if (inputSchema == null) {
Properties properties = UDFContext.getUDFContext().getUDFProperties(this.getClass(), new String[]{functionName});
inputSchema = (Schema) properties.get(functionName + ".inputSchema");
}
return inputSchema;
}
private void setInputSchema(Schema inputSchema) {
this.inputSchema = inputSchema;
Properties properties = UDFContext.getUDFContext().getUDFProperties(this.getClass(), new String[]{functionName});
properties.put(functionName + ".inputSchema", inputSchema);
}
private List<String> getFieldNames(List<FieldSchema> fs) {
List<String> result = new ArrayList<String>();
for(int i = 0; i < fs.size(); i++) {
result.add(fs.get(i).alias);
}
return result;
}
}
| true | true | public Object exec(Tuple tuple) throws IOException {
getInputSchema();
RList result_list;
try {
List<RType> params = RUtils.pigTupleToR(tuple, inputSchema, 0).expand();
String paramStr = params.isEmpty() ? "" : params.get(0).toRString();
for(int i = 1; i < params.size(); i++) {
paramStr += ", " + params.get(i).toRString();
}
RType result = rEngine.eval(functionName + "(" + paramStr + ")");
if(result instanceof RDataFrame) {
throw new UnsupportedOperationException("rPig does not currently support DataFrames");
} else if(!(result instanceof RList)) { // wrap any other RType
result_list = new RList(getFieldNames(outputSchema.getFields()), result.asList());
} else {
result_list = (RList) result;
}
} catch (RException ex) {
throw new IOException("R Function Execution failed", ex);
}
Schema out = outputSchema;
if(out.size() == 1 && out.getField(0).type == DataType.TUPLE) {
out = out.getField(0).schema;
}
Tuple evalTuple = RUtils.rToPigTuple(result_list, out, 0);
Object eval = outputSchema.size() == 1 ? evalTuple.get(0) : evalTuple; // Not sure about this
return eval;
}
| public Object exec(Tuple tuple) throws IOException {
getInputSchema();
RList result_list;
try {
List<RType> params = RUtils.pigTupleToR(tuple, inputSchema, 0).expand();
String paramStr = params.isEmpty() ? "" : params.get(0).toRString();
for(int i = 1; i < params.size(); i++) {
paramStr += ", " + params.get(i).toRString();
}
RType result = rEngine.eval(functionName + "(" + paramStr + ")");
if(result instanceof RDataFrame) {
throw new UnsupportedOperationException("rPig does not currently support DataFrames");
} else if(!(result instanceof RList)) { // wrap any other RType
result_list = new RList(getFieldNames(outputSchema.getFields()), result.asList());
} else {
result_list = (RList) result;
}
} catch (RException ex) {
throw new IOException("R Function Execution failed", ex);
}
Schema out = outputSchema;
if(out.size() == 1 && out.getField(0).type == DataType.TUPLE) {
out = out.getField(0).schema;
}
Tuple evalTuple = RUtils.rToPigTuple(result_list, out, 0);
Object eval = out.size() == 1 ? evalTuple.get(0) : evalTuple; // Not sure about this
return eval;
}
|
diff --git a/containers/tomcat-7/src/main/java/org/mobicents/servlet/sip/startup/SipStandardContext.java b/containers/tomcat-7/src/main/java/org/mobicents/servlet/sip/startup/SipStandardContext.java
index 75b5be552..b81033018 100644
--- a/containers/tomcat-7/src/main/java/org/mobicents/servlet/sip/startup/SipStandardContext.java
+++ b/containers/tomcat-7/src/main/java/org/mobicents/servlet/sip/startup/SipStandardContext.java
@@ -1,1454 +1,1461 @@
/*
* 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.startup;
import java.io.File;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Stack;
import java.util.concurrent.CopyOnWriteArrayList;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.Servlet;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.ServletException;
import javax.servlet.sip.SipServlet;
import javax.servlet.sip.SipServletContextEvent;
import javax.servlet.sip.SipServletListener;
import javax.servlet.sip.SipServletRequest;
import javax.servlet.sip.TimerService;
import org.apache.catalina.Container;
import org.apache.catalina.Engine;
import org.apache.catalina.Globals;
import org.apache.catalina.Host;
import org.apache.catalina.LifecycleException;
import org.apache.catalina.Manager;
import org.apache.catalina.Service;
import org.apache.catalina.Wrapper;
import org.apache.catalina.core.NamingContextListener;
import org.apache.catalina.core.StandardContext;
import org.apache.catalina.deploy.Injectable;
import org.apache.catalina.deploy.InjectionTarget;
import org.apache.catalina.deploy.LoginConfig;
import org.apache.catalina.deploy.NamingResources;
import org.apache.catalina.loader.WebappLoader;
import org.apache.catalina.security.SecurityUtil;
import org.apache.log4j.Logger;
import org.apache.naming.resources.FileDirContext;
import org.apache.naming.resources.WARDirContext;
import org.apache.tomcat.InstanceManager;
import org.mobicents.servlet.sip.SipConnector;
import org.mobicents.servlet.sip.annotation.ConcurrencyControlMode;
import org.mobicents.servlet.sip.annotations.DefaultSipInstanceManager;
import org.mobicents.servlet.sip.catalina.CatalinaSipContext;
import org.mobicents.servlet.sip.catalina.CatalinaSipListenersHolder;
import org.mobicents.servlet.sip.catalina.CatalinaSipManager;
import org.mobicents.servlet.sip.catalina.SARDirContext;
import org.mobicents.servlet.sip.catalina.SipSecurityConstraint;
import org.mobicents.servlet.sip.catalina.SipServletImpl;
import org.mobicents.servlet.sip.catalina.SipStandardManager;
import org.mobicents.servlet.sip.catalina.annotations.SipInstanceManager;
import org.mobicents.servlet.sip.catalina.security.SipSecurityUtils;
import org.mobicents.servlet.sip.catalina.security.authentication.DigestAuthenticator;
import org.mobicents.servlet.sip.core.MobicentsSipServlet;
import org.mobicents.servlet.sip.core.SipApplicationDispatcher;
import org.mobicents.servlet.sip.core.SipContextEvent;
import org.mobicents.servlet.sip.core.SipContextEventType;
import org.mobicents.servlet.sip.core.SipListeners;
import org.mobicents.servlet.sip.core.SipManager;
import org.mobicents.servlet.sip.core.SipService;
import org.mobicents.servlet.sip.core.descriptor.MobicentsSipServletMapping;
import org.mobicents.servlet.sip.core.message.MobicentsSipServletRequest;
import org.mobicents.servlet.sip.core.message.MobicentsSipServletResponse;
import org.mobicents.servlet.sip.core.security.MobicentsSipLoginConfig;
import org.mobicents.servlet.sip.core.security.SipDigestAuthenticator;
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.SipApplicationSessionCreationThreadLocal;
import org.mobicents.servlet.sip.core.session.SipSessionsUtilImpl;
import org.mobicents.servlet.sip.core.timers.ProxyTimerService;
import org.mobicents.servlet.sip.core.timers.ProxyTimerServiceImpl;
import org.mobicents.servlet.sip.core.timers.SipApplicationSessionTimerService;
import org.mobicents.servlet.sip.core.timers.SipServletTimerService;
import org.mobicents.servlet.sip.core.timers.StandardSipApplicationSessionTimerService;
import org.mobicents.servlet.sip.core.timers.TimerServiceImpl;
import org.mobicents.servlet.sip.dns.MobicentsDNSResolver;
import org.mobicents.servlet.sip.listener.SipConnectorListener;
import org.mobicents.servlet.sip.message.SipFactoryFacade;
import org.mobicents.servlet.sip.message.SipFactoryImpl;
import org.mobicents.servlet.sip.ruby.SipRubyController;
/**
* Sip implementation of the <b>Context</b> interface extending the standard
* tomcat context to allow deployment of converged applications (sip & web apps)
* as well as standalone sip servlets applications.
*
* @author Jean Deruelle
*
*/
public class SipStandardContext extends StandardContext implements CatalinaSipContext {
private static final long serialVersionUID = 1L;
// the logger
private static transient final Logger logger = Logger.getLogger(SipStandardContext.class);
/**
* The descriptive information string for this implementation.
*/
private static final String info =
"org.mobicents.servlet.sip.startup.SipStandardContext/1.0";
// as mentionned per JSR 289 Section 6.1.2.1 default lifetime for an
// application session is 3 minutes
private static int DEFAULT_LIFETIME = 3;
protected String applicationName;
protected String smallIcon;
protected String largeIcon;
protected String description;
protected int proxyTimeout;
protected int sipApplicationSessionTimeout;
protected transient SipListeners sipListeners;
protected transient SipFactoryFacade sipFactoryFacade;
protected transient SipSessionsUtilImpl sipSessionsUtil;
protected transient MobicentsSipLoginConfig sipLoginConfig;
protected transient SipSecurityUtils sipSecurityUtils;
protected transient SipDigestAuthenticator sipDigestAuthenticator;
protected boolean hasDistributableManager;
protected String namingContextName;
protected transient Method sipApplicationKeyMethod;
protected ConcurrencyControlMode concurrencyControlMode;
/**
* The set of sip application listener class names configured for this
* application, in the order they were encountered in the sip.xml file.
*/
protected transient List<String> sipApplicationListeners = new CopyOnWriteArrayList<String>();
// Issue 1200 this is needed to be able to give a default servlet handler if we are not in main-servlet servlet selection case
// by example when creating a new sip application session from a factory from an http servlet
private String servletHandler;
private boolean isMainServlet;
private String mainServlet;
/**
* The set of sip servlet mapping configured for this
* application.
*/
protected transient List<MobicentsSipServletMapping> sipServletMappings = new ArrayList<MobicentsSipServletMapping>();
protected transient SipApplicationDispatcher sipApplicationDispatcher = null;
protected transient Map<String, MobicentsSipServlet> childrenMap;
protected transient Map<String, MobicentsSipServlet> childrenMapByClassName;
protected boolean sipJNDIContextLoaded = false;
// timer service used to schedule sip application session expiration timer
protected transient SipApplicationSessionTimerService sasTimerService = null;
// timer service used to schedule sip servlet originated timer tasks
protected transient SipServletTimerService timerService = null;
// timer service used to schedule proxy timer tasks
protected transient ProxyTimerService proxyTimerService = null;
// http://code.google.com/p/mobicents/issues/detail?id=2450
private transient ThreadLocal<SipApplicationSessionCreationThreadLocal> sipApplicationSessionsAccessedThreadLocal = new ThreadLocal<SipApplicationSessionCreationThreadLocal>();
// http://code.google.com/p/mobicents/issues/detail?id=2534 && http://code.google.com/p/mobicents/issues/detail?id=2526
private transient ThreadLocal<Boolean> isManagedThread = new ThreadLocal<Boolean>();
/**
*
*/
public SipStandardContext() {
super();
sipApplicationSessionTimeout = DEFAULT_LIFETIME;
pipeline.setBasic(new SipStandardContextValve());
sipListeners = new CatalinaSipListenersHolder(this);
childrenMap = new HashMap<String, MobicentsSipServlet>();
childrenMapByClassName = new HashMap<String, MobicentsSipServlet>();
int idleTime = getSipApplicationSessionTimeout();
if(idleTime <= 0) {
idleTime = 1;
}
hasDistributableManager = false;
}
@Override
public void initInternal() throws LifecycleException {
if(logger.isInfoEnabled()) {
logger.info("Initializing the sip context");
}
// if (this.getParent() != null) {
// // Add the main configuration listener for sip applications
// LifecycleListener sipConfigurationListener = new SipContextConfig();
// this.addLifecycleListener(sipConfigurationListener);
// setDelegate(true);
// }
// call the super method to correctly initialize the context and fire
// up the
// init event on the new registered SipContextConfig, so that the
// standardcontextconfig
// is correctly initialized too
super.initInternal();
prepareServletContext();
if(logger.isInfoEnabled()) {
logger.info("sip context Initialized");
}
}
protected void prepareServletContext() throws LifecycleException {
if(sipApplicationDispatcher == null) {
setApplicationDispatcher();
}
if(sipFactoryFacade == null) {
sipFactoryFacade = new SipFactoryFacade((SipFactoryImpl)sipApplicationDispatcher.getSipFactory(), this);
}
if(sipSessionsUtil == null) {
sipSessionsUtil = new SipSessionsUtilImpl(this);
}
if(timerService == null) {
timerService = new TimerServiceImpl(sipApplicationDispatcher.getSipService());
}
if(proxyTimerService == null) {
proxyTimerService = new ProxyTimerServiceImpl();
}
if(sasTimerService == null || !sasTimerService.isStarted()) {
sasTimerService = new StandardSipApplicationSessionTimerService();
}
//needed when restarting applications through the tomcat manager
this.getServletContext().setAttribute(javax.servlet.sip.SipServlet.SIP_FACTORY,
sipFactoryFacade);
this.getServletContext().setAttribute(javax.servlet.sip.SipServlet.TIMER_SERVICE,
timerService);
this.getServletContext().setAttribute(javax.servlet.sip.SipServlet.SUPPORTED,
Arrays.asList(sipApplicationDispatcher.getExtensionsSupported()));
this.getServletContext().setAttribute("javax.servlet.sip.100rel", Boolean.TRUE);
this.getServletContext().setAttribute(javax.servlet.sip.SipServlet.SUPPORTED_RFCs,
Arrays.asList(sipApplicationDispatcher.getRfcSupported()));
this.getServletContext().setAttribute(javax.servlet.sip.SipServlet.SIP_SESSIONS_UTIL,
sipSessionsUtil);
this.getServletContext().setAttribute(javax.servlet.sip.SipServlet.OUTBOUND_INTERFACES,
sipApplicationDispatcher.getOutboundInterfaces());
this.getServletContext().setAttribute("org.mobicents.servlet.sip.SIP_CONNECTORS",
sipApplicationDispatcher.getSipService().findSipConnectors());
this.getServletContext().setAttribute("org.mobicents.servlet.sip.DNS_RESOLVER",
new MobicentsDNSResolver(sipApplicationDispatcher.getDNSServerLocator()));
}
/**
* @throws Exception
*/
protected void setApplicationDispatcher() throws LifecycleException {
Container container = getParent().getParent();
if(container instanceof Engine) {
Service service = ((Engine)container).getService();
if(service instanceof SipService) {
sipApplicationDispatcher =
((SipService)service).getSipApplicationDispatcher();
}
}
if(sipApplicationDispatcher == null) {
throw new LifecycleException("cannot find any application dispatcher for this context " + name);
}
}
@Override
public synchronized void startInternal() throws LifecycleException {
if(logger.isInfoEnabled()) {
logger.info("Starting the sip context");
}
// if( this.getState().equals(LifecycleState.INITIALIZED)) {
prepareServletContext();
// }
// Add missing components as necessary
boolean ok = true;
if (getResources() == null) { // (1) Required by Loader
if (logger.isDebugEnabled())
logger.debug("Configuring default Resources");
try {
if ((getDocBase() != null) && (getDocBase().endsWith(".war")) && (!(new File(getBasePath())).isDirectory()))
setResources(new WARDirContext());
if ((getDocBase() != null) && (getDocBase().endsWith(".sar")) && (!(new File(getBasePath())).isDirectory()))
setResources(new SARDirContext());
else
setResources(new FileDirContext());
} catch (IllegalArgumentException e) {
logger.error("Error initializing resources: " + e.getMessage());
ok = false;
}
}
if (ok) {
if (!resourcesStart()) {
logger.error( "Error in resourceStart()");
ok = false;
}
}
// Configure default manager if none was specified
if (manager == null) {
if ((getCluster() != null) && getDistributable()) {
try {
manager = getCluster().createManager(getName());
} catch (Exception ex) {
logger.error("standardContext.clusterFail", ex);
// ok = false;
}
} else {
setManager(new SipStandardManager());
}
}
// Reading the "catalina.useNaming" environment variable
String useNamingProperty = System.getProperty("catalina.useNaming");
if ((useNamingProperty != null)
&& (useNamingProperty.equals("false"))) {
setUseNaming(false);
}
// the loader is needed for creating the DefaultSipInstanceManager
if (getLoader() == null) {
WebappLoader webappLoader = new WebappLoader(getParentClassLoader());
webappLoader.setDelegate(getDelegate());
setLoader(webappLoader);
webappLoader.start();
// Report this property change to interested listeners
support.firePropertyChange("loader", null, webappLoader);
- }
+ } else {
+ WebappLoader loader = (WebappLoader) getLoader();
+ loader.setDelegate(getDelegate());
+ setLoader(loader);
+ loader.start();
+ // Report this property change to interested listeners
+ support.firePropertyChange("loader", null, loader);
+ }
//activating our custom naming context to be able to set the sip factory in JNDI
if (isUseNaming()) {
if (getNamingContextListener() == null) {
NamingContextListener namingContextListener = new SipNamingContextListener();
namingContextListener.setName(getNamingContextName());
setNamingContextListener(namingContextListener);
addLifecycleListener(namingContextListener);
addContainerListener(namingContextListener);
}
// Replace the default annotation processor. This is needed to handle resource injection
// for SipFactory, Session utils and other objects residing in the servlet context space.
// Of course if the variable is not found in in the servet context it defaults to the
// normal lookup method - in the default naming context.
//tomcat naming
Map<String, Map<String, String>> injectionMap = buildInjectionMap(
getIgnoreAnnotations() ? new NamingResources(): getNamingResources());
this.setInstanceManager(
new DefaultSipInstanceManager(
getNamingContextListener().getEnvContext(),
injectionMap, this, this.getClass().getClassLoader()));
} else {
// jboss or other kind of naming
try {
Map<String, Map<String, String>> injectionMap = buildInjectionMap(
getIgnoreAnnotations() ? new NamingResources(): getNamingResources());
InitialContext iniCtx = new InitialContext();
Context envCtx = (Context) iniCtx.lookup("java:comp/env");
this.setInstanceManager(
new DefaultSipInstanceManager(
envCtx,
injectionMap, this, this.getClass().getClassLoader()));
} catch (NamingException e) {
logger.error("Impossible to get the naming context ", e);
}
}
//JSR 289 Section 2.1.1 Step 1.Deploy the application.
//This will make start the sip context config, which will in turn parse the sip descriptor deployment
//and call load on startup which is equivalent to
//JSR 289 Section 2.1.1 Step 2.Invoke servlet.init(), the initialization method on the Servlet. Invoke the init() on all the load-on-startup Servlets in the application
super.startInternal();
if(getAvailable()) {
// Replace the default annotation processor. This is needed to handle resource injection
// for SipFactory, Session utils and other objects residing in the servlet context space.
// Of course if the variable is not found in in the servet context it defaults to the
// normal lookup method - in the default naming context.
if(getInstanceManager() == null || !(getInstanceManager() instanceof SipInstanceManager)) {
if(isUseNaming()) {
//tomcat naming
Map<String, Map<String, String>> injectionMap = buildInjectionMap(
getIgnoreAnnotations() ? new NamingResources(): getNamingResources());
this.setInstanceManager(
new DefaultSipInstanceManager(
getNamingContextListener().getEnvContext(),
injectionMap, this, this.getClass().getClassLoader()));
} else {
// jboss or other kind of naming
try {
Map<String, Map<String, String>> injectionMap = buildInjectionMap(
getIgnoreAnnotations() ? new NamingResources(): getNamingResources());
InitialContext iniCtx = new InitialContext();
Context envCtx = (Context) iniCtx.lookup("java:comp/env");
this.setInstanceManager(
new DefaultSipInstanceManager(
envCtx,
injectionMap, this, this.getClass().getClassLoader()));
} catch (NamingException e) {
logger.error("Impossible to get the naming context ", e);
}
}
}
getServletContext().setAttribute(InstanceManager.class.getName(), getInstanceManager());
//set the session manager on the specific sipstandardmanager to handle converged http sessions
if(getManager() instanceof SipManager) {
((SipManager)getManager()).setMobicentsSipFactory(
sipApplicationDispatcher.getSipFactory());
((CatalinaSipManager)manager).setContainer(this);
}
// JSR 289 16.2 Servlet Selection
// When using this mechanism (the main-servlet) for servlet selection,
// if there is only one servlet in the application then this
// declaration is optional and the lone servlet becomes the main servlet
if((mainServlet == null || mainServlet.length() < 1) && childrenMap.size() == 1) {
setMainServlet(childrenMap.keySet().iterator().next());
}
sipSecurityUtils = new SipSecurityUtils(this);
sipDigestAuthenticator = new DigestAuthenticator(sipApplicationDispatcher.getSipFactory().getHeaderFactory());
//JSR 289 Section 2.1.1 Step 3.Invoke SipApplicationRouter.applicationDeployed() for this application.
//called implicitly within sipApplicationDispatcher.addSipApplication
sipApplicationDispatcher.addSipApplication(applicationName, this);
if(manager instanceof DistributableSipManager) {
hasDistributableManager = true;
if(logger.isInfoEnabled()) {
logger.info("this context contains a manager that allows applications to work in a distributed environment");
}
}
if(logger.isInfoEnabled()) {
logger.info("sip application session timeout for this context is " + sipApplicationSessionTimeout + " minutes");
}
if(logger.isInfoEnabled()) {
logger.info("sip context started");
}
} else {
if(logger.isInfoEnabled()) {
logger.info("sip context didn't started due to errors");
}
}
}
@Override
public ServletContext getServletContext() {
if (context == null) {
context = new ConvergedApplicationContext(this);
if (getAltDDName() != null)
context.setAttribute(Globals.ALT_DD_ATTR,getAltDDName());
}
return ((ConvergedApplicationContext)context).getFacade();
}
@Override
public boolean listenerStart() {
boolean ok = super.listenerStart();
//the web listeners couldn't be started so we don't even try to load the sip ones
if(!ok) {
return ok;
}
if (logger.isDebugEnabled())
logger.debug("Configuring sip listeners");
if(!sipJNDIContextLoaded) {
loadSipJNDIContext();
}
// Instantiate the required listeners
ClassLoader loader = getLoader().getClassLoader();
ok = sipListeners.loadListeners(findSipApplicationListeners(), loader);
if(!ok) {
return ok;
}
List<ServletContextListener> servletContextListeners = sipListeners.getServletContextListeners();
if (servletContextListeners != null) {
ServletContextEvent event =
new ServletContextEvent(getServletContext());
for (ServletContextListener servletContextListener : servletContextListeners) {
if (servletContextListener == null)
continue;
try {
fireContainerEvent("beforeContextInitialized", servletContextListener);
servletContextListener.contextInitialized(event);
fireContainerEvent("afterContextInitialized", servletContextListener);
} catch (Throwable t) {
fireContainerEvent("afterContextInitialized", servletContextListener);
getLogger().error
(sm.getString("standardContext.listenerStart",
servletContextListener.getClass().getName()), t);
ok = false;
}
// TODO Annotation processing
}
}
return ok;
}
@Override
public boolean listenerStop() {
boolean ok = super.listenerStop();
if (logger.isDebugEnabled())
logger.debug("Sending application stop events");
List<ServletContextListener> servletContextListeners = sipListeners.getServletContextListeners();
if (servletContextListeners != null) {
ServletContextEvent event =
new ServletContextEvent(getServletContext());
for (ServletContextListener servletContextListener : servletContextListeners) {
if (servletContextListener == null)
continue;
try {
fireContainerEvent("beforeContextDestroyed", servletContextListener);
servletContextListener.contextDestroyed(event);
fireContainerEvent("afterContextDestroyed", servletContextListener);
} catch (Throwable t) {
fireContainerEvent("afterContextDestroyed", servletContextListener);
getLogger().error
(sm.getString("standardContext.listenerStop",
servletContextListener.getClass().getName()), t);
ok = false;
}
// TODO Annotation processing
}
}
// TODO Annotation processing check super class on tomcat 6
sipListeners.clean();
return ok;
}
/**
* Get base path. Copy pasted from StandardContext Tomcat class
*/
public String getBasePath() {
String docBase = null;
Container container = this;
while (container != null) {
if (container instanceof Host)
break;
container = container.getParent();
}
File file = new File(getDocBase());
if (!file.isAbsolute()) {
if (container == null) {
docBase = (new File(engineBase(), getDocBase())).getPath();
} else {
// Use the "appBase" property of this container
String appBase = ((Host) container).getAppBase();
file = new File(appBase);
if (!file.isAbsolute())
file = new File(engineBase(), appBase);
docBase = (new File(file, getDocBase())).getPath();
}
} else {
docBase = file.getPath();
}
return docBase;
}
@Override
public synchronized void stopInternal() throws LifecycleException {
if(logger.isInfoEnabled()) {
logger.info("Stopping the sip context");
}
if(manager instanceof SipManager) {
((SipManager)manager).dumpSipSessions();
((SipManager)manager).dumpSipApplicationSessions();
logger.info("number of active sip sessions : " + ((SipManager)manager).getActiveSipSessions());
logger.info("number of active sip application sessions : " + ((SipManager)manager).getActiveSipApplicationSessions());
}
super.stopInternal();
// this should happen after so that applications can still do some processing
// in destroy methods to notify that context is getting destroyed and app removed
sipListeners.deallocateServletsActingAsListeners();
sipApplicationListeners.clear();
sipServletMappings.clear();
childrenMap.clear();
childrenMapByClassName.clear();
if(sipApplicationDispatcher != null) {
if(applicationName != null) {
sipApplicationDispatcher.removeSipApplication(applicationName);
} else {
logger.error("the application name is null for the following context : " + name);
}
}
sipJNDIContextLoaded = false;
if(sasTimerService != null && sasTimerService.isStarted()) {
sasTimerService.stop();
}
// Issue 1478 : nullify the ref to avoid reusing it
sasTimerService = null;
// Issue 1791 : don't check is the service is started it makes the stop
// of tomcat hang
if(timerService != null) {
timerService.stop();
}
if(proxyTimerService != null) {
proxyTimerService.stop();
}
// Issue 1478 : nullify the ref to avoid reusing it
timerService = null;
getServletContext().setAttribute(javax.servlet.sip.SipServlet.TIMER_SERVICE, null);
setLoader(null);
// not needed since the JNDI will be destroyed automatically
// if(isUseNaming()) {
// fireContainerEvent(SipNamingContextListener.NAMING_CONTEXT_SIP_FACTORY_REMOVED_EVENT, sipFactoryFacade);
// fireContainerEvent(SipNamingContextListener.NAMING_CONTEXT_SIP_SESSIONS_UTIL_REMOVED_EVENT, sipSessionsUtil);
// fireContainerEvent(SipNamingContextListener.NAMING_CONTEXT_TIMER_SERVICE_REMOVED_EVENT, TimerServiceImpl.getInstance());
// fireContainerEvent(SipNamingContextListener.NAMING_CONTEXT_SIP_SUBCONTEXT_REMOVED_EVENT, null);
// } else {
// try {
// InitialContext iniCtx = new InitialContext();
// Context envCtx = (Context) iniCtx.lookup("java:comp/env");
// // jboss or other kind of naming
// SipNamingContextListener.removeSipFactory(envCtx, sipFactoryFacade);
// SipNamingContextListener.removeSipSessionsUtil(envCtx, sipSessionsUtil);
// SipNamingContextListener.removeTimerService(envCtx, TimerServiceImpl.getInstance());
// SipNamingContextListener.removeSipSubcontext(envCtx);
// } catch (NamingException e) {
// //It is possible that the context has already been removed so no problem,
// //we are stopping anyway
//// logger.error("Impossible to get the naming context ", e);
// }
// }
logger.info("sip context stopped");
}
@Override
public void loadOnStartup(Container[] containers) {
if(!sipJNDIContextLoaded) {
loadSipJNDIContext();
}
super.loadOnStartup(containers);
}
protected void loadSipJNDIContext() {
if(getInstanceManager() instanceof SipInstanceManager) {
if(getNamingContextListener() != null) {
getSipInstanceManager().setContext(getNamingContextListener().getEnvContext());
} else {
try {
InitialContext iniCtx = new InitialContext();
Context envCtx = (Context) iniCtx.lookup("java:comp/env");
getSipInstanceManager().setContext(envCtx);
} catch (NamingException e) {
logger.error("Impossible to get the naming context ", e);
throw new IllegalStateException(e);
}
}
}
if(isUseNaming()) {
fireContainerEvent(SipNamingContextListener.NAMING_CONTEXT_SIP_SUBCONTEXT_ADDED_EVENT, null);
fireContainerEvent(SipNamingContextListener.NAMING_CONTEXT_APPNAME_SUBCONTEXT_ADDED_EVENT, null);
fireContainerEvent(SipNamingContextListener.NAMING_CONTEXT_SIP_FACTORY_ADDED_EVENT, sipFactoryFacade);
fireContainerEvent(SipNamingContextListener.NAMING_CONTEXT_SIP_SESSIONS_UTIL_ADDED_EVENT, sipSessionsUtil);
fireContainerEvent(SipNamingContextListener.NAMING_CONTEXT_TIMER_SERVICE_ADDED_EVENT, timerService);
} else {
try {
InitialContext iniCtx = new InitialContext();
Context envCtx = (Context) iniCtx.lookup("java:comp/env");
// jboss or other kind of naming
SipNamingContextListener.addSipSubcontext(envCtx);
SipNamingContextListener.addAppNameSubContext(envCtx, applicationName);
SipNamingContextListener.addSipFactory(envCtx, applicationName, sipFactoryFacade);
SipNamingContextListener.addSipSessionsUtil(envCtx, applicationName, sipSessionsUtil);
SipNamingContextListener.addTimerService(envCtx, applicationName, timerService);
} catch (NamingException e) {
logger.error("Impossible to get the naming context ", e);
throw new IllegalStateException(e);
}
}
sipJNDIContextLoaded = true;
}
@Override
public Wrapper createWrapper() {
return super.createWrapper();
}
@Override
public void addChild(Container container) {
if(children.get(container.getName()) == null) {
super.addChild(container);
} else {
if(logger.isDebugEnabled()) {
logger.debug(container.getName() + " already present as a Sip Servlet not adding it again");
}
}
}
public void addChild(SipServletImpl sipServletImpl) {
SipServletImpl existingServlet = (SipServletImpl) childrenMap.get(sipServletImpl.getName());
if(existingServlet != null) {
logger.warn(sipServletImpl.getName() + " servlet already present, removing the previous one. " +
"This might be due to the fact that the definition of the servlet " +
"is present both in annotations and in sip.xml");
//we remove the previous one (annoations) because it may not have init parameters that has been defined in sip.xml
//See TCK Test ContextTest.testContext1
childrenMap.remove(sipServletImpl.getName());
childrenMapByClassName.remove(sipServletImpl.getServletClass());
super.removeChild(existingServlet);
}
childrenMap.put(sipServletImpl.getName(), sipServletImpl);
childrenMapByClassName.put(sipServletImpl.getServletClass(), sipServletImpl);
super.addChild(sipServletImpl);
}
public void removeChild(SipServletImpl sipServletImpl) {
super.removeChild(sipServletImpl);
childrenMap.remove(sipServletImpl.getName());
childrenMapByClassName.remove(sipServletImpl.getServletClass());
}
/**
* {@inheritDoc}
*/
public Map<String, MobicentsSipServlet> getChildrenMap() {
return childrenMap;
}
/**
* {@inheritDoc}
*/
public MobicentsSipServlet findSipServletByName(String name) {
if (name == null)
return (null);
return childrenMap.get(name);
}
/**
* {@inheritDoc}
*/
public MobicentsSipServlet findSipServletByClassName(String className) {
if (className == null)
return (null);
return childrenMapByClassName.get(className);
}
/* (non-Javadoc)
* @see org.mobicents.servlet.sip.startup.SipContext#getApplicationName()
*/
public String getApplicationName() {
return applicationName;
}
/* (non-Javadoc)
* @see org.mobicents.servlet.sip.startup.SipContext#getApplicationNameHashed()
*/
public String getApplicationNameHashed() {
return sipApplicationDispatcher.getHashFromApplicationName(applicationName);
}
/* (non-Javadoc)
* @see org.mobicents.servlet.sip.startup.SipContext#setApplicationName(java.lang.String)
*/
public void setApplicationName(String applicationName) {
this.applicationName = applicationName;
}
/* (non-Javadoc)
* @see org.mobicents.servlet.sip.startup.SipContext#getDescription()
*/
public String getDescription() {
return description;
}
/* (non-Javadoc)
* @see org.mobicents.servlet.sip.startup.SipContext#setDescription(java.lang.String)
*/
public void setDescription(String description) {
this.description = description;
}
/* (non-Javadoc)
* @see org.mobicents.servlet.sip.startup.SipContext#getLargeIcon()
*/
public String getLargeIcon() {
return largeIcon;
}
/* (non-Javadoc)
* @see org.mobicents.servlet.sip.startup.SipContext#setLargeIcon(java.lang.String)
*/
public void setLargeIcon(String largeIcon) {
this.largeIcon = largeIcon;
}
/* (non-Javadoc)
* @see org.mobicents.servlet.sip.startup.SipContext#getListeners()
*/
public SipListeners getListeners() {
return sipListeners;
}
/* (non-Javadoc)
* @see org.mobicents.servlet.sip.startup.SipContext#setListeners(org.mobicents.servlet.sip.core.session.SipListenersHolder)
*/
public void setListeners(SipListeners listeners) {
this.sipListeners = (CatalinaSipListenersHolder) listeners;
}
/*
* (non-Javadoc)
* @see org.mobicents.servlet.sip.startup.SipContext#isMainServlet()
*/
public boolean isMainServlet() {
return isMainServlet;
}
/* (non-Javadoc)
* @see org.mobicents.servlet.sip.startup.SipContext#getMainServlet()
*/
public String getMainServlet() {
return mainServlet;
}
/* (non-Javadoc)
* @see org.mobicents.servlet.sip.startup.SipContext#setMainServlet(java.lang.String)
*/
public void setMainServlet(String mainServlet) {
this.mainServlet = mainServlet;
this.isMainServlet = true;
servletHandler = mainServlet;
}
/* (non-Javadoc)
* @see org.mobicents.servlet.sip.startup.SipContext#getProxyTimeout()
*/
public int getProxyTimeout() {
return proxyTimeout;
}
/* (non-Javadoc)
* @see org.mobicents.servlet.sip.startup.SipContext#setProxyTimeout(int)
*/
public void setProxyTimeout(int proxyTimeout) {
this.proxyTimeout = proxyTimeout;
}
public void addConstraint(SipSecurityConstraint securityConstraint) {
super.addConstraint(securityConstraint);
}
public void removeConstraint(SipSecurityConstraint securityConstraint) {
super.removeConstraint(securityConstraint);
}
/* (non-Javadoc)
* @see org.mobicents.servlet.sip.startup.SipContext#getSmallIcon()
*/
public String getSmallIcon() {
return smallIcon;
}
/* (non-Javadoc)
* @see org.mobicents.servlet.sip.startup.SipContext#setSmallIcon(java.lang.String)
*/
public void setSmallIcon(String smallIcon) {
this.smallIcon = smallIcon;
}
@Override
public void setLoginConfig(LoginConfig config) {
super.setLoginConfig(config);
}
@Override
public LoginConfig getLoginConfig() {
return super.getLoginConfig();
}
public void setSipLoginConfig(MobicentsSipLoginConfig config) {
this.sipLoginConfig = config;
}
public MobicentsSipLoginConfig getSipLoginConfig() {
return this.sipLoginConfig;
}
/**
* Add a new Listener class name to the set of Listeners
* configured for this application.
*
* @param listener Java class name of a listener class
*/
public void addSipApplicationListener(String listener) {
sipApplicationListeners.add(listener);
fireContainerEvent("addSipApplicationListener", listener);
// FIXME - add instance if already started?
}
/**
* Remove the specified application listener class from the set of
* listeners for this application.
*
* @param listener Java class name of the listener to be removed
*/
public void removeSipApplicationListener(String listener) {
sipApplicationListeners.remove(listener);
// Inform interested listeners
fireContainerEvent("removeSipApplicationListener", listener);
// FIXME - behavior if already started?
}
/**
* Return the set of sip application listener class names configured
* for this application.
*/
public String[] findSipApplicationListeners() {
return sipApplicationListeners.toArray(new String[sipApplicationListeners.size()]);
}
/**
* @return the sipApplicationDispatcher
*/
public SipApplicationDispatcher getSipApplicationDispatcher() {
return sipApplicationDispatcher;
}
/**
* @return the sipFactoryFacade
*/
public SipFactoryFacade getSipFactoryFacade() {
return sipFactoryFacade;
}
/**
* @return the sipSessionsUtil
*/
public SipSessionsUtilImpl getSipSessionsUtil() {
return sipSessionsUtil;
}
/**
* @return the timerService
*/
public TimerService getTimerService() {
return timerService;
}
/**
* @return the proxyTimerService
*/
public ProxyTimerService getProxyTimerService() {
return proxyTimerService;
}
/**
* Get naming context full name.
*/
private String getNamingContextName() {
if (namingContextName == null) {
Container parent = getParent();
if (parent == null) {
namingContextName = getName();
} else {
Stack<String> stk = new Stack<String>();
StringBuffer buff = new StringBuffer();
while (parent != null) {
stk.push(parent.getName());
parent = parent.getParent();
}
while (!stk.empty()) {
buff.append("/" + stk.pop());
}
buff.append(getName());
namingContextName = buff.toString();
}
}
return namingContextName;
}
@Override
public synchronized void setManager(Manager manager) {
if(manager instanceof SipManager && sipApplicationDispatcher != null) {
((SipManager)manager).setMobicentsSipFactory(
sipApplicationDispatcher.getSipFactory());
((CatalinaSipManager)manager).setContainer(this);
}
if(manager instanceof DistributableSipManager) {
hasDistributableManager = true;
if(logger.isInfoEnabled()) {
logger.info("this context contains a manager that allows applications to work in a distributed environment");
}
}
super.setManager(manager);
}
@Override
public Manager getManager() {
return super.getManager();
}
/**
* @return the sipApplicationSessionTimeout in minutes
*/
public int getSipApplicationSessionTimeout() {
return sipApplicationSessionTimeout;
}
/**
* @param sipApplicationSessionTimeout the sipApplicationSessionTimeout to set in minutes
*/
public void setSipApplicationSessionTimeout(int sipApplicationSessionTimeout) {
this.sipApplicationSessionTimeout = sipApplicationSessionTimeout;
}
public Method getSipApplicationKeyMethod() {
return sipApplicationKeyMethod;
}
public void setSipApplicationKeyMethod(Method sipApplicationKeyMethod) {
this.sipApplicationKeyMethod = sipApplicationKeyMethod;
}
public String getJbossBasePath() {
return getBasePath();
}
/**
* {@inheritDoc}
*/
public void addSipServletMapping(MobicentsSipServletMapping sipServletMapping) {
sipServletMappings.add(sipServletMapping);
isMainServlet = false;
if(servletHandler == null) {
servletHandler = sipServletMapping.getServletName();
}
}
/**
* {@inheritDoc}
*/
public List<MobicentsSipServletMapping> findSipServletMappings() {
return sipServletMappings;
}
/**
* {@inheritDoc}
*/
public MobicentsSipServletMapping findSipServletMappings(SipServletRequest sipServletRequest) {
if(logger.isDebugEnabled()) {
logger.debug("Checking sip Servlet Mapping for following request : " + sipServletRequest);
}
for (MobicentsSipServletMapping sipServletMapping : sipServletMappings) {
if(sipServletMapping.getMatchingRule().matches(sipServletRequest)) {
return sipServletMapping;
} else {
logger.debug("Following mapping rule didn't match : servletName => " +
sipServletMapping.getServletName() + " | expression = "+
sipServletMapping.getMatchingRule().getExpression());
}
}
return null;
}
/**
* {@inheritDoc}
*/
public void removeSipServletMapping(MobicentsSipServletMapping sipServletMapping) {
sipServletMappings.remove(sipServletMapping);
}
/**
* {@inheritDoc}
*/
public final SipManager getSipManager() {
return (SipManager)manager;
}
@Override
public String getInfo() {
return info;
}
/**
* Notifies the sip servlet listeners that the servlet has been initialized
* and that it is ready for service
* @param sipContext the sip context of the application where the listeners reside.
* @return true if all listeners have been notified correctly
*/
public boolean notifySipContextListeners(SipContextEvent event) {
boolean ok = true;
if(logger.isDebugEnabled()) {
logger.debug(childrenMap.size() + " container to notify of " + event.getEventType());
}
if(event.getEventType() == SipContextEventType.SERVLET_INITIALIZED) {
if(!timerService.isStarted()) {
timerService.start();
}
if(!proxyTimerService.isStarted()) {
proxyTimerService.start();
}
if(!sasTimerService.isStarted()) {
sasTimerService.start();
}
}
enterSipApp(null, null, false);
boolean batchStarted = enterSipAppHa(true);
try {
for (MobicentsSipServlet container : childrenMap.values()) {
if(logger.isDebugEnabled()) {
logger.debug("container " + container.getName() + ", class : " + container.getClass().getName());
}
if(container instanceof Wrapper) {
Wrapper wrapper = (Wrapper) container;
Servlet sipServlet = null;
try {
sipServlet = wrapper.allocate();
if(sipServlet instanceof SipServlet) {
// Fix for issue 1086 (http://code.google.com/p/mobicents/issues/detail?id=1086) :
// Cannot send a request in SipServletListener.initialize() for servlet-selection applications
boolean servletHandlerWasNull = false;
if(servletHandler == null) {
servletHandler = container.getName();
servletHandlerWasNull = true;
}
final ClassLoader oldClassLoader = Thread.currentThread().getContextClassLoader();
try {
final ClassLoader cl = getLoader().getClassLoader();
Thread.currentThread().setContextClassLoader(cl);
switch(event.getEventType()) {
case SERVLET_INITIALIZED : {
SipServletContextEvent sipServletContextEvent =
new SipServletContextEvent(getServletContext(), (SipServlet)sipServlet);
List<SipServletListener> sipServletListeners = sipListeners.getSipServletsListeners();
if(logger.isDebugEnabled()) {
logger.debug(sipServletListeners.size() + " SipServletListener to notify of servlet initialization");
}
for (SipServletListener sipServletListener : sipServletListeners) {
sipServletListener.servletInitialized(sipServletContextEvent);
}
break;
}
case SIP_CONNECTOR_ADDED : {
// reload the outbound interfaces if they have changed
this.getServletContext().setAttribute(javax.servlet.sip.SipServlet.OUTBOUND_INTERFACES,
sipApplicationDispatcher.getOutboundInterfaces());
List<SipConnectorListener> sipConnectorListeners = sipListeners.getSipConnectorListeners();
if(logger.isDebugEnabled()) {
logger.debug(sipConnectorListeners.size() + " SipConnectorListener to notify of sip connector addition");
}
for (SipConnectorListener sipConnectorListener : sipConnectorListeners) {
sipConnectorListener.sipConnectorAdded((SipConnector)event.getEventObject());
}
break;
}
case SIP_CONNECTOR_REMOVED : {
// reload the outbound interfaces if they have changed
this.getServletContext().setAttribute(javax.servlet.sip.SipServlet.OUTBOUND_INTERFACES,
sipApplicationDispatcher.getOutboundInterfaces());
List<SipConnectorListener> sipConnectorListeners = sipListeners.getSipConnectorListeners();
if(logger.isDebugEnabled()) {
logger.debug(sipConnectorListeners.size() + " SipConnectorListener to notify of sip connector removal");
}
for (SipConnectorListener sipConnectorListener : sipConnectorListeners) {
sipConnectorListener.sipConnectorRemoved((SipConnector)event.getEventObject());
}
break;
}
}
if(servletHandlerWasNull) {
servletHandler = null;
}
} finally {
Thread.currentThread().setContextClassLoader(oldClassLoader);
}
}
} catch (ServletException e) {
logger.error("Cannot allocate the servlet "+ wrapper.getServletClass() +" for notifying the listener " +
" of the event " + event.getEventType(), e);
ok = false;
} catch (Throwable e) {
logger.error("An error occured when notifying the servlet " + wrapper.getServletClass() +
" of the event " + event.getEventType(), e);
ok = false;
}
try {
if(sipServlet != null) {
wrapper.deallocate(sipServlet);
}
} catch (ServletException e) {
logger.error("Deallocate exception for servlet" + wrapper.getName(), e);
ok = false;
} catch (Throwable e) {
logger.error("Deallocate exception for servlet" + wrapper.getName(), e);
ok = false;
}
}
}
} finally {
exitSipAppHa(null, null, batchStarted);
exitSipApp(null, null);
}
return ok;
}
/*
* (non-Javadoc)
* @see org.mobicents.servlet.sip.startup.SipContext#enterSipApp(org.mobicents.servlet.sip.core.session.MobicentsSipApplicationSession, org.mobicents.servlet.sip.core.session.MobicentsSipSession, boolean)
*/
public void enterSipApp(MobicentsSipApplicationSession sipApplicationSession, MobicentsSipSession sipSession, boolean checkIsManagedThread) {
switch (concurrencyControlMode) {
case SipSession:
if(sipSession != null) {
sipSession.acquire();
}
break;
case SipApplicationSession:
if(logger.isDebugEnabled()) {
logger.debug("checkIsManagedThread " + checkIsManagedThread + " , isManagedThread " + isManagedThread.get());
}
// http://code.google.com/p/mobicents/issues/detail?id=2534 && http://code.google.com/p/mobicents/issues/detail?id=2526
if(!checkIsManagedThread || (checkIsManagedThread && Boolean.TRUE.equals(isManagedThread.get()))) {
if(isManagedThread.get() == null) {
isManagedThread.set(Boolean.TRUE);
}
if(sipApplicationSession != null) {
SipApplicationSessionCreationThreadLocal sipApplicationSessionCreationThreadLocal = sipApplicationSessionsAccessedThreadLocal.get();
if(sipApplicationSessionCreationThreadLocal == null) {
sipApplicationSessionCreationThreadLocal = new SipApplicationSessionCreationThreadLocal();
sipApplicationSessionsAccessedThreadLocal.set(sipApplicationSessionCreationThreadLocal);
}
boolean notPresent = sipApplicationSessionCreationThreadLocal.getSipApplicationSessions().add(sipApplicationSession);
if(notPresent) {
if(logger.isDebugEnabled()) {
logger.debug("acquiring sipApplicationSession=" + sipApplicationSession +
" since it is not present in our local thread of accessed sip application sessions " );
}
sipApplicationSession.acquire();
} else {
if(logger.isDebugEnabled()) {
logger.debug("not acquiring sipApplicationSession=" + sipApplicationSession +
" since it is present in our local thread of accessed sip application sessions ");
}
}
}
} else {
if(logger.isDebugEnabled()) {
logger.debug("not acquiring sipApplicationSession=" + sipApplicationSession +
" since isManagedThread is " + isManagedThread.get());
}
}
break;
case None:
break;
}
}
/*
* (non-Javadoc)
* @see org.mobicents.servlet.sip.startup.SipContext#exitSipApp(org.mobicents.servlet.sip.core.session.MobicentsSipApplicationSession, org.mobicents.servlet.sip.core.session.MobicentsSipSession)
*/
public void exitSipApp(MobicentsSipApplicationSession sipApplicationSession, MobicentsSipSession sipSession) {
switch (concurrencyControlMode) {
case SipSession:
if(sipSession != null) {
sipSession.release();
} else {
if(logger.isDebugEnabled()) {
logger.debug("NOT RELEASING SipSession on exit sipApplicationSession=" + sipApplicationSession +
" sipSession=" + sipSession + " semaphore=null");
}
}
break;
case SipApplicationSession:
boolean wasSessionReleased = false;
SipApplicationSessionCreationThreadLocal sipApplicationSessionCreationThreadLocal = sipApplicationSessionsAccessedThreadLocal.get();
if(sipApplicationSessionCreationThreadLocal != null) {
for(MobicentsSipApplicationSession sipApplicationSessionAccessed : sipApplicationSessionsAccessedThreadLocal.get().getSipApplicationSessions()) {
sipApplicationSessionAccessed.release();
if(sipApplicationSessionAccessed.equals(sipApplicationSession)) {
wasSessionReleased = true;
}
}
sipApplicationSessionsAccessedThreadLocal.get().getSipApplicationSessions().clear();
sipApplicationSessionsAccessedThreadLocal.set(null);
sipApplicationSessionsAccessedThreadLocal.remove();
}
isManagedThread.set(null);
isManagedThread.remove();
if(!wasSessionReleased) {
if(sipApplicationSession != null) {
sipApplicationSession.release();
} else {
if(logger.isDebugEnabled()) {
logger.debug("NOT RELEASING SipApplicationSession on exit sipApplicationSession=" + sipApplicationSession +
" sipSession=" + sipSession + " semaphore=null");
}
}
}
break;
case None:
break;
}
}
public ConcurrencyControlMode getConcurrencyControlMode() {
return concurrencyControlMode;
}
public void setConcurrencyControlMode(ConcurrencyControlMode mode) {
this.concurrencyControlMode = mode;
if(concurrencyControlMode != null && logger.isInfoEnabled()) {
logger.info("Concurrency Control set to " + concurrencyControlMode.toString() + " for application " + applicationName);
}
}
public SipRubyController getSipRubyController() {
return null;
}
public void setSipRubyController(SipRubyController rubyController) {
throw new UnsupportedOperationException("ruby applications are not supported on Tomcat or JBoss 4.X versions");
}
public SipApplicationSessionTimerService getSipApplicationSessionTimerService() {
return sasTimerService;
}
public boolean hasDistributableManager() {
return hasDistributableManager;
}
/**
* @return the servletHandler
*/
public String getServletHandler() {
return servletHandler;
}
/**
* @param servletHandler the servletHandler to set
*/
public void setServletHandler(String servletHandler) {
this.servletHandler = servletHandler;
}
@Override
public String getEngineName() {
// TODO Auto-generated method stub
return null;
}
/*
* (non-Javadoc)
* @see org.mobicents.servlet.sip.core.SipContext#enterSipAppHa(boolean)
*/
@Override
public boolean enterSipAppHa(boolean startCacheActivity) {
// we don't support ha features, so nothing to do here
return false;
}
@Override
public void exitSipAppHa(MobicentsSipServletRequest request, MobicentsSipServletResponse response, boolean batchStarted) {
// we don't support ha features, so nothing to do here
}
/**
* Copied from Tomcat 7 StandardContext
*
* @param namingResources
* @return injectionMap
*/
private Map<String, Map<String, String>> buildInjectionMap(NamingResources namingResources) {
Map<String, Map<String, String>> injectionMap = new HashMap<String, Map<String, String>>();
for (Injectable resource: namingResources.findLocalEjbs()) {
addInjectionTarget(resource, injectionMap);
}
for (Injectable resource: namingResources.findEjbs()) {
addInjectionTarget(resource, injectionMap);
}
for (Injectable resource: namingResources.findEnvironments()) {
addInjectionTarget(resource, injectionMap);
}
for (Injectable resource: namingResources.findMessageDestinationRefs()) {
addInjectionTarget(resource, injectionMap);
}
for (Injectable resource: namingResources.findResourceEnvRefs()) {
addInjectionTarget(resource, injectionMap);
}
for (Injectable resource: namingResources.findResources()) {
addInjectionTarget(resource, injectionMap);
}
for (Injectable resource: namingResources.findServices()) {
addInjectionTarget(resource, injectionMap);
}
return injectionMap;
}
/**
* Copied from Tomcat 7 StandardContext
*
* @param resource
* @param injectionMap
*/
private void addInjectionTarget(Injectable resource, Map<String, Map<String, String>> injectionMap) {
List<InjectionTarget> injectionTargets = resource.getInjectionTargets();
if (injectionTargets != null && injectionTargets.size() > 0) {
String jndiName = resource.getName();
for (InjectionTarget injectionTarget: injectionTargets) {
String clazz = injectionTarget.getTargetClass();
Map<String, String> injections = injectionMap.get(clazz);
if (injections == null) {
injections = new HashMap<String, String>();
injectionMap.put(clazz, injections);
}
injections.put(injectionTarget.getTargetName(), jndiName);
}
}
}
@Override
public SipInstanceManager getSipInstanceManager() {
return (SipInstanceManager) super.getInstanceManager();
}
@Override
public void setInstanceManager(InstanceManager instanceManager) {
super.setInstanceManager(instanceManager);
}
public ClassLoader getSipContextClassLoader() {
return getLoader().getClassLoader();
}
public boolean isPackageProtectionEnabled() {
return SecurityUtil.isPackageProtectionEnabled();
}
public boolean authorize(MobicentsSipServletRequest request) {
return sipSecurityUtils.authorize(request);
}
public SipDigestAuthenticator getDigestAuthenticator() {
return sipDigestAuthenticator;
}
}
| true | true | public synchronized void startInternal() throws LifecycleException {
if(logger.isInfoEnabled()) {
logger.info("Starting the sip context");
}
// if( this.getState().equals(LifecycleState.INITIALIZED)) {
prepareServletContext();
// }
// Add missing components as necessary
boolean ok = true;
if (getResources() == null) { // (1) Required by Loader
if (logger.isDebugEnabled())
logger.debug("Configuring default Resources");
try {
if ((getDocBase() != null) && (getDocBase().endsWith(".war")) && (!(new File(getBasePath())).isDirectory()))
setResources(new WARDirContext());
if ((getDocBase() != null) && (getDocBase().endsWith(".sar")) && (!(new File(getBasePath())).isDirectory()))
setResources(new SARDirContext());
else
setResources(new FileDirContext());
} catch (IllegalArgumentException e) {
logger.error("Error initializing resources: " + e.getMessage());
ok = false;
}
}
if (ok) {
if (!resourcesStart()) {
logger.error( "Error in resourceStart()");
ok = false;
}
}
// Configure default manager if none was specified
if (manager == null) {
if ((getCluster() != null) && getDistributable()) {
try {
manager = getCluster().createManager(getName());
} catch (Exception ex) {
logger.error("standardContext.clusterFail", ex);
// ok = false;
}
} else {
setManager(new SipStandardManager());
}
}
// Reading the "catalina.useNaming" environment variable
String useNamingProperty = System.getProperty("catalina.useNaming");
if ((useNamingProperty != null)
&& (useNamingProperty.equals("false"))) {
setUseNaming(false);
}
// the loader is needed for creating the DefaultSipInstanceManager
if (getLoader() == null) {
WebappLoader webappLoader = new WebappLoader(getParentClassLoader());
webappLoader.setDelegate(getDelegate());
setLoader(webappLoader);
webappLoader.start();
// Report this property change to interested listeners
support.firePropertyChange("loader", null, webappLoader);
}
//activating our custom naming context to be able to set the sip factory in JNDI
if (isUseNaming()) {
if (getNamingContextListener() == null) {
NamingContextListener namingContextListener = new SipNamingContextListener();
namingContextListener.setName(getNamingContextName());
setNamingContextListener(namingContextListener);
addLifecycleListener(namingContextListener);
addContainerListener(namingContextListener);
}
// Replace the default annotation processor. This is needed to handle resource injection
// for SipFactory, Session utils and other objects residing in the servlet context space.
// Of course if the variable is not found in in the servet context it defaults to the
// normal lookup method - in the default naming context.
//tomcat naming
Map<String, Map<String, String>> injectionMap = buildInjectionMap(
getIgnoreAnnotations() ? new NamingResources(): getNamingResources());
this.setInstanceManager(
new DefaultSipInstanceManager(
getNamingContextListener().getEnvContext(),
injectionMap, this, this.getClass().getClassLoader()));
} else {
// jboss or other kind of naming
try {
Map<String, Map<String, String>> injectionMap = buildInjectionMap(
getIgnoreAnnotations() ? new NamingResources(): getNamingResources());
InitialContext iniCtx = new InitialContext();
Context envCtx = (Context) iniCtx.lookup("java:comp/env");
this.setInstanceManager(
new DefaultSipInstanceManager(
envCtx,
injectionMap, this, this.getClass().getClassLoader()));
} catch (NamingException e) {
logger.error("Impossible to get the naming context ", e);
}
}
//JSR 289 Section 2.1.1 Step 1.Deploy the application.
//This will make start the sip context config, which will in turn parse the sip descriptor deployment
//and call load on startup which is equivalent to
//JSR 289 Section 2.1.1 Step 2.Invoke servlet.init(), the initialization method on the Servlet. Invoke the init() on all the load-on-startup Servlets in the application
super.startInternal();
if(getAvailable()) {
// Replace the default annotation processor. This is needed to handle resource injection
// for SipFactory, Session utils and other objects residing in the servlet context space.
// Of course if the variable is not found in in the servet context it defaults to the
// normal lookup method - in the default naming context.
if(getInstanceManager() == null || !(getInstanceManager() instanceof SipInstanceManager)) {
if(isUseNaming()) {
//tomcat naming
Map<String, Map<String, String>> injectionMap = buildInjectionMap(
getIgnoreAnnotations() ? new NamingResources(): getNamingResources());
this.setInstanceManager(
new DefaultSipInstanceManager(
getNamingContextListener().getEnvContext(),
injectionMap, this, this.getClass().getClassLoader()));
} else {
// jboss or other kind of naming
try {
Map<String, Map<String, String>> injectionMap = buildInjectionMap(
getIgnoreAnnotations() ? new NamingResources(): getNamingResources());
InitialContext iniCtx = new InitialContext();
Context envCtx = (Context) iniCtx.lookup("java:comp/env");
this.setInstanceManager(
new DefaultSipInstanceManager(
envCtx,
injectionMap, this, this.getClass().getClassLoader()));
} catch (NamingException e) {
logger.error("Impossible to get the naming context ", e);
}
}
}
getServletContext().setAttribute(InstanceManager.class.getName(), getInstanceManager());
//set the session manager on the specific sipstandardmanager to handle converged http sessions
if(getManager() instanceof SipManager) {
((SipManager)getManager()).setMobicentsSipFactory(
sipApplicationDispatcher.getSipFactory());
((CatalinaSipManager)manager).setContainer(this);
}
// JSR 289 16.2 Servlet Selection
// When using this mechanism (the main-servlet) for servlet selection,
// if there is only one servlet in the application then this
// declaration is optional and the lone servlet becomes the main servlet
if((mainServlet == null || mainServlet.length() < 1) && childrenMap.size() == 1) {
setMainServlet(childrenMap.keySet().iterator().next());
}
sipSecurityUtils = new SipSecurityUtils(this);
sipDigestAuthenticator = new DigestAuthenticator(sipApplicationDispatcher.getSipFactory().getHeaderFactory());
//JSR 289 Section 2.1.1 Step 3.Invoke SipApplicationRouter.applicationDeployed() for this application.
//called implicitly within sipApplicationDispatcher.addSipApplication
sipApplicationDispatcher.addSipApplication(applicationName, this);
if(manager instanceof DistributableSipManager) {
hasDistributableManager = true;
if(logger.isInfoEnabled()) {
logger.info("this context contains a manager that allows applications to work in a distributed environment");
}
}
if(logger.isInfoEnabled()) {
logger.info("sip application session timeout for this context is " + sipApplicationSessionTimeout + " minutes");
}
if(logger.isInfoEnabled()) {
logger.info("sip context started");
}
} else {
if(logger.isInfoEnabled()) {
logger.info("sip context didn't started due to errors");
}
}
}
| public synchronized void startInternal() throws LifecycleException {
if(logger.isInfoEnabled()) {
logger.info("Starting the sip context");
}
// if( this.getState().equals(LifecycleState.INITIALIZED)) {
prepareServletContext();
// }
// Add missing components as necessary
boolean ok = true;
if (getResources() == null) { // (1) Required by Loader
if (logger.isDebugEnabled())
logger.debug("Configuring default Resources");
try {
if ((getDocBase() != null) && (getDocBase().endsWith(".war")) && (!(new File(getBasePath())).isDirectory()))
setResources(new WARDirContext());
if ((getDocBase() != null) && (getDocBase().endsWith(".sar")) && (!(new File(getBasePath())).isDirectory()))
setResources(new SARDirContext());
else
setResources(new FileDirContext());
} catch (IllegalArgumentException e) {
logger.error("Error initializing resources: " + e.getMessage());
ok = false;
}
}
if (ok) {
if (!resourcesStart()) {
logger.error( "Error in resourceStart()");
ok = false;
}
}
// Configure default manager if none was specified
if (manager == null) {
if ((getCluster() != null) && getDistributable()) {
try {
manager = getCluster().createManager(getName());
} catch (Exception ex) {
logger.error("standardContext.clusterFail", ex);
// ok = false;
}
} else {
setManager(new SipStandardManager());
}
}
// Reading the "catalina.useNaming" environment variable
String useNamingProperty = System.getProperty("catalina.useNaming");
if ((useNamingProperty != null)
&& (useNamingProperty.equals("false"))) {
setUseNaming(false);
}
// the loader is needed for creating the DefaultSipInstanceManager
if (getLoader() == null) {
WebappLoader webappLoader = new WebappLoader(getParentClassLoader());
webappLoader.setDelegate(getDelegate());
setLoader(webappLoader);
webappLoader.start();
// Report this property change to interested listeners
support.firePropertyChange("loader", null, webappLoader);
} else {
WebappLoader loader = (WebappLoader) getLoader();
loader.setDelegate(getDelegate());
setLoader(loader);
loader.start();
// Report this property change to interested listeners
support.firePropertyChange("loader", null, loader);
}
//activating our custom naming context to be able to set the sip factory in JNDI
if (isUseNaming()) {
if (getNamingContextListener() == null) {
NamingContextListener namingContextListener = new SipNamingContextListener();
namingContextListener.setName(getNamingContextName());
setNamingContextListener(namingContextListener);
addLifecycleListener(namingContextListener);
addContainerListener(namingContextListener);
}
// Replace the default annotation processor. This is needed to handle resource injection
// for SipFactory, Session utils and other objects residing in the servlet context space.
// Of course if the variable is not found in in the servet context it defaults to the
// normal lookup method - in the default naming context.
//tomcat naming
Map<String, Map<String, String>> injectionMap = buildInjectionMap(
getIgnoreAnnotations() ? new NamingResources(): getNamingResources());
this.setInstanceManager(
new DefaultSipInstanceManager(
getNamingContextListener().getEnvContext(),
injectionMap, this, this.getClass().getClassLoader()));
} else {
// jboss or other kind of naming
try {
Map<String, Map<String, String>> injectionMap = buildInjectionMap(
getIgnoreAnnotations() ? new NamingResources(): getNamingResources());
InitialContext iniCtx = new InitialContext();
Context envCtx = (Context) iniCtx.lookup("java:comp/env");
this.setInstanceManager(
new DefaultSipInstanceManager(
envCtx,
injectionMap, this, this.getClass().getClassLoader()));
} catch (NamingException e) {
logger.error("Impossible to get the naming context ", e);
}
}
//JSR 289 Section 2.1.1 Step 1.Deploy the application.
//This will make start the sip context config, which will in turn parse the sip descriptor deployment
//and call load on startup which is equivalent to
//JSR 289 Section 2.1.1 Step 2.Invoke servlet.init(), the initialization method on the Servlet. Invoke the init() on all the load-on-startup Servlets in the application
super.startInternal();
if(getAvailable()) {
// Replace the default annotation processor. This is needed to handle resource injection
// for SipFactory, Session utils and other objects residing in the servlet context space.
// Of course if the variable is not found in in the servet context it defaults to the
// normal lookup method - in the default naming context.
if(getInstanceManager() == null || !(getInstanceManager() instanceof SipInstanceManager)) {
if(isUseNaming()) {
//tomcat naming
Map<String, Map<String, String>> injectionMap = buildInjectionMap(
getIgnoreAnnotations() ? new NamingResources(): getNamingResources());
this.setInstanceManager(
new DefaultSipInstanceManager(
getNamingContextListener().getEnvContext(),
injectionMap, this, this.getClass().getClassLoader()));
} else {
// jboss or other kind of naming
try {
Map<String, Map<String, String>> injectionMap = buildInjectionMap(
getIgnoreAnnotations() ? new NamingResources(): getNamingResources());
InitialContext iniCtx = new InitialContext();
Context envCtx = (Context) iniCtx.lookup("java:comp/env");
this.setInstanceManager(
new DefaultSipInstanceManager(
envCtx,
injectionMap, this, this.getClass().getClassLoader()));
} catch (NamingException e) {
logger.error("Impossible to get the naming context ", e);
}
}
}
getServletContext().setAttribute(InstanceManager.class.getName(), getInstanceManager());
//set the session manager on the specific sipstandardmanager to handle converged http sessions
if(getManager() instanceof SipManager) {
((SipManager)getManager()).setMobicentsSipFactory(
sipApplicationDispatcher.getSipFactory());
((CatalinaSipManager)manager).setContainer(this);
}
// JSR 289 16.2 Servlet Selection
// When using this mechanism (the main-servlet) for servlet selection,
// if there is only one servlet in the application then this
// declaration is optional and the lone servlet becomes the main servlet
if((mainServlet == null || mainServlet.length() < 1) && childrenMap.size() == 1) {
setMainServlet(childrenMap.keySet().iterator().next());
}
sipSecurityUtils = new SipSecurityUtils(this);
sipDigestAuthenticator = new DigestAuthenticator(sipApplicationDispatcher.getSipFactory().getHeaderFactory());
//JSR 289 Section 2.1.1 Step 3.Invoke SipApplicationRouter.applicationDeployed() for this application.
//called implicitly within sipApplicationDispatcher.addSipApplication
sipApplicationDispatcher.addSipApplication(applicationName, this);
if(manager instanceof DistributableSipManager) {
hasDistributableManager = true;
if(logger.isInfoEnabled()) {
logger.info("this context contains a manager that allows applications to work in a distributed environment");
}
}
if(logger.isInfoEnabled()) {
logger.info("sip application session timeout for this context is " + sipApplicationSessionTimeout + " minutes");
}
if(logger.isInfoEnabled()) {
logger.info("sip context started");
}
} else {
if(logger.isInfoEnabled()) {
logger.info("sip context didn't started due to errors");
}
}
}
|
diff --git a/components/bio-formats/src/loci/formats/tiff/TiffSaver.java b/components/bio-formats/src/loci/formats/tiff/TiffSaver.java
index fbca5c28f..1af72f4ee 100644
--- a/components/bio-formats/src/loci/formats/tiff/TiffSaver.java
+++ b/components/bio-formats/src/loci/formats/tiff/TiffSaver.java
@@ -1,825 +1,826 @@
//
// TiffSaver.java
//
/*
OME Bio-Formats package for reading and converting biological file formats.
Copyright (C) 2005-@year@ UW-Madison LOCI and Glencoe Software, Inc.
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 loci.formats.tiff;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.TreeSet;
import loci.common.ByteArrayHandle;
import loci.common.RandomAccessInputStream;
import loci.common.RandomAccessOutputStream;
import loci.formats.FormatException;
import loci.formats.FormatTools;
import loci.formats.codec.CodecOptions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Parses TIFF data from an input source.
*
* <dl><dt><b>Source code:</b></dt>
* <dd><a href="http://trac.openmicroscopy.org.uk/ome/browser/bioformats.git/components/bio-formats/src/loci/formats/tiff/TiffSaver.java">Trac</a>,
* <a href="http://git.openmicroscopy.org/?p=bioformats.git;a=blob;f=components/bio-formats/src/loci/formats/tiff/TiffSaver.java;hb=HEAD">Gitweb</a></dd></dl>
*
* @author Curtis Rueden ctrueden at wisc.edu
* @author Eric Kjellman egkjellman at wisc.edu
* @author Melissa Linkert melissa at glencoesoftware.com
* @author Chris Allan callan at blackcat.ca
*/
public class TiffSaver {
// -- Constructor --
private static final Logger LOGGER = LoggerFactory.getLogger(TiffSaver.class);
// -- Fields --
/** Output stream to use when saving TIFF data. */
protected RandomAccessOutputStream out;
/** Input stream to use when overwriting data. */
protected RandomAccessInputStream in;
/** Whether or not to write BigTIFF data. */
private boolean bigTiff = false;
private boolean sequentialWrite = false;
/** The codec options if set. */
private CodecOptions options;
// -- Constructors --
/** Constructs a new TIFF saver from the given output source. */
public TiffSaver(RandomAccessOutputStream out) {
if (out == null) {
throw new IllegalArgumentException(
"Output stream expected to be not-null");
}
this.out = out;
}
/**
* Creates a new instance.
* @param filename The name of the file for output.
* @throws IOException
*/
public TiffSaver(String filename) throws IOException {
this(new RandomAccessOutputStream(filename));
}
// -- TiffSaver methods --
/**
* Sets whether or not we know that the planes will be written sequentially.
* If we are writing planes sequentially and set this flag, then performance
* is slightly improved.
*/
public void setWritingSequentially(boolean sequential) {
sequentialWrite = sequential;
}
/** Sets the input stream. */
public void setInputStream(RandomAccessInputStream in) {
this.in = in;
}
/** Gets the stream from which TIFF data is being saved. */
public RandomAccessOutputStream getStream() {
return out;
}
/** Sets whether or not little-endian data should be written. */
public void setLittleEndian(boolean littleEndian) {
out.order(littleEndian);
}
/** Sets whether or not BigTIFF data should be written. */
public void setBigTiff(boolean bigTiff) {
this.bigTiff = bigTiff;
}
/** Returns whether or not we are writing little-endian data. */
public boolean isLittleEndian() {
return out.isLittleEndian();
}
/** Returns whether or not we are writing BigTIFF data. */
public boolean isBigTiff() { return bigTiff; }
/**
* Sets the codec options.
* @param options The value to set.
*/
public void setCodecOptions(CodecOptions options) {
this.options = options;
}
/** Writes the TIFF file header. */
public void writeHeader() throws IOException {
// write endianness indicator
if (isLittleEndian()) {
out.writeByte(TiffConstants.LITTLE);
out.writeByte(TiffConstants.LITTLE);
}
else {
out.writeByte(TiffConstants.BIG);
out.writeByte(TiffConstants.BIG);
}
// write magic number
if (bigTiff) {
out.writeShort(TiffConstants.BIG_TIFF_MAGIC_NUMBER);
}
else out.writeShort(TiffConstants.MAGIC_NUMBER);
// write the offset to the first IFD
// for vanilla TIFFs, 8 is the offset to the first IFD
// for BigTIFFs, 8 is the number of bytes in an offset
out.writeInt(8);
if (bigTiff) {
// write the offset to the first IFD for BigTIFF files
out.writeLong(16);
}
}
/**
*/
public void writeImage(byte[][] buf, IFDList ifds, int pixelType)
throws FormatException, IOException
{
if (ifds == null) {
throw new FormatException("IFD cannot be null");
}
if (buf == null) {
throw new FormatException("Image data cannot be null");
}
for (int i=0; i<ifds.size(); i++) {
if (i < buf.length) {
writeImage(buf[i], ifds.get(i), i, pixelType, i == ifds.size() - 1);
}
}
}
/**
*/
public void writeImage(byte[] buf, IFD ifd, int no, int pixelType,
boolean last)
throws FormatException, IOException
{
if (ifd == null) {
throw new FormatException("IFD cannot be null");
}
int w = (int) ifd.getImageWidth();
int h = (int) ifd.getImageLength();
writeImage(buf, ifd, no, pixelType, 0, 0, w, h, last);
}
/**
* Writes to any rectangle from the passed block.
*
* @param buf The block that is to be written.
* @param ifd The Image File Directories. Mustn't be <code>null</code>.
* @param no The image index within the current file, starting from 0.
* @param pixelType The type of pixels.
* @param x The X-coordinate of the top-left corner.
* @param y The Y-coordinate of the top-left corner.
* @param w The width of the rectangle.
* @param h The height of the rectangle.
* @param last Pass <code>true</code> if it is the last image,
* <code>false</code> otherwise.
* @throws FormatException
* @throws IOException
*/
public void writeImage(byte[] buf, IFD ifd, int no, int pixelType, int x,
int y, int w, int h, boolean last)
throws FormatException, IOException
{
LOGGER.debug("Attempting to write image.");
//b/c method is public should check parameters again
if (buf == null) {
throw new FormatException("Image data cannot be null");
}
if (in == null) {
throw new FormatException("RandomAccessInputStream is null. " +
"Call setInputStream(RandomAccessInputStream) first.");
}
if (ifd == null) {
throw new FormatException("IFD cannot be null");
}
int bytesPerPixel = FormatTools.getBytesPerPixel(pixelType);
int blockSize = w * h * bytesPerPixel;
int nChannels = buf.length / (w * h * bytesPerPixel);
boolean interleaved = ifd.getPlanarConfiguration() == 1;
boolean isTiled = ifd.isTiled();
makeValidIFD(ifd, pixelType, nChannels);
// create pixel output buffers
TiffCompression compression = ifd.getCompression();
int tileWidth = (int) ifd.getTileWidth();
int tileHeight = (int) ifd.getTileLength();
int tilesPerRow = (int) ifd.getTilesPerRow();
int tilesPerColumn = (int) ifd.getTilesPerColumn();
int rowsPerStrip = (int) ifd.getRowsPerStrip()[0];
int stripSize = rowsPerStrip * tileWidth * bytesPerPixel;
- int nStrips = (w / tileWidth) * (h / tileHeight);
+ int nStrips = ((w + tileWidth - 1) / tileWidth)
+ * ((h + tileHeight - 1) / tileHeight);
if (interleaved) stripSize *= nChannels;
else nStrips *= nChannels;
ByteArrayOutputStream[] stripBuf = new ByteArrayOutputStream[nStrips];
DataOutputStream[] stripOut = new DataOutputStream[nStrips];
for (int strip=0; strip<nStrips; strip++) {
stripBuf[strip] = new ByteArrayOutputStream(stripSize);
stripOut[strip] = new DataOutputStream(stripBuf[strip]);
}
int[] bps = ifd.getBitsPerSample();
int off;
// write pixel strips to output buffers
for (int strip = 0; strip < nStrips; strip++) {
x = (strip % tilesPerRow) * tileWidth;
y = (strip / tilesPerRow) * tileHeight;
for (int row=0; row<tileHeight; row++) {
for (int col=0; col<tileWidth; col++) {
int ndx = ((row+y) * w + col +x) * bytesPerPixel;
for (int c=0; c<nChannels; c++) {
for (int n=0; n<bps[c]/8; n++) {
if (interleaved) {
off = ndx + c * blockSize + n;
if (row >= h || col >= w) {
stripOut[strip].writeByte(0);
} else {
stripOut[strip].writeByte(buf[off]);
}
}
else {
off = c * blockSize + ndx + n;
if (row >= h || col >= w) {
stripOut[strip].writeByte(0);
} else {
stripOut[c * (nStrips / nChannels) + strip].writeByte(
buf[off]);
}
}
}
}
}
}
}
// compress strips according to given differencing and compression schemes
byte[][] strips = new byte[nStrips][];
for (int strip=0; strip<nStrips; strip++) {
strips[strip] = stripBuf[strip].toByteArray();
TiffCompression.difference(strips[strip], ifd);
CodecOptions codecOptions = compression.getCompressionCodecOptions(
ifd, options);
codecOptions.height = tileHeight;
codecOptions.width = tileWidth;
strips[strip] = compression.compress(strips[strip], codecOptions);
}
if (!sequentialWrite) {
TiffParser parser = new TiffParser(in);
long[] ifdOffsets = parser.getIFDOffsets();
if (no < ifdOffsets.length) {
out.seek(ifdOffsets[no]);
ifd = parser.getIFD(ifdOffsets[no]);
}
}
// record strip byte counts and offsets
List<Long> byteCounts = new ArrayList<Long>();
List<Long> offsets = new ArrayList<Long>();
long totalTiles = tilesPerRow * tilesPerColumn;
if (ifd.containsKey(IFD.STRIP_BYTE_COUNTS)
|| ifd.containsKey(IFD.TILE_BYTE_COUNTS)) {
long[] ifdByteCounts = isTiled? ifd.getIFDLongArray(IFD.TILE_BYTE_COUNTS)
: ifd.getStripByteCounts();
for (long stripByteCount : ifdByteCounts) {
byteCounts.add(stripByteCount);
}
}
else {
while (byteCounts.size() < totalTiles) {
byteCounts.add(0L);
}
}
Integer lastOffset = null;
if (ifd.containsKey(IFD.STRIP_OFFSETS)
|| ifd.containsKey(IFD.TILE_OFFSETS)) {
long[] ifdOffsets = isTiled? ifd.getIFDLongArray(IFD.TILE_OFFSETS)
: ifd.getStripOffsets();
for (int i = 0; i < ifdOffsets.length; i++) {
if (lastOffset == null && ifdOffsets[i] == 0L) {
lastOffset = i - 1;
}
offsets.add(ifdOffsets[i]);
}
}
else {
while (offsets.size() < totalTiles) {
offsets.add(0L);
}
lastOffset = -1;
}
if (isTiled) {
ifd.putIFDValue(IFD.TILE_BYTE_COUNTS, toPrimitiveArray(byteCounts));
ifd.putIFDValue(IFD.TILE_OFFSETS, toPrimitiveArray(offsets));
}
else {
ifd.putIFDValue(IFD.STRIP_BYTE_COUNTS, toPrimitiveArray(byteCounts));
ifd.putIFDValue(IFD.STRIP_OFFSETS, toPrimitiveArray(offsets));
}
long fp = out.getFilePointer();
writeIFD(ifd, 0);
for (int i=0; i<strips.length; i++) {
if (lastOffset != -1) {
out.seek(offsets.get(lastOffset) + byteCounts.get(lastOffset));
}
int thisOffset = lastOffset + i + 1;
offsets.set(thisOffset, out.getFilePointer());
byteCounts.set(thisOffset, new Long(strips[i].length));
if (LOGGER.isDebugEnabled()) {
LOGGER.debug(String.format(
"Writing tile/strip %d/%d size: %d offset: %d",
thisOffset + 1, totalTiles, byteCounts.get(thisOffset),
offsets.get(thisOffset)));
}
out.write(strips[i]);
}
if (isTiled) {
ifd.putIFDValue(IFD.TILE_BYTE_COUNTS, toPrimitiveArray(byteCounts));
ifd.putIFDValue(IFD.TILE_OFFSETS, toPrimitiveArray(offsets));
}
else {
ifd.putIFDValue(IFD.STRIP_BYTE_COUNTS, toPrimitiveArray(byteCounts));
ifd.putIFDValue(IFD.STRIP_OFFSETS, toPrimitiveArray(offsets));
}
long endFP = out.getFilePointer();
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Offset before IFD write: {} Seeking to: {}",
out.getFilePointer(), fp);
}
out.seek(fp);
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Writing tile/strip offsets: {}",
Arrays.toString(toPrimitiveArray(offsets)));
LOGGER.debug("Writing tile/strip byte counts: {}",
Arrays.toString(toPrimitiveArray(byteCounts)));
}
writeIFD(ifd, last ? 0 : endFP);
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Offset after IFD write: {}", out.getFilePointer());
}
}
public void writeIFD(IFD ifd, long nextOffset)
throws FormatException, IOException
{
TreeSet<Integer> keys = new TreeSet<Integer>(ifd.keySet());
int keyCount = keys.size();
if (ifd.containsKey(new Integer(IFD.LITTLE_ENDIAN))) keyCount--;
if (ifd.containsKey(new Integer(IFD.BIG_TIFF))) keyCount--;
if (ifd.containsKey(new Integer(IFD.REUSE))) keyCount--;
long fp = out.getFilePointer();
int bytesPerEntry = bigTiff ? TiffConstants.BIG_TIFF_BYTES_PER_ENTRY :
TiffConstants.BYTES_PER_ENTRY;
int ifdBytes = (bigTiff ? 16 : 6) + bytesPerEntry * keyCount;
if (bigTiff) out.writeLong(keyCount);
else out.writeShort(keyCount);
ByteArrayHandle extra = new ByteArrayHandle();
RandomAccessOutputStream extraStream = new RandomAccessOutputStream(extra);
for (Integer key : keys) {
if (key.equals(IFD.LITTLE_ENDIAN) || key.equals(IFD.BIG_TIFF) ||
key.equals(IFD.REUSE)) continue;
Object value = ifd.get(key);
writeIFDValue(extraStream, ifdBytes + fp, key.intValue(), value);
}
if (bigTiff) out.seek(out.getFilePointer() - 8);
writeIntValue(out, nextOffset);
out.write(extra.getBytes(), 0, (int) extra.length());
}
/**
* Writes the given IFD value to the given output object.
* @param extraOut buffer to which "extra" IFD information should be written
* @param offset global offset to use for IFD offset values
* @param tag IFD tag to write
* @param value IFD value to write
*/
public void writeIFDValue(RandomAccessOutputStream extraOut, long offset,
int tag, Object value)
throws FormatException, IOException
{
extraOut.order(isLittleEndian());
// convert singleton objects into arrays, for simplicity
if (value instanceof Short) {
value = new short[] {((Short) value).shortValue()};
}
else if (value instanceof Integer) {
value = new int[] {((Integer) value).intValue()};
}
else if (value instanceof Long) {
value = new long[] {((Long) value).longValue()};
}
else if (value instanceof TiffRational) {
value = new TiffRational[] {(TiffRational) value};
}
else if (value instanceof Float) {
value = new float[] {((Float) value).floatValue()};
}
else if (value instanceof Double) {
value = new double[] {((Double) value).doubleValue()};
}
int dataLength = bigTiff ? 8 : 4;
// write directory entry to output buffers
out.writeShort(tag); // tag
if (value instanceof short[]) {
short[] q = (short[]) value;
out.writeShort(IFDType.BYTE.getCode());
writeIntValue(out, q.length);
if (q.length <= dataLength) {
for (int i=0; i<q.length; i++) out.writeByte(q[i]);
for (int i=q.length; i<dataLength; i++) out.writeByte(0);
}
else {
writeIntValue(out, offset + extraOut.length());
for (int i=0; i<q.length; i++) extraOut.writeByte(q[i]);
}
}
else if (value instanceof String) { // ASCII
char[] q = ((String) value).toCharArray();
out.writeShort(IFDType.ASCII.getCode()); // type
writeIntValue(out, q.length + 1);
if (q.length < dataLength) {
for (int i=0; i<q.length; i++) out.writeByte(q[i]); // value(s)
for (int i=q.length; i<dataLength; i++) out.writeByte(0); // padding
}
else {
writeIntValue(out, offset + extraOut.length());
for (int i=0; i<q.length; i++) extraOut.writeByte(q[i]); // values
extraOut.writeByte(0); // concluding NULL byte
}
}
else if (value instanceof int[]) { // SHORT
int[] q = (int[]) value;
out.writeShort(IFDType.SHORT.getCode()); // type
writeIntValue(out, q.length);
if (q.length <= dataLength / 2) {
for (int i=0; i<q.length; i++) {
out.writeShort(q[i]); // value(s)
}
for (int i=q.length; i<dataLength / 2; i++) {
out.writeShort(0); // padding
}
}
else {
writeIntValue(out, offset + extraOut.length());
for (int i=0; i<q.length; i++) {
extraOut.writeShort(q[i]); // values
}
}
}
else if (value instanceof long[]) { // LONG
long[] q = (long[]) value;
int type = bigTiff ? IFDType.LONG8.getCode() : IFDType.LONG.getCode();
out.writeShort(type);
writeIntValue(out, q.length);
if (q.length <= dataLength / 4) {
for (int i=0; i<q.length; i++) {
writeIntValue(out, q[0]);
}
for (int i=q.length; i<dataLength / 4; i++) {
writeIntValue(out, 0);
}
}
else {
writeIntValue(out, offset + extraOut.length());
for (int i=0; i<q.length; i++) {
writeIntValue(extraOut, q[i]);
}
}
}
else if (value instanceof TiffRational[]) { // RATIONAL
TiffRational[] q = (TiffRational[]) value;
out.writeShort(IFDType.RATIONAL.getCode()); // type
writeIntValue(out, q.length);
if (bigTiff && q.length == 1) {
out.writeInt((int) q[0].getNumerator());
out.writeInt((int) q[0].getDenominator());
}
else {
writeIntValue(out, offset + extraOut.length());
for (int i=0; i<q.length; i++) {
extraOut.writeInt((int) q[i].getNumerator());
extraOut.writeInt((int) q[i].getDenominator());
}
}
}
else if (value instanceof float[]) { // FLOAT
float[] q = (float[]) value;
out.writeShort(IFDType.FLOAT.getCode()); // type
writeIntValue(out, q.length);
if (q.length <= dataLength / 4) {
for (int i=0; i<q.length; i++) {
out.writeFloat(q[0]); // value
}
for (int i=q.length; i<dataLength / 4; i++) {
out.writeInt(0); // padding
}
}
else {
writeIntValue(out, offset + extraOut.length());
for (int i=0; i<q.length; i++) {
extraOut.writeFloat(q[i]); // values
}
}
}
else if (value instanceof double[]) { // DOUBLE
double[] q = (double[]) value;
out.writeShort(IFDType.DOUBLE.getCode()); // type
writeIntValue(out, q.length);
writeIntValue(out, offset + extraOut.length());
for (int i=0; i<q.length; i++) {
extraOut.writeDouble(q[i]); // values
}
}
else {
throw new FormatException("Unknown IFD value type (" +
value.getClass().getName() + "): " + value);
}
}
public void overwriteLastIFDOffset(RandomAccessInputStream raf)
throws FormatException, IOException
{
if (raf == null)
throw new FormatException("Output cannot be null");
TiffParser parser = new TiffParser(raf);
long[] offsets = parser.getIFDOffsets();
out.seek(raf.getFilePointer() - (bigTiff ? 8 : 4));
writeIntValue(out, 0);
}
/**
* Surgically overwrites an existing IFD value with the given one. This
* method requires that the IFD directory entry already exist. It
* intelligently updates the count field of the entry to match the new
* length. If the new length is longer than the old length, it appends the
* new data to the end of the file and updates the offset field; if not, or
* if the old data is already at the end of the file, it overwrites the old
* data in place.
*/
public void overwriteIFDValue(RandomAccessInputStream raf,
int ifd, int tag, Object value) throws FormatException, IOException
{
if (raf == null)
throw new FormatException("Output cannot be null");
LOGGER.debug("overwriteIFDValue (ifd={}; tag={}; value={})",
new Object[] {ifd, tag, value});
raf.seek(0);
TiffParser parser = new TiffParser(raf);
Boolean valid = parser.checkHeader();
if (valid == null) {
throw new FormatException("Invalid TIFF header");
}
boolean little = valid.booleanValue();
boolean bigTiff = parser.isBigTiff();
setLittleEndian(little);
setBigTiff(bigTiff);
long offset = bigTiff ? 8 : 4; // offset to the IFD
int bytesPerEntry = bigTiff ?
TiffConstants.BIG_TIFF_BYTES_PER_ENTRY : TiffConstants.BYTES_PER_ENTRY;
raf.seek(offset);
// skip to the correct IFD
long[] offsets = parser.getIFDOffsets();
if (ifd >= offsets.length) {
throw new FormatException(
"No such IFD (" + ifd + " of " + offsets.length + ")");
}
raf.seek(offsets[ifd]);
// get the number of directory entries
long num = bigTiff ? raf.readLong() : raf.readUnsignedShort();
// search directory entries for proper tag
for (int i=0; i<num; i++) {
raf.seek(offsets[ifd] + (bigTiff ? 8 : 2) + bytesPerEntry * i);
TiffIFDEntry entry = parser.readTiffIFDEntry();
if (entry.getTag() == tag) {
// write new value to buffers
ByteArrayHandle ifdBuf = new ByteArrayHandle(bytesPerEntry);
RandomAccessOutputStream ifdOut = new RandomAccessOutputStream(ifdBuf);
ByteArrayHandle extraBuf = new ByteArrayHandle();
RandomAccessOutputStream extraOut =
new RandomAccessOutputStream(extraBuf);
extraOut.order(little);
TiffSaver saver = new TiffSaver(ifdOut);
saver.setLittleEndian(isLittleEndian());
saver.writeIFDValue(extraOut, entry.getValueOffset(), tag, value);
ifdBuf.seek(0);
extraBuf.seek(0);
// extract new directory entry parameters
int newTag = ifdBuf.readShort();
int newType = ifdBuf.readShort();
int newCount;
long newOffset;
if (bigTiff) {
newCount = ifdBuf.readInt() & 0xffffffff;
newOffset = ifdBuf.readLong();
}
else {
newCount = ifdBuf.readInt();
newOffset = ifdBuf.readInt();
}
LOGGER.debug("overwriteIFDValue:");
LOGGER.debug("\told ({});", entry);
LOGGER.debug("\tnew: (tag={}; type={}; count={}; offset={})",
new Object[] {newTag, newType, newCount, newOffset});
// determine the best way to overwrite the old entry
if (extraBuf.length() == 0) {
// new entry is inline; if old entry wasn't, old data is orphaned
// do not override new offset value since data is inline
LOGGER.debug("overwriteIFDValue: new entry is inline");
}
else if (entry.getValueOffset() + entry.getValueCount() *
entry.getType().getBytesPerElement() == raf.length())
{
// old entry was already at EOF; overwrite it
newOffset = entry.getValueOffset();
LOGGER.debug("overwriteIFDValue: old entry is at EOF");
}
else if (newCount <= entry.getValueCount()) {
// new entry is as small or smaller than old entry; overwrite it
newOffset = entry.getValueOffset();
LOGGER.debug("overwriteIFDValue: new entry is <= old entry");
}
else {
// old entry was elsewhere; append to EOF, orphaning old entry
newOffset = raf.length();
LOGGER.debug("overwriteIFDValue: old entry will be orphaned");
}
// overwrite old entry
out.seek(offsets[ifd] + (bigTiff ? 8 : 2) + bytesPerEntry * i + 2);
out.writeShort(newType);
writeIntValue(out, newCount);
writeIntValue(out, newOffset);
if (extraBuf.length() > 0) {
out.seek(newOffset);
out.write(extraBuf.getByteBuffer(), 0, newCount);
}
return;
}
}
throw new FormatException("Tag not found (" + IFD.getIFDTagName(tag) + ")");
}
/** Convenience method for overwriting a file's first ImageDescription. */
public void overwriteComment(RandomAccessInputStream in, Object value)
throws FormatException, IOException
{
overwriteIFDValue(in, 0, IFD.IMAGE_DESCRIPTION, value);
}
// -- Helper methods --
/**
* Coverts a list to a primitive array.
* @param l The list of <code>Long</code> to convert.
* @return A primitive array of type <code>long[]</code> with the values from
* </code>l</code>.
*/
private long[] toPrimitiveArray(List<Long> l) {
long[] toReturn = new long[l.size()];
for (int i = 0; i < l.size(); i++) {
toReturn[i] = l.get(i);
}
return toReturn;
}
/**
* Write the given value to the given RandomAccessOutputStream.
* If the 'bigTiff' flag is set, then the value will be written as an 8 byte
* long; otherwise, it will be written as a 4 byte integer.
*/
private void writeIntValue(RandomAccessOutputStream out, long offset)
throws IOException
{
if (bigTiff) {
out.writeLong(offset);
}
else {
out.writeInt((int) offset);
}
}
/**
* Makes a valid IFD.
*
* @param ifd The IFD to handle.
* @param pixelType The pixel type.
* @param nChannels The number of channels.
*/
private void makeValidIFD(IFD ifd, int pixelType, int nChannels) {
int bytesPerPixel = FormatTools.getBytesPerPixel(pixelType);
int bps = 8 * bytesPerPixel;
int[] bpsArray = new int[nChannels];
Arrays.fill(bpsArray, bps);
ifd.putIFDValue(IFD.BITS_PER_SAMPLE, bpsArray);
if (FormatTools.isFloatingPoint(pixelType)) {
ifd.putIFDValue(IFD.SAMPLE_FORMAT, 3);
}
if (ifd.getIFDValue(IFD.COMPRESSION) == null) {
ifd.putIFDValue(IFD.COMPRESSION, TiffCompression.UNCOMPRESSED.getCode());
}
boolean indexed = nChannels == 1 && ifd.getIFDValue(IFD.COLOR_MAP) != null;
PhotoInterp pi = indexed ? PhotoInterp.RGB_PALETTE :
nChannels == 1 ? PhotoInterp.BLACK_IS_ZERO : PhotoInterp.RGB;
ifd.putIFDValue(IFD.PHOTOMETRIC_INTERPRETATION, pi.getCode());
ifd.putIFDValue(IFD.SAMPLES_PER_PIXEL, nChannels);
if (ifd.get(IFD.X_RESOLUTION) == null) {
ifd.putIFDValue(IFD.X_RESOLUTION, new TiffRational(1, 1));
}
if (ifd.get(IFD.Y_RESOLUTION) == null) {
ifd.putIFDValue(IFD.Y_RESOLUTION, new TiffRational(1, 1));
}
if (ifd.get(IFD.SOFTWARE) == null) {
ifd.putIFDValue(IFD.SOFTWARE, "LOCI Bio-Formats");
}
if (ifd.get(IFD.ROWS_PER_STRIP) == null) {
ifd.putIFDValue(IFD.ROWS_PER_STRIP, new long[] {1});
}
if (ifd.get(IFD.IMAGE_DESCRIPTION) == null) {
ifd.putIFDValue(IFD.IMAGE_DESCRIPTION, "");
}
}
}
| true | true | public void writeImage(byte[] buf, IFD ifd, int no, int pixelType, int x,
int y, int w, int h, boolean last)
throws FormatException, IOException
{
LOGGER.debug("Attempting to write image.");
//b/c method is public should check parameters again
if (buf == null) {
throw new FormatException("Image data cannot be null");
}
if (in == null) {
throw new FormatException("RandomAccessInputStream is null. " +
"Call setInputStream(RandomAccessInputStream) first.");
}
if (ifd == null) {
throw new FormatException("IFD cannot be null");
}
int bytesPerPixel = FormatTools.getBytesPerPixel(pixelType);
int blockSize = w * h * bytesPerPixel;
int nChannels = buf.length / (w * h * bytesPerPixel);
boolean interleaved = ifd.getPlanarConfiguration() == 1;
boolean isTiled = ifd.isTiled();
makeValidIFD(ifd, pixelType, nChannels);
// create pixel output buffers
TiffCompression compression = ifd.getCompression();
int tileWidth = (int) ifd.getTileWidth();
int tileHeight = (int) ifd.getTileLength();
int tilesPerRow = (int) ifd.getTilesPerRow();
int tilesPerColumn = (int) ifd.getTilesPerColumn();
int rowsPerStrip = (int) ifd.getRowsPerStrip()[0];
int stripSize = rowsPerStrip * tileWidth * bytesPerPixel;
int nStrips = (w / tileWidth) * (h / tileHeight);
if (interleaved) stripSize *= nChannels;
else nStrips *= nChannels;
ByteArrayOutputStream[] stripBuf = new ByteArrayOutputStream[nStrips];
DataOutputStream[] stripOut = new DataOutputStream[nStrips];
for (int strip=0; strip<nStrips; strip++) {
stripBuf[strip] = new ByteArrayOutputStream(stripSize);
stripOut[strip] = new DataOutputStream(stripBuf[strip]);
}
int[] bps = ifd.getBitsPerSample();
int off;
// write pixel strips to output buffers
for (int strip = 0; strip < nStrips; strip++) {
x = (strip % tilesPerRow) * tileWidth;
y = (strip / tilesPerRow) * tileHeight;
for (int row=0; row<tileHeight; row++) {
for (int col=0; col<tileWidth; col++) {
int ndx = ((row+y) * w + col +x) * bytesPerPixel;
for (int c=0; c<nChannels; c++) {
for (int n=0; n<bps[c]/8; n++) {
if (interleaved) {
off = ndx + c * blockSize + n;
if (row >= h || col >= w) {
stripOut[strip].writeByte(0);
} else {
stripOut[strip].writeByte(buf[off]);
}
}
else {
off = c * blockSize + ndx + n;
if (row >= h || col >= w) {
stripOut[strip].writeByte(0);
} else {
stripOut[c * (nStrips / nChannels) + strip].writeByte(
buf[off]);
}
}
}
}
}
}
}
// compress strips according to given differencing and compression schemes
byte[][] strips = new byte[nStrips][];
for (int strip=0; strip<nStrips; strip++) {
strips[strip] = stripBuf[strip].toByteArray();
TiffCompression.difference(strips[strip], ifd);
CodecOptions codecOptions = compression.getCompressionCodecOptions(
ifd, options);
codecOptions.height = tileHeight;
codecOptions.width = tileWidth;
strips[strip] = compression.compress(strips[strip], codecOptions);
}
if (!sequentialWrite) {
TiffParser parser = new TiffParser(in);
long[] ifdOffsets = parser.getIFDOffsets();
if (no < ifdOffsets.length) {
out.seek(ifdOffsets[no]);
ifd = parser.getIFD(ifdOffsets[no]);
}
}
// record strip byte counts and offsets
List<Long> byteCounts = new ArrayList<Long>();
List<Long> offsets = new ArrayList<Long>();
long totalTiles = tilesPerRow * tilesPerColumn;
if (ifd.containsKey(IFD.STRIP_BYTE_COUNTS)
|| ifd.containsKey(IFD.TILE_BYTE_COUNTS)) {
long[] ifdByteCounts = isTiled? ifd.getIFDLongArray(IFD.TILE_BYTE_COUNTS)
: ifd.getStripByteCounts();
for (long stripByteCount : ifdByteCounts) {
byteCounts.add(stripByteCount);
}
}
else {
while (byteCounts.size() < totalTiles) {
byteCounts.add(0L);
}
}
Integer lastOffset = null;
if (ifd.containsKey(IFD.STRIP_OFFSETS)
|| ifd.containsKey(IFD.TILE_OFFSETS)) {
long[] ifdOffsets = isTiled? ifd.getIFDLongArray(IFD.TILE_OFFSETS)
: ifd.getStripOffsets();
for (int i = 0; i < ifdOffsets.length; i++) {
if (lastOffset == null && ifdOffsets[i] == 0L) {
lastOffset = i - 1;
}
offsets.add(ifdOffsets[i]);
}
}
else {
while (offsets.size() < totalTiles) {
offsets.add(0L);
}
lastOffset = -1;
}
if (isTiled) {
ifd.putIFDValue(IFD.TILE_BYTE_COUNTS, toPrimitiveArray(byteCounts));
ifd.putIFDValue(IFD.TILE_OFFSETS, toPrimitiveArray(offsets));
}
else {
ifd.putIFDValue(IFD.STRIP_BYTE_COUNTS, toPrimitiveArray(byteCounts));
ifd.putIFDValue(IFD.STRIP_OFFSETS, toPrimitiveArray(offsets));
}
long fp = out.getFilePointer();
writeIFD(ifd, 0);
for (int i=0; i<strips.length; i++) {
if (lastOffset != -1) {
out.seek(offsets.get(lastOffset) + byteCounts.get(lastOffset));
}
int thisOffset = lastOffset + i + 1;
offsets.set(thisOffset, out.getFilePointer());
byteCounts.set(thisOffset, new Long(strips[i].length));
if (LOGGER.isDebugEnabled()) {
LOGGER.debug(String.format(
"Writing tile/strip %d/%d size: %d offset: %d",
thisOffset + 1, totalTiles, byteCounts.get(thisOffset),
offsets.get(thisOffset)));
}
out.write(strips[i]);
}
if (isTiled) {
ifd.putIFDValue(IFD.TILE_BYTE_COUNTS, toPrimitiveArray(byteCounts));
ifd.putIFDValue(IFD.TILE_OFFSETS, toPrimitiveArray(offsets));
}
else {
ifd.putIFDValue(IFD.STRIP_BYTE_COUNTS, toPrimitiveArray(byteCounts));
ifd.putIFDValue(IFD.STRIP_OFFSETS, toPrimitiveArray(offsets));
}
long endFP = out.getFilePointer();
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Offset before IFD write: {} Seeking to: {}",
out.getFilePointer(), fp);
}
out.seek(fp);
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Writing tile/strip offsets: {}",
Arrays.toString(toPrimitiveArray(offsets)));
LOGGER.debug("Writing tile/strip byte counts: {}",
Arrays.toString(toPrimitiveArray(byteCounts)));
}
writeIFD(ifd, last ? 0 : endFP);
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Offset after IFD write: {}", out.getFilePointer());
}
}
| public void writeImage(byte[] buf, IFD ifd, int no, int pixelType, int x,
int y, int w, int h, boolean last)
throws FormatException, IOException
{
LOGGER.debug("Attempting to write image.");
//b/c method is public should check parameters again
if (buf == null) {
throw new FormatException("Image data cannot be null");
}
if (in == null) {
throw new FormatException("RandomAccessInputStream is null. " +
"Call setInputStream(RandomAccessInputStream) first.");
}
if (ifd == null) {
throw new FormatException("IFD cannot be null");
}
int bytesPerPixel = FormatTools.getBytesPerPixel(pixelType);
int blockSize = w * h * bytesPerPixel;
int nChannels = buf.length / (w * h * bytesPerPixel);
boolean interleaved = ifd.getPlanarConfiguration() == 1;
boolean isTiled = ifd.isTiled();
makeValidIFD(ifd, pixelType, nChannels);
// create pixel output buffers
TiffCompression compression = ifd.getCompression();
int tileWidth = (int) ifd.getTileWidth();
int tileHeight = (int) ifd.getTileLength();
int tilesPerRow = (int) ifd.getTilesPerRow();
int tilesPerColumn = (int) ifd.getTilesPerColumn();
int rowsPerStrip = (int) ifd.getRowsPerStrip()[0];
int stripSize = rowsPerStrip * tileWidth * bytesPerPixel;
int nStrips = ((w + tileWidth - 1) / tileWidth)
* ((h + tileHeight - 1) / tileHeight);
if (interleaved) stripSize *= nChannels;
else nStrips *= nChannels;
ByteArrayOutputStream[] stripBuf = new ByteArrayOutputStream[nStrips];
DataOutputStream[] stripOut = new DataOutputStream[nStrips];
for (int strip=0; strip<nStrips; strip++) {
stripBuf[strip] = new ByteArrayOutputStream(stripSize);
stripOut[strip] = new DataOutputStream(stripBuf[strip]);
}
int[] bps = ifd.getBitsPerSample();
int off;
// write pixel strips to output buffers
for (int strip = 0; strip < nStrips; strip++) {
x = (strip % tilesPerRow) * tileWidth;
y = (strip / tilesPerRow) * tileHeight;
for (int row=0; row<tileHeight; row++) {
for (int col=0; col<tileWidth; col++) {
int ndx = ((row+y) * w + col +x) * bytesPerPixel;
for (int c=0; c<nChannels; c++) {
for (int n=0; n<bps[c]/8; n++) {
if (interleaved) {
off = ndx + c * blockSize + n;
if (row >= h || col >= w) {
stripOut[strip].writeByte(0);
} else {
stripOut[strip].writeByte(buf[off]);
}
}
else {
off = c * blockSize + ndx + n;
if (row >= h || col >= w) {
stripOut[strip].writeByte(0);
} else {
stripOut[c * (nStrips / nChannels) + strip].writeByte(
buf[off]);
}
}
}
}
}
}
}
// compress strips according to given differencing and compression schemes
byte[][] strips = new byte[nStrips][];
for (int strip=0; strip<nStrips; strip++) {
strips[strip] = stripBuf[strip].toByteArray();
TiffCompression.difference(strips[strip], ifd);
CodecOptions codecOptions = compression.getCompressionCodecOptions(
ifd, options);
codecOptions.height = tileHeight;
codecOptions.width = tileWidth;
strips[strip] = compression.compress(strips[strip], codecOptions);
}
if (!sequentialWrite) {
TiffParser parser = new TiffParser(in);
long[] ifdOffsets = parser.getIFDOffsets();
if (no < ifdOffsets.length) {
out.seek(ifdOffsets[no]);
ifd = parser.getIFD(ifdOffsets[no]);
}
}
// record strip byte counts and offsets
List<Long> byteCounts = new ArrayList<Long>();
List<Long> offsets = new ArrayList<Long>();
long totalTiles = tilesPerRow * tilesPerColumn;
if (ifd.containsKey(IFD.STRIP_BYTE_COUNTS)
|| ifd.containsKey(IFD.TILE_BYTE_COUNTS)) {
long[] ifdByteCounts = isTiled? ifd.getIFDLongArray(IFD.TILE_BYTE_COUNTS)
: ifd.getStripByteCounts();
for (long stripByteCount : ifdByteCounts) {
byteCounts.add(stripByteCount);
}
}
else {
while (byteCounts.size() < totalTiles) {
byteCounts.add(0L);
}
}
Integer lastOffset = null;
if (ifd.containsKey(IFD.STRIP_OFFSETS)
|| ifd.containsKey(IFD.TILE_OFFSETS)) {
long[] ifdOffsets = isTiled? ifd.getIFDLongArray(IFD.TILE_OFFSETS)
: ifd.getStripOffsets();
for (int i = 0; i < ifdOffsets.length; i++) {
if (lastOffset == null && ifdOffsets[i] == 0L) {
lastOffset = i - 1;
}
offsets.add(ifdOffsets[i]);
}
}
else {
while (offsets.size() < totalTiles) {
offsets.add(0L);
}
lastOffset = -1;
}
if (isTiled) {
ifd.putIFDValue(IFD.TILE_BYTE_COUNTS, toPrimitiveArray(byteCounts));
ifd.putIFDValue(IFD.TILE_OFFSETS, toPrimitiveArray(offsets));
}
else {
ifd.putIFDValue(IFD.STRIP_BYTE_COUNTS, toPrimitiveArray(byteCounts));
ifd.putIFDValue(IFD.STRIP_OFFSETS, toPrimitiveArray(offsets));
}
long fp = out.getFilePointer();
writeIFD(ifd, 0);
for (int i=0; i<strips.length; i++) {
if (lastOffset != -1) {
out.seek(offsets.get(lastOffset) + byteCounts.get(lastOffset));
}
int thisOffset = lastOffset + i + 1;
offsets.set(thisOffset, out.getFilePointer());
byteCounts.set(thisOffset, new Long(strips[i].length));
if (LOGGER.isDebugEnabled()) {
LOGGER.debug(String.format(
"Writing tile/strip %d/%d size: %d offset: %d",
thisOffset + 1, totalTiles, byteCounts.get(thisOffset),
offsets.get(thisOffset)));
}
out.write(strips[i]);
}
if (isTiled) {
ifd.putIFDValue(IFD.TILE_BYTE_COUNTS, toPrimitiveArray(byteCounts));
ifd.putIFDValue(IFD.TILE_OFFSETS, toPrimitiveArray(offsets));
}
else {
ifd.putIFDValue(IFD.STRIP_BYTE_COUNTS, toPrimitiveArray(byteCounts));
ifd.putIFDValue(IFD.STRIP_OFFSETS, toPrimitiveArray(offsets));
}
long endFP = out.getFilePointer();
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Offset before IFD write: {} Seeking to: {}",
out.getFilePointer(), fp);
}
out.seek(fp);
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Writing tile/strip offsets: {}",
Arrays.toString(toPrimitiveArray(offsets)));
LOGGER.debug("Writing tile/strip byte counts: {}",
Arrays.toString(toPrimitiveArray(byteCounts)));
}
writeIFD(ifd, last ? 0 : endFP);
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Offset after IFD write: {}", out.getFilePointer());
}
}
|
diff --git a/org.eclipse.mylyn.tests/src/org/eclipse/mylyn/tests/AllTests.java b/org.eclipse.mylyn.tests/src/org/eclipse/mylyn/tests/AllTests.java
index ba19daf..a7bfa3c 100644
--- a/org.eclipse.mylyn.tests/src/org/eclipse/mylyn/tests/AllTests.java
+++ b/org.eclipse.mylyn.tests/src/org/eclipse/mylyn/tests/AllTests.java
@@ -1,45 +1,45 @@
/*******************************************************************************
* Copyright (c) 2004 - 2005 University Of British Columbia 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:
* University Of British Columbia - initial API and implementation
*******************************************************************************/
package org.eclipse.mylar.tests;
import junit.framework.Test;
import junit.framework.TestSuite;
import org.eclipse.mylar.bugzilla.test.AllBugzillaTests;
import org.eclipse.mylar.core.tests.AllCoreTests;
import org.eclipse.mylar.java.tests.AllJavaTests;
import org.eclipse.mylar.monitor.tests.AllMonitorTests;
import org.eclipse.mylar.tasklist.tests.AllTasklistTests;
import org.eclipse.mylar.xml.tests.AllXmlTests;
/**
* @author Mik Kersten
*/
public class AllTests {
public static Test suite() {
TestSuite suite = new TestSuite("Test for org.eclipse.mylar.tests");
//$JUnit-BEGIN$
// NOTE: the order of these tests matters
// TODO: make tests clear workbench state on completion
- suite.addTest(AllMonitorTests.suite());
+ suite.addTest(AllMonitorTests.suite());
suite.addTest(AllXmlTests.suite()); // HACK: first because it doesn't clean up properly
suite.addTest(AllJavaTests.suite());
suite.addTest(AllCoreTests.suite());
suite.addTest(AllTasklistTests.suite());
suite.addTest(AllBugzillaTests.suite());
suite.addTest(MiscTests.suite());
//$JUnit-END$
return suite;
}
}
| true | true | public static Test suite() {
TestSuite suite = new TestSuite("Test for org.eclipse.mylar.tests");
//$JUnit-BEGIN$
// NOTE: the order of these tests matters
// TODO: make tests clear workbench state on completion
suite.addTest(AllMonitorTests.suite());
suite.addTest(AllXmlTests.suite()); // HACK: first because it doesn't clean up properly
suite.addTest(AllJavaTests.suite());
suite.addTest(AllCoreTests.suite());
suite.addTest(AllTasklistTests.suite());
suite.addTest(AllBugzillaTests.suite());
suite.addTest(MiscTests.suite());
//$JUnit-END$
return suite;
}
| public static Test suite() {
TestSuite suite = new TestSuite("Test for org.eclipse.mylar.tests");
//$JUnit-BEGIN$
// NOTE: the order of these tests matters
// TODO: make tests clear workbench state on completion
suite.addTest(AllMonitorTests.suite());
suite.addTest(AllXmlTests.suite()); // HACK: first because it doesn't clean up properly
suite.addTest(AllJavaTests.suite());
suite.addTest(AllCoreTests.suite());
suite.addTest(AllTasklistTests.suite());
suite.addTest(AllBugzillaTests.suite());
suite.addTest(MiscTests.suite());
//$JUnit-END$
return suite;
}
|
diff --git a/modules/dCache/diskCacheV111/util/ActiveAdapter.java b/modules/dCache/diskCacheV111/util/ActiveAdapter.java
index 101d136784..fbd4fe3e52 100644
--- a/modules/dCache/diskCacheV111/util/ActiveAdapter.java
+++ b/modules/dCache/diskCacheV111/util/ActiveAdapter.java
@@ -1,831 +1,833 @@
//$Id: ActiveAdapter.java,v 1.4 2007-10-10 09:35:11 behrmann Exp $
//$Log: not supported by cvs2svn $
//Revision 1.3 2007/05/29 21:23:25 podstvkv
//Adapter closing mechanism changed
//
/*
COPYRIGHT STATUS:
Dec 1st 2001, Fermi National Accelerator Laboratory (FNAL) documents and
software are sponsored by the U.S. Department of Energy under Contract No.
DE-AC02-76CH03000. Therefore, the U.S. Government retains a world-wide
non-exclusive, royalty-free license to publish or reproduce these documents
and software for U.S. Government purposes. All documents and software
available from this server are protected under the U.S. and Foreign
Copyright Laws, and FNAL reserves all rights.
Distribution of the software available from this server is free of
charge subject to the user following the terms of the Fermitools
Software Legal Information.
Redistribution and/or modification of the software shall be accompanied
by the Fermitools Software Legal Information (including the copyright
notice).
The user is asked to feed back problems, benefits, and/or suggestions
about the software to the Fermilab Software Providers.
Neither the name of Fermilab, the URA, nor the names of the contributors
may be used to endorse or promote products derived from this software
without specific prior written permission.
DISCLAIMER OF LIABILITY (BSD):
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 FERMILAB,
OR THE URA, OR THE U.S. DEPARTMENT of ENERGY, 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.
Liabilities of the Government:
This software is provided by URA, independent from its Prime Contract
with the U.S. Department of Energy. URA is acting independently from
the Government and in its own private capacity and is not acting on
behalf of the U.S. Government, nor as its contractor nor its agent.
Correspondingly, it is understood and agreed that the U.S. Government
has no connection to this software and in no manner whatsoever shall
be liable for nor assume any responsibility or obligation for any claim,
cost, or damages arising out of or resulting from the use of the software
available from this server.
Export Control:
All documents and software available from this server are subject to U.S.
export control laws. Anyone downloading information from this server is
obligated to secure any necessary Government licenses before exporting
documents or software obtained from this server.
*/
package diskCacheV111.util;
import java.io.IOException;
import java.net.BindException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.nio.ByteBuffer;
import java.nio.channels.ClosedChannelException;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Random;
import dmg.cells.nucleus.CellAdapter;
/**
* @author V. Podstavkov
*
*/
public class ActiveAdapter implements Runnable, ProxyAdapter {
private ServerSocketChannel _ssc; // The ServerSocketChannel we will
// listen on...
private String _tgtHost = null; // The remote host to connect
private int _tgtPort = 0; // The remote port to connect
private String _laddr = null; // Local IP address
private int _lport; // Local port number
private int _maxBlockSize = 32768; // Size of the buffers for transfers
private int _maxStreams = 128; // The maximum number of concurrent streams
// allowed
private Selector _selector = null;
private LinkedList<SocketChannel> _pending = new LinkedList<SocketChannel>();
private String _error;
private CellAdapter _door; // The cell used for error logging
private Random _random = new Random(); // Random number generator used when
// binding sockets
private Thread _t = null; // A thread driving the adapter
private boolean _closeRequested = false; // Request to close received
public ActiveAdapter(CellAdapter door) throws IOException {
this(door, (ServerSocketChannel) null, (String) null, 0);
}
/**
*
* @param door
* @param lowPort
* @param highPort
* @throws IOException
*/
public ActiveAdapter(CellAdapter door, int lowPort, int highPort)
throws IOException {
_door = door;
if (lowPort > highPort) {
throw new IllegalArgumentException("lowPort > highPort");
}
say("Port range=" + lowPort + "-" + highPort);
if (lowPort > 0) {
/*
* We randomise the first socket to try to reduce the risk of
* conflicts and to make the port less predictable.
*/
int start = _random.nextInt(highPort - lowPort + 1) + lowPort;
int i = start;
do {
try {
say("Trying Port " + i);
_ssc = ServerSocketChannel.open();
_ssc.configureBlocking(false); // Set it to non-blocking,
// so we can use select
_ssc.socket().bind(new InetSocketAddress(i));
break;
} catch (BindException ee) {
say("Problems trying port " + i + " " + ee);
if (i == highPort) {
throw ee;
}
}
i = (i < highPort ? i + 1 : lowPort);
} while (i != start);
} else {
_ssc = ServerSocketChannel.open();
_ssc.configureBlocking(false); // Set it to non-blocking, so we can
// use select
_ssc.socket().bind(null);
}
_laddr = InetAddress.getLocalHost().getHostAddress(); // Find the
// address as a
// string
_lport = _ssc.socket().getLocalPort(); // Find the port
_t = new Thread(this);
// Create a new Selector for selecting
_selector = Selector.open();
}
/*
*
*/
public ActiveAdapter(CellAdapter door, ServerSocketChannel ssc)
throws IOException {
this(door, ssc, (String) null, 0);
}
/*
*
*/
public ActiveAdapter(CellAdapter door, ServerSocketChannel ssc,
String host, int port) throws IOException {
//
_door = door;
if (ssc == null) {
_ssc = ServerSocketChannel.open(); // Instead of creating a
// ServerSocket, create a new
// ServerSocketChannel
_ssc.configureBlocking(false); // Set it to non-blocking, so we can
// use select
_ssc.socket().bind(null); // Get the Socket connected to this
// channel, and bind to some system
// chosen port
} else {
_ssc = ssc;
}
_laddr = InetAddress.getLocalHost().getHostAddress(); // Find the
// address as a
// string
_lport = _ssc.socket().getLocalPort(); // Find the port
_tgtHost = host;
_tgtPort = port;
_t = new Thread(this);
// Create a new Selector for selecting
_selector = Selector.open();
}
// <!--
/*
* (non-Javadoc)
*
* @see diskCacheV111.util.ProxyAdapter#acceptOnClientListener()
*/
public Socket acceptOnClientListener() throws IOException {
return _ssc.accept().socket();
}
/*
* (non-Javadoc)
*
* @see diskCacheV111.util.ProxyAdapter#close()
*/
public void close() {
say("Close request received...");
// say("# of keys = "+_selector.keys().size());
_closeRequested = true;
_selector.wakeup();
return;
}
private void _close() {
say("Closing listener socket");
// say("Still have "+_selector.keys().size()+" keys");
try {
if (_ssc != null) {
_ssc.close();
_ssc = null;
_selector.close();
_selector = null;
}
} catch (IOException e) {
esay("_clientListenerSock.close() failed with IOException, ignoring");
// esay(e);
}
}
/**
* Check if transfer is still in progress
*
* @return
*/
private boolean transferInProgress() {
if (_closeRequested == true && _selector.keys().size() < 2) {
return false;
}
return true;
}
/*
* (non-Javadoc)
*
* @see diskCacheV111.util.ProxyAdapter#getClientListenerPort()
*/
public int getClientListenerPort() {
return _lport;
}
/*
* (non-Javadoc)
*
* @see diskCacheV111.util.ProxyAdapter#getError()
*/
public String getError() {
return _error;
}
/*
* (non-Javadoc)
*
* @see diskCacheV111.util.ProxyAdapter#getPoolListenerPort()
*/
public int getPoolListenerPort() {
// This adapter does not listen the second port,
// it actively connects to the second party
return _lport;
}
/*
* (non-Javadoc)
*
* @see diskCacheV111.util.ProxyAdapter#setMaxBlockSize(int)
*/
public void setMaxBlockSize(int size) {
_maxBlockSize = size;
}
/*
* (non-Javadoc)
*
* @see diskCacheV111.util.ProxyAdapter#setMaxStreams(int)
*/
public void setMaxStreams(int n) {
_maxStreams = n;
}
protected void say(String s) {
if (_door == null) {
System.out.println("ActiveAdapter: " + s);
} else {
_door.say("ActiveAdapter: " + s);
}
}
protected void esay(String s) {
if (_door == null) {
System.err.println("ActiveAdapter: " + s);
} else {
_door.esay("ActiveAdapter: " + s);
}
}
protected void esay(Throwable t) {
if (_door == null) {
System.err.println("ActiveAdapter exception:");
System.err.println(t);
} else {
_door.esay("ActiveAdapter exception:");
_door.esay(t);
}
}
/*
* (non-Javadoc)
*
* @see diskCacheV111.util.ProxyAdapter#hasError()
*/
public boolean hasError() {
return _error != null;
}
public void setDirClientToPool() {
// TODO Auto-generated method stub
}
public void setDirPoolToClient() {
// TODO Auto-generated method stub
}
public void setModeE(boolean modeE) {
// TODO Auto-generated method stub
}
/*
* (non-Javadoc)
*
* @see diskCacheV111.util.ProxyAdapter#isAlive()
*/
public boolean isAlive() {
return _t.isAlive();
}
/*
* (non-Javadoc)
*
* @see diskCacheV111.util.ProxyAdapter#join()
*/
public void join() throws InterruptedException {
_t.join();
}
/*
* (non-Javadoc)
*
* @see diskCacheV111.util.ProxyAdapter#join(long)
*/
public void join(long millis) throws InterruptedException {
_t.join(millis);
}
/*
* (non-Javadoc)
*
* @see diskCacheV111.util.ProxyAdapter#start()
*/
public void start() {
_t.start();
}
// -->
/*
*
*/
public String getLocalHost() {
return _laddr;
}
/**
*
*/
private class Tunnel {
//
private final SocketChannel _scs;
private final SocketChannel _sct;
// A pre-allocated buffer for data
private final ByteBuffer _sbuffer = ByteBuffer.allocate(_maxBlockSize);
private final ByteBuffer _tbuffer = ByteBuffer.allocate(_maxBlockSize);
/*
*
*/
Tunnel(SocketChannel scs, SocketChannel sct) {
_scs = scs;
_sct = sct;
}
/*
*
*/
public void register(Selector selector) throws ClosedChannelException {
//
if (_sct.isConnectionPending()) {
// Register the target channel with selector, listening for
// OP_CONNECT events
_sct.register(selector, SelectionKey.OP_CONNECT, this);
} else if (_sct.isConnected()) {
// Register the source channel with the selector, for reading
_scs.register(selector, SelectionKey.OP_READ, this);
// System.err.printf("Register %s%n", _scs);
// Register the target channel with selector, listening for
// OP_READ events
_sct.register(selector, SelectionKey.OP_READ, this);
}
// System.err.printf("Register %s%n", _sct);
}
/*
*
*/
public void cancel(Selector selector) {
//
SelectionKey key = _scs.keyFor(selector);
if (key != null)
key.cancel();
try {
_scs.close();
say("Close " + _scs);
} catch (IOException ie) {
esay("Error closing channel " + _scs + ": " + ie);
}
key = _sct.keyFor(selector);
if (key != null)
key.cancel();
try {
_sct.close();
say("Close " + _sct);
} catch (IOException ie) {
esay("Error closing channel " + _sct + ": " + ie);
}
}
/*
*
*/
public ByteBuffer getBuffer(SocketChannel sc) {
if (sc == _scs)
return _sbuffer;
else if (sc == _sct)
return _tbuffer;
else
return null;
}
/*
*
*/
public SocketChannel getMate(SocketChannel sc) {
if (sc == _scs)
return _sct;
else if (sc == _sct)
return _scs;
else
return null;
}
/*
*
*/
private boolean processInput(SocketChannel scs) throws IOException {
//
SocketChannel sct = getMate(scs);
boolean ok = true;
ByteBuffer b = this.getBuffer(scs);
b.clear();
int r = scs.read(b);
if (r < 0) {
say("Can't read from " + scs);
return false;
} else if (r > 0) {
b.flip();
// System.out.println("Read "+r+" from "+scs);
ok = send(sct);
} else {
// System.err.printf("Read 0 %s%n", scs);
SelectionKey key = scs.keyFor(_selector);
key.interestOps(key.interestOps() | SelectionKey.OP_READ);
}
return ok;
}
/*
*
*/
private boolean send(SocketChannel sct) throws IOException {
//
SocketChannel scs = getMate(sct);
ByteBuffer b = this.getBuffer(scs);
int r = sct.write(b);
// System.err.printf("Wrote %d to %s%n", r, sct);
if (r < 0) {
say("Can't write to " + sct);
return false;
}
if (b.hasRemaining()) {
// Register the output channel for OP_WRITE
SelectionKey key = sct.keyFor(_selector);
key.interestOps(key.interestOps() | SelectionKey.OP_WRITE);
// System.err.printf("has remaining: set OP_WRITE%n");
} else {
// Register the input channel for OP_READ
SelectionKey key = scs.keyFor(_selector);
key.interestOps(key.interestOps() | SelectionKey.OP_READ);
// System.err.printf("no remaining: set OP_READ%n");
}
return true;
}
/*
*
*/
private boolean processOutput(SocketChannel sct) throws IOException {
//
return send(sct);
}
public String toString() {
return _scs.toString() + "<->" + _sct.toString();
}
} // class Tunnel
/*
*
*/
public void run() {
//
try {
// Create a new Selector for selecting
// _selector = Selector.open();
// Register the ServerSocketChannel, so we can listen for incoming
// connections
_ssc.register(_selector, SelectionKey.OP_ACCEPT);
say("Listening on port " + _ssc.socket().getLocalPort());
// Now process the events in the infinite loop
while (transferInProgress()) {
// Watch for either an incoming connection, or incoming data on
// an existing connection
int num = _selector.select(5000);
// System.err.printf("select returned %d%n", num);
// if (num == 0) continue; // Just in case...
// Get the keys corresponding to the activity that has been
// detected, and process them one by one
Iterator<SelectionKey> selectedKeys = _selector.selectedKeys()
.iterator();
while (selectedKeys.hasNext()) {
// Get a key representing one of bits of I/O activity
SelectionKey key = selectedKeys.next();
selectedKeys.remove();
if (!key.isValid()) {
continue;
}
try {
processSelectionKey(key);
} catch (IOException e) {
// Handle error with channel and unregister
key.cancel();
esay("key processing error");
}
}
// Process pending accepted sockets and add them to the selector
processPending();
}
- _close();
+// _close();
} catch (IOException ie) {
esay(ie);
+ } finally {
+ _close();
}
}
/*
*
*/
private void accept(SelectionKey key) throws IOException {
ServerSocketChannel ssc = (ServerSocketChannel) key.channel();
SocketChannel sc = ssc.accept();
// System.out.println("Got connection from "+sc);
addPending(sc);
}
/*
*
*/
private void finishConnection(SelectionKey key) throws IOException {
SocketChannel sc = (SocketChannel) key.channel();
Tunnel tnl = (Tunnel) key.attachment();
boolean success = sc.finishConnect();
if (success) {
say("New connection: " + sc);
tnl.register(_selector);
} else {
// An error occurred; handle it
esay("Connection error: " + sc);
tnl.cancel(_selector);
}
}
/*
*
*/
public void processSelectionKey(SelectionKey key) throws IOException {
// System.err.printf("key.readyOps()=%x%n", key.readyOps());
if (key.isValid() && key.isAcceptable()) {
// System.out.println("ACCEPT");
// It's an incoming connection, accept it
this.accept(key);
}
if (key.isValid() && key.isConnectable()) {
// System.out.println("CONNECT");
// Get channel with connection request
this.finishConnection(key);
}
if (key.isValid() && key.isReadable()) {
// Obtain the interest of the key
// int readyOps = key.readyOps();
// System.out.println("READ:"+readyOps);
// Disable the interest for the operation that is ready.
// This prevents the same event from being raised multiple times.
// key.interestOps(key.interestOps() & ~readyOps);
key.interestOps(key.interestOps() & ~SelectionKey.OP_READ);
// It's incoming data on a connection, process it
this.read(key);
}
if (key.isValid() && key.isWritable()) {
// Obtain the interest of the key
// int readyOps = key.readyOps();
// System.out.println("WRITE:"+readyOps);
// Disable the interest for the operation that is ready.
// This prevents the same event from being raised multiple times.
// key.interestOps(key.interestOps() & ~readyOps);
key.interestOps(key.interestOps() & ~SelectionKey.OP_WRITE);
// It's incoming data on a connection, process it
this.write(key);
}
}
/*
*
*/
private void read(SelectionKey key) throws IOException {
Tunnel tnl = null;
try {
// There is incoming data on a connection, process it
tnl = (Tunnel) key.attachment();
//
boolean ok = tnl.processInput((SocketChannel) key.channel());
//
// If the connection is dead, then remove it from the selector and
// close it
if (!ok) {
// System.err.printf("Connection %s is dead%n", tnl);
tnl.cancel(_selector);
}
} catch (IOException ie) {
esay("Communication error");
// On exception, remove this channel from the selector
tnl.cancel(_selector);
}
}
/*
*
*/
private void write(SelectionKey key) throws IOException {
Tunnel tnl = null;
try {
// There is outgoing data on a connection, process it
tnl = (Tunnel) key.attachment();
//
boolean ok = tnl.processOutput((SocketChannel) key.channel());
//
// If the connection is dead, then remove it from the selector and
// close it
if (!ok) {
// System.err.printf("Connection %s is dead%n", tnl);
tnl.cancel(_selector);
}
} catch (IOException ie) {
esay("Communication error");
// On exception, remove this channel from the selector
tnl.cancel(_selector);
}
}
/*
*
*/
void addPending(SocketChannel s) {
//
synchronized (_pending) {
// System.err.printf("addPending: add: %s%n", s);
_pending.add(s);
_pending.notify();
}
}
/*
*
*/
public void setDestination(String host, int port) {
_tgtHost = host;
_tgtPort = port;
_selector.wakeup();
}
/*
* Process any targets in the pending list
*/
private void processPending() throws IOException {
if (_tgtHost == null || _tgtPort == 0)
return;
synchronized (_pending) {
// System.err.printf("ProcessPending: pending.size=%d%n",
// _pending.size());
while (_pending.size() > 0) {
SocketChannel scs = _pending.removeFirst();
// Make it non-blocking, so we can use a selector on it.
scs.configureBlocking(false);
// System.err.printf("ProcessPending: got %s%n", scs);
try {
// Prepare the socket channel for the target
SocketChannel sct = createSocketChannel(_tgtHost, _tgtPort);
Tunnel tnl = new Tunnel(scs, sct);
tnl.register(_selector);
} catch (IOException ie) {
// Something went wrong..........
ie.printStackTrace();
}
}
}
}
/*
* Creates a non-blocking socket channel for the specified host name and
* port and calls the connect() on the new channel before it is returned.
*/
static public SocketChannel createSocketChannel(String host, int port) throws IOException {
// Create a non-blocking socket channel
SocketChannel sc = SocketChannel.open();
sc.configureBlocking(false);
// Send a connection request to the server; this method is non-blocking
sc.connect(new InetSocketAddress(host, port));
return sc;
}
/*
*
*/
static public void main(String args[]) throws Exception {
String rsvrHost = args[0]; // Data receiver host to connect
int rsvrPort = Integer.parseInt(args[1]); // Data receiver port to
// connect
// Create the adapter
ActiveAdapter aa = new ActiveAdapter((CellAdapter) null);
System.out.printf("ActiveAdaper is listening on %s:%d%n", aa
.getLocalHost(), aa.getClientListenerPort());
// Start the adapter
aa.start();
// The receiver address can be set even after the adapter started
// For example when the adapter is used to store the data the pool is
// not known in advance
//
System.out.printf("Set destination: %s, %d%n", rsvrHost, rsvrPort);
aa.setDestination(rsvrHost, rsvrPort);
}
}
| false | true | public void run() {
//
try {
// Create a new Selector for selecting
// _selector = Selector.open();
// Register the ServerSocketChannel, so we can listen for incoming
// connections
_ssc.register(_selector, SelectionKey.OP_ACCEPT);
say("Listening on port " + _ssc.socket().getLocalPort());
// Now process the events in the infinite loop
while (transferInProgress()) {
// Watch for either an incoming connection, or incoming data on
// an existing connection
int num = _selector.select(5000);
// System.err.printf("select returned %d%n", num);
// if (num == 0) continue; // Just in case...
// Get the keys corresponding to the activity that has been
// detected, and process them one by one
Iterator<SelectionKey> selectedKeys = _selector.selectedKeys()
.iterator();
while (selectedKeys.hasNext()) {
// Get a key representing one of bits of I/O activity
SelectionKey key = selectedKeys.next();
selectedKeys.remove();
if (!key.isValid()) {
continue;
}
try {
processSelectionKey(key);
} catch (IOException e) {
// Handle error with channel and unregister
key.cancel();
esay("key processing error");
}
}
// Process pending accepted sockets and add them to the selector
processPending();
}
_close();
} catch (IOException ie) {
esay(ie);
}
}
| public void run() {
//
try {
// Create a new Selector for selecting
// _selector = Selector.open();
// Register the ServerSocketChannel, so we can listen for incoming
// connections
_ssc.register(_selector, SelectionKey.OP_ACCEPT);
say("Listening on port " + _ssc.socket().getLocalPort());
// Now process the events in the infinite loop
while (transferInProgress()) {
// Watch for either an incoming connection, or incoming data on
// an existing connection
int num = _selector.select(5000);
// System.err.printf("select returned %d%n", num);
// if (num == 0) continue; // Just in case...
// Get the keys corresponding to the activity that has been
// detected, and process them one by one
Iterator<SelectionKey> selectedKeys = _selector.selectedKeys()
.iterator();
while (selectedKeys.hasNext()) {
// Get a key representing one of bits of I/O activity
SelectionKey key = selectedKeys.next();
selectedKeys.remove();
if (!key.isValid()) {
continue;
}
try {
processSelectionKey(key);
} catch (IOException e) {
// Handle error with channel and unregister
key.cancel();
esay("key processing error");
}
}
// Process pending accepted sockets and add them to the selector
processPending();
}
// _close();
} catch (IOException ie) {
esay(ie);
} finally {
_close();
}
}
|
diff --git a/src/com/rootbox/rootboxota/fragments/InstallFragment.java b/src/com/rootbox/rootboxota/fragments/InstallFragment.java
index e03d0bd..c52f268 100644
--- a/src/com/rootbox/rootboxota/fragments/InstallFragment.java
+++ b/src/com/rootbox/rootboxota/fragments/InstallFragment.java
@@ -1,179 +1,179 @@
/*
* Copyright (C) 2013 ParanoidAndroid Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use mContext 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.rootbox.rootboxota.fragments;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.preference.Preference;
import android.preference.Preference.OnPreferenceClickListener;
import android.preference.PreferenceCategory;
import android.preference.PreferenceScreen;
import com.rootbox.rootboxota.IOUtils;
import com.rootbox.rootboxota.R;
import com.rootbox.rootboxota.Utils;
import com.rootbox.rootboxota.activities.RequestFileActivity;
import com.rootbox.rootboxota.activities.RequestFileActivity.RequestFileCallback;
public class InstallFragment extends android.preference.PreferenceFragment
implements RequestFileCallback {
private static List<File> sFiles = new ArrayList<File>();
public static void clearFiles() {
sFiles.clear();
}
public static void addFile(File file) {
if (sFiles.indexOf(file) >= 0) {
sFiles.remove(file);
}
sFiles.add(file);
}
public static String[] getFiles() {
List<String> files = new ArrayList<String>();
for (File file : sFiles) {
files.add(file.getAbsolutePath());
}
return files.toArray(new String[files.size()]);
}
private static Context mContext;
private static OnPreferenceClickListener mListener;
private static PreferenceCategory mLocalRoot;
private static PreferenceCategory mExtrasRoot;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mContext = getActivity();
mListener = new OnPreferenceClickListener() {
@Override
public boolean onPreferenceClick(Preference preference) {
showRemoveDialog(preference);
return false;
}
};
RequestFileActivity.setRequestFileCallback(this);
PreferenceScreen root = getPreferenceManager().createPreferenceScreen(mContext);
mLocalRoot = new PreferenceCategory(mContext);
mLocalRoot.setTitle(R.string.local);
root.addPreference(mLocalRoot);
mExtrasRoot = new PreferenceCategory(mContext);
mExtrasRoot.setTitle(R.string.extras);
root.addPreference(mExtrasRoot);
setPreferenceScreen(root);
update();
}
@Override
public void fileRequested(String filePath) {
addFile(new File(filePath));
update();
}
public static void update() {
mLocalRoot.removeAll();
mExtrasRoot.removeAll();
for (File file : sFiles) {
Preference pref = new Preference(mContext);
pref.setTitle(file.getName());
pref.setSummary(getSummary(file, true));
pref.setIcon(R.drawable.ic_download);
pref.getExtras().putString("filePath", file.getAbsolutePath());
pref.setOnPreferenceClickListener(mListener);
- if (IOUtils.isOnDownloadList(mContext, file.getName())) {
+ if (IOUtils.isRom(file.getName()) || IOUtils.isGapps(file.getName())) {
mLocalRoot.addPreference(pref);
} else {
mExtrasRoot.addPreference(pref);
}
}
if(mLocalRoot.getPreferenceCount() == 0) {
Preference pref0 = new Preference(mContext);
pref0.setSummary(R.string.no_files_added);
pref0.setIcon(R.drawable.ic_info);
pref0.setEnabled(false);
pref0.setSelectable(false);
mLocalRoot.addPreference(pref0);
}
if(mExtrasRoot.getPreferenceCount() == 0) {
Preference pref1 = new Preference(mContext);
pref1.setSummary(R.string.no_files_added_extra);
pref1.setIcon(R.drawable.ic_info);
pref1.setEnabled(false);
pref1.setSelectable(false);
mExtrasRoot.addPreference(pref1);
}
}
private static String getSummary(File file, boolean isDownloaded) {
if (isDownloaded) {
String name = file.getName();
if(IOUtils.isRom(name)) {
return Utils.getReadableVersionRom(name)+ " - " + IOUtils.humanReadableByteCount(file.length(), false);
}
else if(IOUtils.isGapps(name)) {
return Utils.getReadableVersion(name) + " - " + IOUtils.humanReadableByteCount(file.length(), false);
}
return IOUtils.humanReadableByteCount(file.length(), false);
} else {
String path = file.getAbsolutePath();
return path.substring(0, path.lastIndexOf("/"));
}
}
private void showRemoveDialog(final Preference preference) {
AlertDialog.Builder alert = new AlertDialog.Builder(mContext);
alert.setTitle(R.string.remove_file_title);
alert.setMessage(R.string.remove_file_summary);
alert.setPositiveButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
dialog.dismiss();
}
});
alert.setNegativeButton(android.R.string.ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
dialog.dismiss();
File file = new File(preference.getExtras().getString("filePath"));
sFiles.remove(file);
update();
}
});
alert.show();
}
}
| true | true | public static void update() {
mLocalRoot.removeAll();
mExtrasRoot.removeAll();
for (File file : sFiles) {
Preference pref = new Preference(mContext);
pref.setTitle(file.getName());
pref.setSummary(getSummary(file, true));
pref.setIcon(R.drawable.ic_download);
pref.getExtras().putString("filePath", file.getAbsolutePath());
pref.setOnPreferenceClickListener(mListener);
if (IOUtils.isOnDownloadList(mContext, file.getName())) {
mLocalRoot.addPreference(pref);
} else {
mExtrasRoot.addPreference(pref);
}
}
if(mLocalRoot.getPreferenceCount() == 0) {
Preference pref0 = new Preference(mContext);
pref0.setSummary(R.string.no_files_added);
pref0.setIcon(R.drawable.ic_info);
pref0.setEnabled(false);
pref0.setSelectable(false);
mLocalRoot.addPreference(pref0);
}
if(mExtrasRoot.getPreferenceCount() == 0) {
Preference pref1 = new Preference(mContext);
pref1.setSummary(R.string.no_files_added_extra);
pref1.setIcon(R.drawable.ic_info);
pref1.setEnabled(false);
pref1.setSelectable(false);
mExtrasRoot.addPreference(pref1);
}
}
| public static void update() {
mLocalRoot.removeAll();
mExtrasRoot.removeAll();
for (File file : sFiles) {
Preference pref = new Preference(mContext);
pref.setTitle(file.getName());
pref.setSummary(getSummary(file, true));
pref.setIcon(R.drawable.ic_download);
pref.getExtras().putString("filePath", file.getAbsolutePath());
pref.setOnPreferenceClickListener(mListener);
if (IOUtils.isRom(file.getName()) || IOUtils.isGapps(file.getName())) {
mLocalRoot.addPreference(pref);
} else {
mExtrasRoot.addPreference(pref);
}
}
if(mLocalRoot.getPreferenceCount() == 0) {
Preference pref0 = new Preference(mContext);
pref0.setSummary(R.string.no_files_added);
pref0.setIcon(R.drawable.ic_info);
pref0.setEnabled(false);
pref0.setSelectable(false);
mLocalRoot.addPreference(pref0);
}
if(mExtrasRoot.getPreferenceCount() == 0) {
Preference pref1 = new Preference(mContext);
pref1.setSummary(R.string.no_files_added_extra);
pref1.setIcon(R.drawable.ic_info);
pref1.setEnabled(false);
pref1.setSelectable(false);
mExtrasRoot.addPreference(pref1);
}
}
|
diff --git a/src/tests/java/de/ismll/table/impl/VectorsTest.java b/src/tests/java/de/ismll/table/impl/VectorsTest.java
index 38441b6..6b0baee 100644
--- a/src/tests/java/de/ismll/table/impl/VectorsTest.java
+++ b/src/tests/java/de/ismll/table/impl/VectorsTest.java
@@ -1,39 +1,39 @@
package de.ismll.table.impl;
import de.ismll.table.IntVector;
import de.ismll.table.Vectors;
public class VectorsTest {
// @Test
public void testCovariance() {
DefaultVector a1 = new DefaultVector(10);
Vectors.fillUniformAtRandom(a1, 0.f, 1.f);
DefaultVector a2 = new DefaultVector(10);
Vectors.fillUniformAtRandom(a2, 9.f, 10.f);
double value = Vectors.covariance(a1, a2);
System.out.println(value);
}
// @Test
public void testRemoveAll() {
IntVector base = new DefaultIntVector(100);
IntVector removeIndizes = new DefaultIntVector(10);
- IntVector assumedResult = new DefaultIntVector(90);
+// IntVector assumedResult = new DefaultIntVector(90);
for (int i = 0; i < base.size(); i++)
base.set(i, i);
for (int i = 0; i < removeIndizes.size(); i++)
removeIndizes.set(i, i*i);
- int assumedIdx=0;
+// int assumedIdx=0;
// System.out.println(assumedResult);
// base.set(i, i);
IntVector removeAll = Vectors.removeAll(base, removeIndizes);
System.out.println(removeAll);
}
}
| false | true | public void testRemoveAll() {
IntVector base = new DefaultIntVector(100);
IntVector removeIndizes = new DefaultIntVector(10);
IntVector assumedResult = new DefaultIntVector(90);
for (int i = 0; i < base.size(); i++)
base.set(i, i);
for (int i = 0; i < removeIndizes.size(); i++)
removeIndizes.set(i, i*i);
int assumedIdx=0;
// System.out.println(assumedResult);
// base.set(i, i);
IntVector removeAll = Vectors.removeAll(base, removeIndizes);
System.out.println(removeAll);
}
| public void testRemoveAll() {
IntVector base = new DefaultIntVector(100);
IntVector removeIndizes = new DefaultIntVector(10);
// IntVector assumedResult = new DefaultIntVector(90);
for (int i = 0; i < base.size(); i++)
base.set(i, i);
for (int i = 0; i < removeIndizes.size(); i++)
removeIndizes.set(i, i*i);
// int assumedIdx=0;
// System.out.println(assumedResult);
// base.set(i, i);
IntVector removeAll = Vectors.removeAll(base, removeIndizes);
System.out.println(removeAll);
}
|
diff --git a/cool-tree.java b/cool-tree.java
index d15292a..4b0be33 100755
--- a/cool-tree.java
+++ b/cool-tree.java
@@ -1,2014 +1,2014 @@
// -*- mode: java -*-
//
// file: cool-tree.m4
//
// This file defines the AST
//
//////////////////////////////////////////////////////////
import java.util.Enumeration;
import java.io.PrintStream;
import java.util.Vector;
import java.util.*;
import java.lang.*;
/** Defines simple phylum Program */
abstract class Program extends TreeNode {
protected Program(int lineNumber) {
super(lineNumber);
}
public abstract void dump_with_types(PrintStream out, int n);
public abstract void semant();
}
/** Defines simple phylum Class_ */
abstract class Class_ extends TreeNode {
protected Class_(int lineNumber) {
super(lineNumber);
}
public abstract void dump_with_types(PrintStream out, int n);
}
/** Defines list phylum Classes
<p>
See <a href="ListNode.html">ListNode</a> for full documentation. */
class Classes extends ListNode {
public final static Class elementClass = Class_.class;
/** Returns class of this lists's elements */
public Class getElementClass() {
return elementClass;
}
protected Classes(int lineNumber, Vector elements) {
super(lineNumber, elements);
}
/** Creates an empty "Classes" list */
public Classes(int lineNumber) {
super(lineNumber);
}
/** Appends "Class_" element to this list */
public Classes appendElement(TreeNode elem) {
addElement(elem);
return this;
}
public TreeNode copy() {
return new Classes(lineNumber, copyElements());
}
}
/** Defines simple phylum Feature */
abstract class Feature extends TreeNode {
protected Feature(int lineNumber) {
super(lineNumber);
}
public abstract void dump_with_types(PrintStream out, int n);
}
/** Defines list phylum Features
<p>
See <a href="ListNode.html">ListNode</a> for full documentation. */
class Features extends ListNode {
public final static Class elementClass = Feature.class;
/** Returns class of this lists's elements */
public Class getElementClass() {
return elementClass;
}
protected Features(int lineNumber, Vector elements) {
super(lineNumber, elements);
}
/** Creates an empty "Features" list */
public Features(int lineNumber) {
super(lineNumber);
}
/** Appends "Feature" element to this list */
public Features appendElement(TreeNode elem) {
addElement(elem);
return this;
}
public TreeNode copy() {
return new Features(lineNumber, copyElements());
}
}
/** Defines simple phylum Formal */
abstract class Formal extends TreeNode {
protected Formal(int lineNumber) {
super(lineNumber);
}
public abstract void dump_with_types(PrintStream out, int n);
}
/** Defines list phylum Formals
<p>
See <a href="ListNode.html">ListNode</a> for full documentation. */
class Formals extends ListNode {
public final static Class elementClass = Formal.class;
/** Returns class of this lists's elements */
public Class getElementClass() {
return elementClass;
}
protected Formals(int lineNumber, Vector elements) {
super(lineNumber, elements);
}
/** Creates an empty "Formals" list */
public Formals(int lineNumber) {
super(lineNumber);
}
/** Appends "Formal" element to this list */
public Formals appendElement(TreeNode elem) {
addElement(elem);
return this;
}
public TreeNode copy() {
return new Formals(lineNumber, copyElements());
}
}
/** Defines simple phylum Expression */
abstract class Expression extends TreeNode {
protected Expression(int lineNumber) {
super(lineNumber);
}
private AbstractSymbol type = null;
public AbstractSymbol get_type() { return type; }
public Expression set_type(AbstractSymbol s) { type = s; return this; }
public abstract void dump_with_types(PrintStream out, int n);
public void dump_type(PrintStream out, int n) {
if (type != null)
{ out.println(Utilities.pad(n) + ": " + type.getString()); }
else
{ out.println(Utilities.pad(n) + ": _no_type"); }
}
}
/** Defines list phylum Expressions
<p>
See <a href="ListNode.html">ListNode</a> for full documentation. */
class Expressions extends ListNode {
public final static Class elementClass = Expression.class;
/** Returns class of this lists's elements */
public Class getElementClass() {
return elementClass;
}
protected Expressions(int lineNumber, Vector elements) {
super(lineNumber, elements);
}
/** Creates an empty "Expressions" list */
public Expressions(int lineNumber) {
super(lineNumber);
}
/** Appends "Expression" element to this list */
public Expressions appendElement(TreeNode elem) {
addElement(elem);
return this;
}
public TreeNode copy() {
return new Expressions(lineNumber, copyElements());
}
}
/** Defines simple phylum Case */
abstract class Case extends TreeNode {
protected Case(int lineNumber) {
super(lineNumber);
}
public abstract void dump_with_types(PrintStream out, int n);
}
/** Defines list phylum Cases
<p>
See <a href="ListNode.html">ListNode</a> for full documentation. */
class Cases extends ListNode {
public final static Class elementClass = Case.class;
/** Returns class of this lists's elements */
public Class getElementClass() {
return elementClass;
}
protected Cases(int lineNumber, Vector elements) {
super(lineNumber, elements);
}
/** Creates an empty "Cases" list */
public Cases(int lineNumber) {
super(lineNumber);
}
/** Appends "Case" element to this list */
public Cases appendElement(TreeNode elem) {
addElement(elem);
return this;
}
public TreeNode copy() {
return new Cases(lineNumber, copyElements());
}
}
/** Defines AST constructor 'programc'.
<p>
See <a href="TreeNode.html">TreeNode</a> for full documentation. */
class programc extends Program {
/* Initialize two MySymbolTables - one for method and one for objects */
HashMap<String, MySymbolTable> objectSymTabMap = new HashMap<String, MySymbolTable>();
HashMap<String, MySymbolTable> methodSymTabMap = new HashMap<String, MySymbolTable>();
HashMap< String, HashMap< String, ArrayList<AbstractSymbol>>> methodEnvironment;
protected Classes classes;
ClassTable classTable;
/** Creates "programc" AST node.
*
* @param lineNumber the line in the source file from which this node came.
* @param a0 initial value for classes
*/
public programc(int lineNumber, Classes a1) {
super(lineNumber);
classes = a1;
}
public TreeNode copy() {
return new programc(lineNumber, (Classes)classes.copy());
}
public void dump(PrintStream out, int n) {
out.print(Utilities.pad(n) + "programc\n");
classes.dump(out, n+2);
}
public void dump_with_types(PrintStream out, int n) {
dump_line(out, n);
out.println(Utilities.pad(n) + "_program");
for (Enumeration e = classes.getElements(); e.hasMoreElements(); ) {
// sm: changed 'n + 1' to 'n + 2' to match changes elsewhere
((Class_)e.nextElement()).dump_with_types(out, n + 2);
}
}
/** This method is the entry point to the semantic checker. You will
need to complete it in programming assignment 4.
<p>
Your checker should do the following two things:
<ol>
<li>Check that the program is semantically correct
<li>Decorate the abstract syntax tree with type information
by setting the type field in each Expression node.
(see tree.h)
</ol>
<p>
You are free to first do (1) and make sure you catch all semantic
errors. Part (2) can be done in a second stage when you want
to test the complete compiler.
*/
public void semant() {
/* ClassTable constructor may do some semantic analysis */
classTable = new ClassTable(classes);
// Abort if there are errors in the inheritanc graph
if (classTable.errors()) {
System.err.println("Compilation halted due to static semantic errors.");
System.exit(1);
}
/* some semantic analysis code may go here */
/* Traverse the AST top-down and when the leaves are reached, fill in the type information
as we're winding back up. This does Scoping/Naming
*/
/* Traverse basic classes first */
Classes basicClasses = classTable.getBasicClassList();
methodEnvironment = new HashMap< String, HashMap< String, ArrayList<AbstractSymbol>>>();
traverseAST(basicClasses);
traverseAST(classes);
/* Perform type checking with another traversal */
if (Flags.semant_debug) {
System.out.println(methodEnvironment);
}
traverseASTWithTypecheck(classes);
if (classTable.errors()) {
System.err.println("Compilation halted due to static semantic errors.");
System.exit(1);
}
}
/** Traverses AST and does 1. Scoping 2. Type Checking **/
private void traverseAST(Classes classes) {
/* Loop through each class */
for (Enumeration e = classes.getElements(); e.hasMoreElements(); ) {
class_c currentClass = ((class_c)e.nextElement());
if (Flags.semant_debug) {
System.out.println("First Pass Class " + currentClass.getName().toString());
}
/* Inside each class, start new scope, traverse down the class AST */
objectSymTabMap.put(currentClass.getName().toString(), new MySymbolTable());
MySymbolTable objectSymTab = objectSymTabMap.get(currentClass.getName().toString());
objectSymTab.enterScope();
methodEnvironment.put(currentClass.getName().toString(), new HashMap<String,ArrayList<AbstractSymbol>>());
HashMap<String, ArrayList<AbstractSymbol>> methodSymTab = methodEnvironment.get(currentClass.getName().toString());
Features features = currentClass.getFeatures();
for (Enumeration fe = features.getElements(); fe.hasMoreElements();) {
Feature f = ((Feature)fe.nextElement());
if ( f instanceof attr ) {
//System.out.println("Attribute ");
if (Flags.semant_debug) {
System.out.println("Traversing Attribute : " + ((attr)f).getName().toString());
}
// Add attribute to object Symbol Table,if already present, scope error
if (objectSymTab.lookup(((attr)f).getName()) != null) {
classTable.semantError(currentClass.getFilename(), f).println("Attribute " + ((attr)f).getName().toString() + " is multiply defined");
}
//add attribute to symbol table, overwrite if already there
objectSymTab.addId(((attr)f).getName(), ((attr)f).getType());
traverseExpression(currentClass, ((attr)f).getExpression(), objectSymTab, null);
} else {
if (Flags.semant_debug) {
System.out.println("Traversing Method : " + ((method)f).getName().toString());
}
// Add method to method Symbol Table,if already present, scope error
if (methodSymTab.containsKey(((method)f).getName().toString())) {
classTable.semantError(currentClass.getFilename(), f).println("Method " + ((method)f).getName().toString() + " is multiply defined");
}
traverseMethod(currentClass, ((method)f), objectSymTab);
}
}
}
}
/** Traverse method. Check formal parameters, return type and expressions **/
private void traverseMethod(class_c currentClass, method m, MySymbolTable objectSymTab) {
String className = currentClass.getName().toString();
// Start a new scope
objectSymTab.enterScope();
// Traverse formal arguments, adding them to scope
Formals formals = m.getFormals();
String methodname = m.getName().toString();
if (methodEnvironment.get(className).get(methodname) == null) {
methodEnvironment.get(className).put(methodname, new ArrayList<AbstractSymbol>());
}
for (Enumeration e = formals.getElements(); e.hasMoreElements();) {
formalc formal = ((formalc)e.nextElement());
if (objectSymTab.probe(formal.getName()) != null) {
classTable.semantError(currentClass.getFilename(), formal).println("Formal parameter " + formal.getName().toString() + " is multiply defined");
}
// Recover from multiply defined formal parameter. Just overwrite it
objectSymTab.addId(formal.getName(), formal.getType());
methodEnvironment.get(className).get(methodname).add(formal.getType());
}
methodEnvironment.get(className).get(methodname).add(m.getReturnType());
// Traverse expression
traverseExpression(currentClass, m.getExpression(), objectSymTab, null);
objectSymTab.exitScope();
}
/** Depending on what kind of expression, traverse down and fill in types and do scoping **/
private void traverseExpression(class_c currentClass, Expression expression, MySymbolTable objectSymTab, MySymbolTable methodSymTab) {
if (expression instanceof object) {
if ( ((object)expression).getName() == TreeConstants.self ) {
expression.set_type(TreeConstants.SELF_TYPE);
} else if (objectSymTab.lookup(((object)expression).getName()) == null) {
classTable.semantError(currentClass.getFilename(),expression).println("Undeclared identifier " + ((object)expression).getName());
expression.set_type(TreeConstants.Object_);
} else {
// Set the type of this object from the symbol table, if it exists
expression.set_type((AbstractSymbol)objectSymTab.lookup(((object)expression).getName()));
}
} else if (expression instanceof string_const) {
expression.set_type(TreeConstants.Str);
} else if (expression instanceof bool_const) {
expression.set_type(TreeConstants.Bool);
} else if (expression instanceof int_const) {
expression.set_type(TreeConstants.Int);
} else if (expression instanceof isvoid) {
expression.set_type(TreeConstants.Bool);
traverseExpression(currentClass, ((isvoid)expression).getExpression(), objectSymTab, methodSymTab);
} else if (expression instanceof new_) {
expression.set_type(((new_)expression).getTypeName());
} else if (expression instanceof comp) {
expression.set_type(TreeConstants.Bool);
traverseExpression(currentClass, ((comp)expression).getExpression(), objectSymTab, methodSymTab);
} else if (expression instanceof eq) {
expression.set_type(TreeConstants.Bool);
traverseExpression(currentClass, ((eq)expression).getLHS(), objectSymTab, methodSymTab);
traverseExpression(currentClass, ((eq)expression).getRHS(), objectSymTab, methodSymTab);
} else if (expression instanceof leq) {
expression.set_type(TreeConstants.Bool);
traverseExpression(currentClass, ((leq)expression).getLHS(), objectSymTab, methodSymTab);
traverseExpression(currentClass, ((leq)expression).getRHS(), objectSymTab, methodSymTab);
} else if (expression instanceof lt) {
expression.set_type(TreeConstants.Bool);
traverseExpression(currentClass, ((lt)expression).getLHS(), objectSymTab, methodSymTab);
traverseExpression(currentClass, ((lt)expression).getRHS(), objectSymTab, methodSymTab);
} else if (expression instanceof neg) {
expression.set_type(TreeConstants.Int);
traverseExpression(currentClass, ((neg)expression).getExpression(), objectSymTab, methodSymTab);
} else if (expression instanceof divide) {
expression.set_type(TreeConstants.Int);
traverseExpression(currentClass, ((divide)expression).getLHS(), objectSymTab, methodSymTab);
traverseExpression(currentClass, ((divide)expression).getRHS(), objectSymTab, methodSymTab);
} else if (expression instanceof sub) {
expression.set_type(TreeConstants.Int);
traverseExpression(currentClass, ((sub)expression).getLHS(), objectSymTab, methodSymTab);
traverseExpression(currentClass, ((sub)expression).getRHS(), objectSymTab, methodSymTab);
} else if (expression instanceof mul) {
expression.set_type(TreeConstants.Int);
traverseExpression(currentClass, ((mul)expression).getLHS(), objectSymTab, methodSymTab);
traverseExpression(currentClass, ((mul)expression).getRHS(), objectSymTab, methodSymTab);
} else if (expression instanceof plus) {
expression.set_type(TreeConstants.Int);
traverseExpression(currentClass, ((plus)expression).getLHS(), objectSymTab, methodSymTab);
traverseExpression(currentClass, ((plus)expression).getRHS(), objectSymTab, methodSymTab);
} else if (expression instanceof loop) {
expression.set_type(TreeConstants.Object_);
traverseExpression(currentClass, ((loop)expression).getPredicate(), objectSymTab, methodSymTab);
traverseExpression(currentClass, ((loop)expression).getBody(), objectSymTab, methodSymTab);
} else if (expression instanceof let) {
// Start a new scope, and add ID to Mysymboltable
objectSymTab.enterScope();
let letExpression = (let)expression;
objectSymTab.addId(letExpression.getIdentifier(), letExpression.getType());
traverseExpression(currentClass, letExpression.getInit(), objectSymTab, methodSymTab);
traverseExpression(currentClass, letExpression.getBody(), objectSymTab, methodSymTab);
// The type of let is the type if the last statement in the body
letExpression.set_type(letExpression.getBody().get_type());
objectSymTab.exitScope();
} else if (expression instanceof block) {
// Type of block is type of last expression
Expressions body = ((block)expression).getBody();
AbstractSymbol lastType = null;
for (Enumeration e = body.getElements(); e.hasMoreElements();) {
Expression nextExpression = (Expression)e.nextElement();
traverseExpression(currentClass, nextExpression, objectSymTab, methodSymTab);
lastType = nextExpression.get_type();
}
expression.set_type(lastType);
} else if (expression instanceof static_dispatch) {
static_dispatch e = (static_dispatch)expression;
traverseExpression( currentClass, e.getExpression(), objectSymTab, methodSymTab);
for (Enumeration enumer = e.getActual().getElements(); enumer.hasMoreElements();) {
traverseExpression(currentClass, ((Expression)enumer.nextElement()), objectSymTab, methodSymTab);
}
// TODO: Fill in the type of dispatch here ?
} else if (expression instanceof assign) {
if (objectSymTab.lookup(((assign)expression).getName()) == null) {
classTable.semantError(currentClass.getFilename(),expression).println("Undeclared identifier " + ((assign)expression).getName());
}
Expression e = ((assign)expression).getExpression();
traverseExpression( currentClass, e, objectSymTab, methodSymTab);
expression.set_type(e.get_type());
}
//dispatch
else if (expression instanceof dispatch) {
dispatch e = (dispatch)expression;
traverseExpression(currentClass, e.getExpression(), objectSymTab, methodSymTab);
for (Enumeration en = e.getActual().getElements(); en.hasMoreElements();) {
traverseExpression(currentClass, ((Expression)en.nextElement()), objectSymTab, methodSymTab);
}
}
// if then else statment
else if (expression instanceof cond) {
Expression then_exp = ((cond)expression).getThen();
Expression else_exp = ((cond)expression).getElse();
//traverseExpression(currentClass, ((cond)expression).getPredicate(), objectSymTab, methodSymTab);
traverseExpression(currentClass, then_exp, objectSymTab, methodSymTab);
traverseExpression(currentClass, else_exp, objectSymTab, methodSymTab);
//set final type of cond expression to the lowest common ancestor of then and else expressions
ArrayList<AbstractSymbol> inputTypes = new ArrayList<AbstractSymbol>();
inputTypes.add(then_exp.get_type());
inputTypes.add(else_exp.get_type());
AbstractSymbol finalType = LCA(inputTypes);
expression.set_type(finalType);
} else if (expression instanceof typcase) {
typcase caseExpression = (typcase)expression;
traverseExpression(currentClass, caseExpression.getExpression(), objectSymTab, methodSymTab);
ArrayList<AbstractSymbol> branchTypes = new ArrayList<AbstractSymbol>();
- Cases caselist = caseExpression.getCases();
+ Cases caseList = caseExpression.getCases();
//add all types returned from branch expressions to arraylist
for (Enumeration e = caseList.getElements(); e.hasMoreElements();){
branch c = (branch)e.nextElement();
//recurse on branch expression, add type to list of expressions
Expression branchExp = c.getExpression();
traverseExpression(currentClass, branchExp, objectSymTab, methodSymTab);
AbstractSymbol branchType = branchExp.get_type();
branchTypes.add(branchType);
}
//return the lca of all branch types
AbstractSymbol finalType = LCA(branchTypes);
expression.set_type(finalType);
}
}
// find the lowest common ancestor in inheritance tree
private AbstractSymbol LCA (ArrayList<AbstractSymbol> inputTypes) {
int smallestDepth = Integer.MAX_VALUE;
HashMap<AbstractSymbol, Integer> nodeToDepths = new HashMap<AbstractSymbol, Integer>();
for (AbstractSymbol type : inputTypes) {
int depth = classTable.getDepthFromNode(type.toString());
if (depth < smallestDepth) smallestDepth = depth;
nodeToDepths.put(type, depth);
}
ArrayList<String> ancestors = new ArrayList<String>();
//get parent to same depth
for (AbstractSymbol node : nodeToDepths.keySet()) {
int depth = nodeToDepths.get(node);
int difference = depth - smallestDepth;
String nodeName = node.toString();
for (int i = 0; i < difference; i++){
nodeName = classTable.getParent(nodeName);
}
ancestors.add(nodeName);
}
boolean LCA_notfound = true;
//getParent until all nodes are the same
while (LCA_notfound){
boolean LCAfound = true;
//compare all nodes to first node, doesn't matter because we check
//that all nodes must be the same.
String firstNode = ancestors.get(0);
for (String nodeName : ancestors){
if (!firstNode.equals(nodeName)) {
LCAfound = false;
break;
}
}
if (LCAfound == true){
LCA_notfound = false;
} else{
//getparent to every node
//create temporary arraylist and copy over elements
ArrayList<String> temp = new ArrayList<String>();
for (String ancestor: ancestors){
temp.add(ancestor);
}
ancestors.clear();
for (String ancestor: temp){
String parent = classTable.getParent(ancestor);
ancestors.add(parent);
}
}
}
//return type of LCA
return classTable.getClass(ancestors.get(0)).getName();
}
/** Second + Third pass through AST to perform inheritance **/
private void traverseASTWithTypecheck(Classes classes) {
// Start type checking from root
setupInheritedClass(TreeConstants.Object_.toString());
// Traverse AST and do type checking now
for (Enumeration e = classes.getElements(); e.hasMoreElements(); ) {
class_c currentClass = ((class_c)e.nextElement());
String className = currentClass.getName().toString();
if (Flags.semant_debug) {
System.out.println("Type checking Class " + className);
}
MySymbolTable objectSymTab = objectSymTabMap.get(className);
MySymbolTable methodSymTab = methodSymTabMap.get(className);
Features features = currentClass.getFeatures();
for (Enumeration fe = features.getElements(); fe.hasMoreElements();) {
Feature f = ((Feature)fe.nextElement());
if ( f instanceof attr ) {
//typeCheckAttribute(currentClass, f, objectSymTab, methodSymTab);
} else {
typeCheckMethod(currentClass, (method)f, objectSymTab, methodSymTab);
}
}
}
}
// Traverse the class graph and inherit methods/attributes from parent to child
private void setupInheritedClass(String currentClassName) {
if (Flags.semant_debug) {
System.out.println("Setting up inheritance for class:" + currentClassName);
}
HashMap<String, class_c> classMap = classTable.nameToClass;
class_c currentClass = classMap.get(currentClassName);
String parent = classTable.getParent(currentClassName);
MySymbolTable parentsSymTab = objectSymTabMap.get(parent);
HashMap<String, ArrayList<AbstractSymbol>> parentsMethodSymTab = methodEnvironment.get(parent);
MySymbolTable myObjSymTab = objectSymTabMap.get(currentClassName);
HashMap<String, ArrayList<AbstractSymbol>> myMethSymTab = methodEnvironment.get(currentClassName);
// Check for properly overrideen attributes/methods
if (Flags.semant_debug) {
System.out.println("Parent : " + parent);
System.out.println("Parent's object Symbol Table : " + parentsSymTab);
System.out.println("Parent's method Symbol Table : " + parentsMethodSymTab);
}
if (parentsSymTab != null) {
Features features = currentClass.getFeatures();
for (Enumeration fe = features.getElements(); fe.hasMoreElements();) {
Feature f = ((Feature)fe.nextElement());
// An attribute cannot be overridden
if (f instanceof attr) {
if (parentsSymTab.lookup(((attr)f).getName()) != null) {
classTable.semantError(currentClass.getFilename(), f).println("Attribute " + ((attr)f).getName().toString() + " is an attribute of an inherited class");
}
} else {
// A method can, provided the signature is the same
method m = (method)f;
String methodname = m.getName().toString();
if (parentsMethodSymTab != null && parentsMethodSymTab.containsKey(methodname)) {
ArrayList<AbstractSymbol> subclassSignature = myMethSymTab.get(methodname);
ArrayList<AbstractSymbol> inheritclassSignature = parentsMethodSymTab.get(methodname);
// Check if the two lists are exactly same
if (!subclassSignature.equals(inheritclassSignature)) {
classTable.semantError(currentClass.getFilename(), m).println("Overriding Method " + methodname + " should have same signature as in parent class " + parent);
}
}
}
}
/* For each id added to the outer scope hastable of the parent's Mysymboltable,
inherit the id if not already present, if present skip it, as this has been dealt with just above */
parentsSymTab.copy(myObjSymTab);
for (String methodName : parentsMethodSymTab.keySet()) {
if (!myMethSymTab.containsKey(methodName)) {
myMethSymTab.put(methodName, parentsMethodSymTab.get(methodName));
}
}
}
/* Recurse on the children of this class */
if (classTable.getChildren(currentClassName) != null) {
for (String child : classTable.getChildren(currentClassName)) {
setupInheritedClass(child);
}
}
}
/** Type check a method and all the expressions in it **/
private void typeCheckMethod(class_c currentClass, method m, MySymbolTable objectSymTab, MySymbolTable methodSymTab) {
String className = currentClass.getName().toString();
// Start a new scope
objectSymTab.enterScope();
// Traverse formal arguments, adding them to scope
Formals formals = m.getFormals();
String methodname = m.getName().toString();
if (Flags.semant_debug) {
System.out.println("Type checking method: " + methodname);
}
for (Enumeration e = formals.getElements(); e.hasMoreElements();) {
formalc formal = ((formalc)e.nextElement());
// Check if the type of this formal is valid
if ( !classTable.isValidType(formal.getType())) {
classTable.semantError(currentClass.getFilename(), formal).println("Class " + formal.getType() + " of formal parameter " + formal.getName() + " is undefined");
}
objectSymTab.addId(formal.getName(), formal.getType());
}
// Check return type
typeCheckExpression(currentClass, m.getExpression(), objectSymTab, methodSymTab);
if (m.getExpression().get_type() == null) {
if (Flags.semant_debug) {
System.out.println("ERROR: Expression has no type set!");
m.getExpression().dump_with_types(System.out, 1);
}
}
AbstractSymbol observedReturnType = m.getExpression().get_type();
ArrayList<AbstractSymbol> declaredFormalTypes = methodEnvironment.get(className).get(methodname);
AbstractSymbol declaredReturnType = declaredFormalTypes.get(declaredFormalTypes.size() - 1);
if (Flags.semant_debug) {
System.out.println("Inferred Return type: " + observedReturnType + ". Declared :" + declaredReturnType);
}
if (declaredReturnType == TreeConstants.SELF_TYPE) {
declaredReturnType = currentClass.getName();
}
if (observedReturnType == TreeConstants.SELF_TYPE) {
observedReturnType = currentClass.getName();
}
if (!classTable.checkConformance(observedReturnType, declaredReturnType)) {
classTable.semantError(currentClass.getFilename(), m).println("Inferred return type " + observedReturnType.toString() + " of method " + methodname + " does not conform to declared return type " + declaredReturnType.toString());
}
objectSymTab.exitScope();
}
private void typeCheckExpression(class_c currentClass, Expression expression, MySymbolTable objectSymTab, MySymbolTable methodSymTab) {
String className = currentClass.getName().getString();
if (expression instanceof object) {
// Wonder if this can ever happen
/*
AbstractSymbol name = ((object)expression).getName();
if (objectSymTab.lookup(name) != ((object)expression).get_type()) {
classTable.semantError(currentClass.getFilename(), expression).println("ID " + name + " has the wrong type");
}
*/
} else if (expression instanceof assign) {
assign e = (assign)expression;
typeCheckExpression(currentClass, e.getExpression(), objectSymTab, methodSymTab);
e.set_type(e.getExpression().get_type());
AbstractSymbol inferredType = e.getExpression().get_type();
AbstractSymbol declaredType = (AbstractSymbol) objectSymTab.lookup(e.getName());
if (Flags.semant_debug) {
System.out.println("Type checking assignment : ");
//e.dump_with_types(System.out, 1);
}
if (!classTable.checkConformance(inferredType, declaredType)) {
classTable.semantError(currentClass.getFilename(), e).println("Type " + inferredType + " of assigned expression does not conform to declared type " + declaredType + " of identifier " + e.getName());
}
} else if (expression instanceof cond) {
cond e = (cond)expression;
// Type check the expression for the predicate
typeCheckExpression(currentClass, e.getPredicate(), objectSymTab, methodSymTab);
typeCheckExpression(currentClass, e.getThen(), objectSymTab, methodSymTab);
typeCheckExpression(currentClass, e.getElse(), objectSymTab, methodSymTab);
// Set the type of the cond here
AbstractSymbol typeOfPredicate = e.getPredicate().get_type();
if (typeOfPredicate != TreeConstants.Bool) {
classTable.semantError(currentClass.getFilename(), e).println("Predicate of \"if\" does not have type Bool");
}
} else if (expression instanceof let) {
let e = (let)expression;
typeCheckExpression(currentClass, e.getInit(), objectSymTab, methodSymTab);
AbstractSymbol T0Prime = e.getType();
if (T0Prime == TreeConstants.SELF_TYPE) {
T0Prime = currentClass.getName();
}
if (!(e.getInit() instanceof no_expr)) {
AbstractSymbol T1 = e.getInit().get_type();
if (!classTable.checkConformance(T1, T0Prime)) {
classTable.semantError(currentClass.getFilename(), e).println("Inferred type " + T1 + " of initialization of " + e.getIdentifier() + " does not conform to identifier's declared type " + T0Prime);
}
}
objectSymTab.enterScope();
objectSymTab.addId(e.getIdentifier(), e.getType());
typeCheckExpression(currentClass, e.getBody(), objectSymTab, methodSymTab);
e.set_type(e.getBody().get_type());
objectSymTab.exitScope();
} else if (expression instanceof block) {
Expressions body = ((block)expression).getBody();
AbstractSymbol lastType = null;
for (Enumeration e = body.getElements(); e.hasMoreElements();) {
Expression nextExpression = (Expression)e.nextElement();
typeCheckExpression(currentClass, nextExpression, objectSymTab, methodSymTab);
lastType = nextExpression.get_type();
}
expression.set_type(lastType);
} else if (expression instanceof dispatch) {
dispatch e = (dispatch)expression;
String methodname = e.getName().toString();
typeCheckExpression(currentClass, e.getExpression(), objectSymTab, methodSymTab);
AbstractSymbol T0 = e.getExpression().get_type();
if (Flags.semant_debug) {
System.out.println("Type checking dispatch: " + methodname + " of class " + T0);
e.dump_with_types(System.out,1);
}
AbstractSymbol T0Prime = T0;
if (T0Prime == TreeConstants.SELF_TYPE) {
T0Prime = currentClass.getName();
}
// Check if method actually exists in class T0Prime
if (!methodEnvironment.get(T0Prime.toString()).containsKey(methodname)) {
classTable.semantError(currentClass.getFilename(), e).println("Dispatch to undefined method " + methodname);
} else {
// Check if actual and formal conform
ArrayList<AbstractSymbol> inferredTypes = new ArrayList<AbstractSymbol>();
for (Enumeration en = e.getActual().getElements(); en.hasMoreElements();) {
Expression next = (Expression)en.nextElement();
typeCheckExpression(currentClass, next , objectSymTab, methodSymTab);
inferredTypes.add(next.get_type());
}
ArrayList<AbstractSymbol> declaredTypes = methodEnvironment.get(T0Prime.toString()).get(methodname);
if (declaredTypes.size() != inferredTypes.size()+1) {
classTable.semantError(currentClass.getFilename(), e).println("Method " + methodname + " called with wrong number of arguments");
}
for (int i = 0; i < declaredTypes.size() - 1; i++) {
AbstractSymbol inferred = inferredTypes.get(i);
AbstractSymbol declared = declaredTypes.get(i);
if (!classTable.checkConformance(inferred, declared)) {
classTable.semantError(currentClass.getFilename(), e).println("In call of method " + methodname + " type " + inferred + " of parameter number " + i + " does not conform to declared type " + declared);
}
}
// Check, well actually set, return type
AbstractSymbol declaredReturnType = declaredTypes.get(declaredTypes.size() - 1);
if (declaredReturnType == TreeConstants.SELF_TYPE) {
declaredReturnType = T0;
}
e.set_type(declaredReturnType);
}
}
}
}
/** Defines AST constructor 'class_c'.
<p>
See <a href="TreeNode.html">TreeNode</a> for full documentation. */
class class_c extends Class_ {
protected AbstractSymbol name;
protected AbstractSymbol parent;
protected Features features;
protected AbstractSymbol filename;
/** Creates "class_c" AST node.
*
* @param lineNumber the line in the source file from which this node came.
* @param a0 initial value for name
* @param a1 initial value for parent
* @param a2 initial value for features
* @param a3 initial value for filename
*/
public class_c(int lineNumber, AbstractSymbol a1, AbstractSymbol a2, Features a3, AbstractSymbol a4) {
super(lineNumber);
name = a1;
parent = a2;
features = a3;
filename = a4;
}
public TreeNode copy() {
return new class_c(lineNumber, copy_AbstractSymbol(name), copy_AbstractSymbol(parent), (Features)features.copy(), copy_AbstractSymbol(filename));
}
public void dump(PrintStream out, int n) {
out.print(Utilities.pad(n) + "class_c\n");
dump_AbstractSymbol(out, n+2, name);
dump_AbstractSymbol(out, n+2, parent);
features.dump(out, n+2);
dump_AbstractSymbol(out, n+2, filename);
}
public AbstractSymbol getFilename() { return filename; }
public AbstractSymbol getName() { return name; }
public AbstractSymbol getParent() { return parent; }
public Features getFeatures() { return features; }
public void dump_with_types(PrintStream out, int n) {
dump_line(out, n);
out.println(Utilities.pad(n) + "_class");
dump_AbstractSymbol(out, n + 2, name);
dump_AbstractSymbol(out, n + 2, parent);
out.print(Utilities.pad(n + 2) + "\"");
Utilities.printEscapedString(out, filename.getString());
out.println("\"\n" + Utilities.pad(n + 2) + "(");
for (Enumeration e = features.getElements(); e.hasMoreElements();) {
((Feature)e.nextElement()).dump_with_types(out, n + 2);
}
out.println(Utilities.pad(n + 2) + ")");
}
}
/** Defines AST constructor 'method'.
<p>
See <a href="TreeNode.html">TreeNode</a> for full documentation. */
class method extends Feature {
protected AbstractSymbol name;
protected Formals formals;
protected AbstractSymbol return_type;
protected Expression expr;
/** Creates "method" AST node.
*
* @param lineNumber the line in the source file from which this node came.
* @param a0 initial value for name
* @param a1 initial value for formals
* @param a2 initial value for return_type
* @param a3 initial value for expr
*/
public method(int lineNumber, AbstractSymbol a1, Formals a2, AbstractSymbol a3, Expression a4) {
super(lineNumber);
name = a1;
formals = a2;
return_type = a3;
expr = a4;
}
public TreeNode copy() {
return new method(lineNumber, copy_AbstractSymbol(name), (Formals)formals.copy(), copy_AbstractSymbol(return_type), (Expression)expr.copy());
}
public AbstractSymbol getName() { return name; }
public Formals getFormals() { return formals; }
public Expression getExpression() { return expr; }
public AbstractSymbol getReturnType() { return return_type; }
public void dump(PrintStream out, int n) {
out.print(Utilities.pad(n) + "method\n");
dump_AbstractSymbol(out, n+2, name);
formals.dump(out, n+2);
dump_AbstractSymbol(out, n+2, return_type);
expr.dump(out, n+2);
}
public void dump_with_types(PrintStream out, int n) {
dump_line(out, n);
out.println(Utilities.pad(n) + "_method");
dump_AbstractSymbol(out, n + 2, name);
for (Enumeration e = formals.getElements(); e.hasMoreElements();) {
((Formal)e.nextElement()).dump_with_types(out, n + 2);
}
dump_AbstractSymbol(out, n + 2, return_type);
expr.dump_with_types(out, n + 2);
}
}
/** Defines AST constructor 'attr'.
<p>
See <a href="TreeNode.html">TreeNode</a> for full documentation. */
class attr extends Feature {
protected AbstractSymbol name;
protected AbstractSymbol type_decl;
protected Expression init;
/** Creates "attr" AST node.
*
* @param lineNumber the line in the source file from which this node came.
* @param a0 initial value for name
* @param a1 initial value for type_decl
* @param a2 initial value for init
*/
public attr(int lineNumber, AbstractSymbol a1, AbstractSymbol a2, Expression a3) {
super(lineNumber);
name = a1;
type_decl = a2;
init = a3;
}
public TreeNode copy() {
return new attr(lineNumber, copy_AbstractSymbol(name), copy_AbstractSymbol(type_decl), (Expression)init.copy());
}
//helper functions added in
public AbstractSymbol getName() { return name; }
public Expression getExpression() { return init; }
public AbstractSymbol getType() { return type_decl; }
public void dump(PrintStream out, int n) {
out.print(Utilities.pad(n) + "attr\n");
dump_AbstractSymbol(out, n+2, name);
dump_AbstractSymbol(out, n+2, type_decl);
init.dump(out, n+2);
}
public void dump_with_types(PrintStream out, int n) {
dump_line(out, n);
out.println(Utilities.pad(n) + "_attr");
dump_AbstractSymbol(out, n + 2, name);
dump_AbstractSymbol(out, n + 2, type_decl);
init.dump_with_types(out, n + 2);
}
}
/** Defines AST constructor 'formalc'.
<p>
See <a href="TreeNode.html">TreeNode</a> for full documentation. */
class formalc extends Formal {
protected AbstractSymbol name;
protected AbstractSymbol type_decl;
/** Creates "formalc" AST node.
*
* @param lineNumber the line in the source file from which this node came.
* @param a0 initial value for name
* @param a1 initial value for type_decl
*/
public formalc(int lineNumber, AbstractSymbol a1, AbstractSymbol a2) {
super(lineNumber);
name = a1;
type_decl = a2;
}
public TreeNode copy() {
return new formalc(lineNumber, copy_AbstractSymbol(name), copy_AbstractSymbol(type_decl));
}
public void dump(PrintStream out, int n) {
out.print(Utilities.pad(n) + "formalc\n");
dump_AbstractSymbol(out, n+2, name);
dump_AbstractSymbol(out, n+2, type_decl);
}
public AbstractSymbol getName() { return name; }
public AbstractSymbol getType() { return type_decl; }
public void dump_with_types(PrintStream out, int n) {
dump_line(out, n);
out.println(Utilities.pad(n) + "_formal");
dump_AbstractSymbol(out, n + 2, name);
dump_AbstractSymbol(out, n + 2, type_decl);
}
}
/** Defines AST constructor 'branch'.
<p>
See <a href="TreeNode.html">TreeNode</a> for full documentation. */
class branch extends Case {
protected AbstractSymbol name;
protected AbstractSymbol type_decl;
protected Expression expr;
/** Creates "branch" AST node.
*
* @param lineNumber the line in the source file from which this node came.
* @param a0 initial value for name
* @param a1 initial value for type_decl
* @param a2 initial value for expr
*/
public branch(int lineNumber, AbstractSymbol a1, AbstractSymbol a2, Expression a3) {
super(lineNumber);
name = a1;
type_decl = a2;
expr = a3;
}
public TreeNode copy() {
return new branch(lineNumber, copy_AbstractSymbol(name), copy_AbstractSymbol(type_decl), (Expression)expr.copy());
}
public void dump(PrintStream out, int n) {
out.print(Utilities.pad(n) + "branch\n");
dump_AbstractSymbol(out, n+2, name);
dump_AbstractSymbol(out, n+2, type_decl);
expr.dump(out, n+2);
}
public void dump_with_types(PrintStream out, int n) {
dump_line(out, n);
out.println(Utilities.pad(n) + "_branch");
dump_AbstractSymbol(out, n + 2, name);
dump_AbstractSymbol(out, n + 2, type_decl);
expr.dump_with_types(out, n + 2);
}
public AbstractSymbol getName() {return name;}
public AbstractSymbol getType() {return type_decl;}
public Expression getExpression() {return expr;}
}
/** Defines AST constructor 'assign'.
<p>
See <a href="TreeNode.html">TreeNode</a> for full documentation. */
class assign extends Expression {
protected AbstractSymbol name;
protected Expression expr;
/** Creates "assign" AST node.
*
* @param lineNumber the line in the source file from which this node came.
* @param a0 initial value for name
* @param a1 initial value for expr
*/
public assign(int lineNumber, AbstractSymbol a1, Expression a2) {
super(lineNumber);
name = a1;
expr = a2;
}
public TreeNode copy() {
return new assign(lineNumber, copy_AbstractSymbol(name), (Expression)expr.copy());
}
public void dump(PrintStream out, int n) {
out.print(Utilities.pad(n) + "assign\n");
dump_AbstractSymbol(out, n+2, name);
expr.dump(out, n+2);
}
public void dump_with_types(PrintStream out, int n) {
dump_line(out, n);
out.println(Utilities.pad(n) + "_assign");
dump_AbstractSymbol(out, n + 2, name);
expr.dump_with_types(out, n + 2);
dump_type(out, n);
}
public AbstractSymbol getName() { return name; }
public Expression getExpression() { return expr; }
}
/** Defines AST constructor 'static_dispatch'.
<p>
See <a href="TreeNode.html">TreeNode</a> for full documentation. */
class static_dispatch extends Expression {
protected Expression expr;
protected AbstractSymbol type_name;
protected AbstractSymbol name;
protected Expressions actual;
/** Creates "static_dispatch" AST node.
*
* @param lineNumber the line in the source file from which this node came.
* @param a0 initial value for expr
* @param a1 initial value for type_name
* @param a2 initial value for name
* @param a3 initial value for actual
*/
public static_dispatch(int lineNumber, Expression a1, AbstractSymbol a2, AbstractSymbol a3, Expressions a4) {
super(lineNumber);
expr = a1;
type_name = a2;
name = a3;
actual = a4;
}
public TreeNode copy() {
return new static_dispatch(lineNumber, (Expression)expr.copy(), copy_AbstractSymbol(type_name), copy_AbstractSymbol(name), (Expressions)actual.copy());
}
public void dump(PrintStream out, int n) {
out.print(Utilities.pad(n) + "static_dispatch\n");
expr.dump(out, n+2);
dump_AbstractSymbol(out, n+2, type_name);
dump_AbstractSymbol(out, n+2, name);
actual.dump(out, n+2);
}
public void dump_with_types(PrintStream out, int n) {
dump_line(out, n);
out.println(Utilities.pad(n) + "_static_dispatch");
expr.dump_with_types(out, n + 2);
dump_AbstractSymbol(out, n + 2, type_name);
dump_AbstractSymbol(out, n + 2, name);
out.println(Utilities.pad(n + 2) + "(");
for (Enumeration e = actual.getElements(); e.hasMoreElements();) {
((Expression)e.nextElement()).dump_with_types(out, n + 2);
}
out.println(Utilities.pad(n + 2) + ")");
dump_type(out, n);
}
public Expression getExpression() { return expr; }
public AbstractSymbol getTypeName() { return type_name; }
public AbstractSymbol getName() { return name; }
public Expressions getActual() { return actual; }
}
/** Defines AST constructor 'dispatch'.
<p>
See <a href="TreeNode.html">TreeNode</a> for full documentation. */
class dispatch extends Expression {
protected Expression expr;
protected AbstractSymbol name;
protected Expressions actual;
/** Creates "dispatch" AST node.
*
* @param lineNumber the line in the source file from which this node came.
* @param a0 initial value for expr
* @param a1 initial value for name
* @param a2 initial value for actual
*/
public dispatch(int lineNumber, Expression a1, AbstractSymbol a2, Expressions a3) {
super(lineNumber);
expr = a1;
name = a2;
actual = a3;
}
public TreeNode copy() {
return new dispatch(lineNumber, (Expression)expr.copy(), copy_AbstractSymbol(name), (Expressions)actual.copy());
}
public void dump(PrintStream out, int n) {
out.print(Utilities.pad(n) + "dispatch\n");
expr.dump(out, n+2);
dump_AbstractSymbol(out, n+2, name);
actual.dump(out, n+2);
}
public void dump_with_types(PrintStream out, int n) {
dump_line(out, n);
out.println(Utilities.pad(n) + "_dispatch");
expr.dump_with_types(out, n + 2);
dump_AbstractSymbol(out, n + 2, name);
out.println(Utilities.pad(n + 2) + "(");
for (Enumeration e = actual.getElements(); e.hasMoreElements();) {
((Expression)e.nextElement()).dump_with_types(out, n + 2);
}
out.println(Utilities.pad(n + 2) + ")");
dump_type(out, n);
}
public Expression getExpression() { return expr; }
public AbstractSymbol getName() { return name; }
public Expressions getActual() { return actual; }
}
/** Defines AST constructor 'cond'.
<p>
See <a href="TreeNode.html">TreeNode</a> for full documentation. */
class cond extends Expression {
protected Expression pred;
protected Expression then_exp;
protected Expression else_exp;
/** Creates "cond" AST node.
*
* @param lineNumber the line in the source file from which this node came.
* @param a0 initial value for pred
* @param a1 initial value for then_exp
* @param a2 initial value for else_exp
*/
public cond(int lineNumber, Expression a1, Expression a2, Expression a3) {
super(lineNumber);
pred = a1;
then_exp = a2;
else_exp = a3;
}
public TreeNode copy() {
return new cond(lineNumber, (Expression)pred.copy(), (Expression)then_exp.copy(), (Expression)else_exp.copy());
}
public void dump(PrintStream out, int n) {
out.print(Utilities.pad(n) + "cond\n");
pred.dump(out, n+2);
then_exp.dump(out, n+2);
else_exp.dump(out, n+2);
}
public void dump_with_types(PrintStream out, int n) {
dump_line(out, n);
out.println(Utilities.pad(n) + "_cond");
pred.dump_with_types(out, n + 2);
then_exp.dump_with_types(out, n + 2);
else_exp.dump_with_types(out, n + 2);
dump_type(out, n);
}
public Expression getPredicate() { return pred; }
public Expression getThen() { return then_exp; }
public Expression getElse() { return else_exp; }
}
/** Defines AST constructor 'loop'.
<p>
See <a href="TreeNode.html">TreeNode</a> for full documentation. */
class loop extends Expression {
protected Expression pred;
protected Expression body;
/** Creates "loop" AST node.
*
* @param lineNumber the line in the source file from which this node came.
* @param a0 initial value for pred
* @param a1 initial value for body
*/
public loop(int lineNumber, Expression a1, Expression a2) {
super(lineNumber);
pred = a1;
body = a2;
}
public TreeNode copy() {
return new loop(lineNumber, (Expression)pred.copy(), (Expression)body.copy());
}
public void dump(PrintStream out, int n) {
out.print(Utilities.pad(n) + "loop\n");
pred.dump(out, n+2);
body.dump(out, n+2);
}
public void dump_with_types(PrintStream out, int n) {
dump_line(out, n);
out.println(Utilities.pad(n) + "_loop");
pred.dump_with_types(out, n + 2);
body.dump_with_types(out, n + 2);
dump_type(out, n);
}
public Expression getPredicate() { return pred; }
public Expression getBody() { return body; }
}
/** Defines AST constructor 'typcase'.
<p>
See <a href="TreeNode.html">TreeNode</a> for full documentation. */
class typcase extends Expression {
protected Expression expr;
protected Cases cases;
/** Creates "typcase" AST node.
*
* @param lineNumber the line in the source file from which this node came.
* @param a0 initial value for expr
* @param a1 initial value for cases
*/
public typcase(int lineNumber, Expression a1, Cases a2) {
super(lineNumber);
expr = a1;
cases = a2;
}
public TreeNode copy() {
return new typcase(lineNumber, (Expression)expr.copy(), (Cases)cases.copy());
}
public void dump(PrintStream out, int n) {
out.print(Utilities.pad(n) + "typcase\n");
expr.dump(out, n+2);
cases.dump(out, n+2);
}
public void dump_with_types(PrintStream out, int n) {
dump_line(out, n);
out.println(Utilities.pad(n) + "_typcase");
expr.dump_with_types(out, n + 2);
for (Enumeration e = cases.getElements(); e.hasMoreElements();) {
((Case)e.nextElement()).dump_with_types(out, n + 2);
}
dump_type(out, n);
}
public Expression getExpression() {return expr; }
public Cases getCases() {return cases; }
}
/** Defines AST constructor 'block'.
<p>
See <a href="TreeNode.html">TreeNode</a> for full documentation. */
class block extends Expression {
protected Expressions body;
/** Creates "block" AST node.
*
* @param lineNumber the line in the source file from which this node came.
* @param a0 initial value for body
*/
public block(int lineNumber, Expressions a1) {
super(lineNumber);
body = a1;
}
public TreeNode copy() {
return new block(lineNumber, (Expressions)body.copy());
}
public void dump(PrintStream out, int n) {
out.print(Utilities.pad(n) + "block\n");
body.dump(out, n+2);
}
public void dump_with_types(PrintStream out, int n) {
dump_line(out, n);
out.println(Utilities.pad(n) + "_block");
for (Enumeration e = body.getElements(); e.hasMoreElements();) {
((Expression)e.nextElement()).dump_with_types(out, n + 2);
}
dump_type(out, n);
}
public Expressions getBody() { return body; }
}
/** Defines AST constructor 'let'.
<p>
See <a href="TreeNode.html">TreeNode</a> for full documentation. */
class let extends Expression {
protected AbstractSymbol identifier;
protected AbstractSymbol type_decl;
protected Expression init;
protected Expression body;
/** Creates "let" AST node.
*
* @param lineNumber the line in the source file from which this node came.
* @param a0 initial value for identifier
* @param a1 initial value for type_decl
* @param a2 initial value for init
* @param a3 initial value for body
*/
public let(int lineNumber, AbstractSymbol a1, AbstractSymbol a2, Expression a3, Expression a4) {
super(lineNumber);
identifier = a1;
type_decl = a2;
init = a3;
body = a4;
}
public TreeNode copy() {
return new let(lineNumber, copy_AbstractSymbol(identifier), copy_AbstractSymbol(type_decl), (Expression)init.copy(), (Expression)body.copy());
}
public void dump(PrintStream out, int n) {
out.print(Utilities.pad(n) + "let\n");
dump_AbstractSymbol(out, n+2, identifier);
dump_AbstractSymbol(out, n+2, type_decl);
init.dump(out, n+2);
body.dump(out, n+2);
}
public void dump_with_types(PrintStream out, int n) {
dump_line(out, n);
out.println(Utilities.pad(n) + "_let");
dump_AbstractSymbol(out, n + 2, identifier);
dump_AbstractSymbol(out, n + 2, type_decl);
init.dump_with_types(out, n + 2);
body.dump_with_types(out, n + 2);
dump_type(out, n);
}
public AbstractSymbol getIdentifier() { return identifier; }
public AbstractSymbol getType() { return type_decl; }
public Expression getInit() { return init; }
public Expression getBody() { return body; }
}
/** Defines AST constructor 'plus'.
<p>
See <a href="TreeNode.html">TreeNode</a> for full documentation. */
class plus extends Expression {
protected Expression e1;
protected Expression e2;
/** Creates "plus" AST node.
*
* @param lineNumber the line in the source file from which this node came.
* @param a0 initial value for e1
* @param a1 initial value for e2
*/
public plus(int lineNumber, Expression a1, Expression a2) {
super(lineNumber);
e1 = a1;
e2 = a2;
}
public TreeNode copy() {
return new plus(lineNumber, (Expression)e1.copy(), (Expression)e2.copy());
}
public void dump(PrintStream out, int n) {
out.print(Utilities.pad(n) + "plus\n");
e1.dump(out, n+2);
e2.dump(out, n+2);
}
public void dump_with_types(PrintStream out, int n) {
dump_line(out, n);
out.println(Utilities.pad(n) + "_plus");
e1.dump_with_types(out, n + 2);
e2.dump_with_types(out, n + 2);
dump_type(out, n);
}
public Expression getLHS() { return e1; }
public Expression getRHS() { return e2; }
}
/** Defines AST constructor 'sub'.
<p>
See <a href="TreeNode.html">TreeNode</a> for full documentation. */
class sub extends Expression {
protected Expression e1;
protected Expression e2;
/** Creates "sub" AST node.
*
* @param lineNumber the line in the source file from which this node came.
* @param a0 initial value for e1
* @param a1 initial value for e2
*/
public sub(int lineNumber, Expression a1, Expression a2) {
super(lineNumber);
e1 = a1;
e2 = a2;
}
public TreeNode copy() {
return new sub(lineNumber, (Expression)e1.copy(), (Expression)e2.copy());
}
public void dump(PrintStream out, int n) {
out.print(Utilities.pad(n) + "sub\n");
e1.dump(out, n+2);
e2.dump(out, n+2);
}
public void dump_with_types(PrintStream out, int n) {
dump_line(out, n);
out.println(Utilities.pad(n) + "_sub");
e1.dump_with_types(out, n + 2);
e2.dump_with_types(out, n + 2);
dump_type(out, n);
}
public Expression getLHS() { return e1; }
public Expression getRHS() { return e2; }
}
/** Defines AST constructor 'mul'.
<p>
See <a href="TreeNode.html">TreeNode</a> for full documentation. */
class mul extends Expression {
protected Expression e1;
protected Expression e2;
/** Creates "mul" AST node.
*
* @param lineNumber the line in the source file from which this node came.
* @param a0 initial value for e1
* @param a1 initial value for e2
*/
public mul(int lineNumber, Expression a1, Expression a2) {
super(lineNumber);
e1 = a1;
e2 = a2;
}
public TreeNode copy() {
return new mul(lineNumber, (Expression)e1.copy(), (Expression)e2.copy());
}
public void dump(PrintStream out, int n) {
out.print(Utilities.pad(n) + "mul\n");
e1.dump(out, n+2);
e2.dump(out, n+2);
}
public void dump_with_types(PrintStream out, int n) {
dump_line(out, n);
out.println(Utilities.pad(n) + "_mul");
e1.dump_with_types(out, n + 2);
e2.dump_with_types(out, n + 2);
dump_type(out, n);
}
public Expression getLHS() { return e1; }
public Expression getRHS() { return e2; }
}
/** Defines AST constructor 'divide'.
<p>
See <a href="TreeNode.html">TreeNode</a> for full documentation. */
class divide extends Expression {
protected Expression e1;
protected Expression e2;
/** Creates "divide" AST node.
*
* @param lineNumber the line in the source file from which this node came.
* @param a0 initial value for e1
* @param a1 initial value for e2
*/
public divide(int lineNumber, Expression a1, Expression a2) {
super(lineNumber);
e1 = a1;
e2 = a2;
}
public TreeNode copy() {
return new divide(lineNumber, (Expression)e1.copy(), (Expression)e2.copy());
}
public void dump(PrintStream out, int n) {
out.print(Utilities.pad(n) + "divide\n");
e1.dump(out, n+2);
e2.dump(out, n+2);
}
public void dump_with_types(PrintStream out, int n) {
dump_line(out, n);
out.println(Utilities.pad(n) + "_divide");
e1.dump_with_types(out, n + 2);
e2.dump_with_types(out, n + 2);
dump_type(out, n);
}
public Expression getLHS() { return e1; }
public Expression getRHS() { return e2; }
}
/** Defines AST constructor 'neg'.
<p>
See <a href="TreeNode.html">TreeNode</a> for full documentation. */
class neg extends Expression {
protected Expression e1;
/** Creates "neg" AST node.
*
* @param lineNumber the line in the source file from which this node came.
* @param a0 initial value for e1
*/
public neg(int lineNumber, Expression a1) {
super(lineNumber);
e1 = a1;
}
public TreeNode copy() {
return new neg(lineNumber, (Expression)e1.copy());
}
public void dump(PrintStream out, int n) {
out.print(Utilities.pad(n) + "neg\n");
e1.dump(out, n+2);
}
public void dump_with_types(PrintStream out, int n) {
dump_line(out, n);
out.println(Utilities.pad(n) + "_neg");
e1.dump_with_types(out, n + 2);
dump_type(out, n);
}
public Expression getExpression() { return e1; }
}
/** Defines AST constructor 'lt'.
<p>
See <a href="TreeNode.html">TreeNode</a> for full documentation. */
class lt extends Expression {
protected Expression e1;
protected Expression e2;
/** Creates "lt" AST node.
*
* @param lineNumber the line in the source file from which this node came.
* @param a0 initial value for e1
* @param a1 initial value for e2
*/
public lt(int lineNumber, Expression a1, Expression a2) {
super(lineNumber);
e1 = a1;
e2 = a2;
}
public TreeNode copy() {
return new lt(lineNumber, (Expression)e1.copy(), (Expression)e2.copy());
}
public void dump(PrintStream out, int n) {
out.print(Utilities.pad(n) + "lt\n");
e1.dump(out, n+2);
e2.dump(out, n+2);
}
public void dump_with_types(PrintStream out, int n) {
dump_line(out, n);
out.println(Utilities.pad(n) + "_lt");
e1.dump_with_types(out, n + 2);
e2.dump_with_types(out, n + 2);
dump_type(out, n);
}
public Expression getLHS() { return e1; }
public Expression getRHS() { return e2; }
}
/** Defines AST constructor 'eq'.
<p>
See <a href="TreeNode.html">TreeNode</a> for full documentation. */
class eq extends Expression {
protected Expression e1;
protected Expression e2;
/** Creates "eq" AST node.
*
* @param lineNumber the line in the source file from which this node came.
* @param a0 initial value for e1
* @param a1 initial value for e2
*/
public eq(int lineNumber, Expression a1, Expression a2) {
super(lineNumber);
e1 = a1;
e2 = a2;
}
public TreeNode copy() {
return new eq(lineNumber, (Expression)e1.copy(), (Expression)e2.copy());
}
public void dump(PrintStream out, int n) {
out.print(Utilities.pad(n) + "eq\n");
e1.dump(out, n+2);
e2.dump(out, n+2);
}
public void dump_with_types(PrintStream out, int n) {
dump_line(out, n);
out.println(Utilities.pad(n) + "_eq");
e1.dump_with_types(out, n + 2);
e2.dump_with_types(out, n + 2);
dump_type(out, n);
}
public Expression getLHS() { return e1; }
public Expression getRHS() { return e2; }
}
/** Defines AST constructor 'leq'.
<p>
See <a href="TreeNode.html">TreeNode</a> for full documentation. */
class leq extends Expression {
protected Expression e1;
protected Expression e2;
/** Creates "leq" AST node.
*
* @param lineNumber the line in the source file from which this node came.
* @param a0 initial value for e1
* @param a1 initial value for e2
*/
public leq(int lineNumber, Expression a1, Expression a2) {
super(lineNumber);
e1 = a1;
e2 = a2;
}
public TreeNode copy() {
return new leq(lineNumber, (Expression)e1.copy(), (Expression)e2.copy());
}
public void dump(PrintStream out, int n) {
out.print(Utilities.pad(n) + "leq\n");
e1.dump(out, n+2);
e2.dump(out, n+2);
}
public void dump_with_types(PrintStream out, int n) {
dump_line(out, n);
out.println(Utilities.pad(n) + "_leq");
e1.dump_with_types(out, n + 2);
e2.dump_with_types(out, n + 2);
dump_type(out, n);
}
public Expression getLHS() { return e1; }
public Expression getRHS() { return e2; }
}
/** Defines AST constructor 'comp'.
<p>
See <a href="TreeNode.html">TreeNode</a> for full documentation. */
class comp extends Expression {
protected Expression e1;
/** Creates "comp" AST node.
*
* @param lineNumber the line in the source file from which this node came.
* @param a0 initial value for e1
*/
public comp(int lineNumber, Expression a1) {
super(lineNumber);
e1 = a1;
}
public TreeNode copy() {
return new comp(lineNumber, (Expression)e1.copy());
}
public void dump(PrintStream out, int n) {
out.print(Utilities.pad(n) + "comp\n");
e1.dump(out, n+2);
}
public void dump_with_types(PrintStream out, int n) {
dump_line(out, n);
out.println(Utilities.pad(n) + "_comp");
e1.dump_with_types(out, n + 2);
dump_type(out, n);
}
public Expression getExpression() { return e1; }
}
/** Defines AST constructor 'int_const'.
<p>
See <a href="TreeNode.html">TreeNode</a> for full documentation. */
class int_const extends Expression {
protected AbstractSymbol token;
/** Creates "int_const" AST node.
*
* @param lineNumber the line in the source file from which this node came.
* @param a0 initial value for token
*/
public int_const(int lineNumber, AbstractSymbol a1) {
super(lineNumber);
token = a1;
}
public TreeNode copy() {
return new int_const(lineNumber, copy_AbstractSymbol(token));
}
public void dump(PrintStream out, int n) {
out.print(Utilities.pad(n) + "int_const\n");
dump_AbstractSymbol(out, n+2, token);
}
public void dump_with_types(PrintStream out, int n) {
dump_line(out, n);
out.println(Utilities.pad(n) + "_int");
dump_AbstractSymbol(out, n + 2, token);
dump_type(out, n);
}
}
/** Defines AST constructor 'bool_const'.
<p>
See <a href="TreeNode.html">TreeNode</a> for full documentation. */
class bool_const extends Expression {
protected Boolean val;
/** Creates "bool_const" AST node.
*
* @param lineNumber the line in the source file from which this node came.
* @param a0 initial value for val
*/
public bool_const(int lineNumber, Boolean a1) {
super(lineNumber);
val = a1;
}
public TreeNode copy() {
return new bool_const(lineNumber, copy_Boolean(val));
}
public void dump(PrintStream out, int n) {
out.print(Utilities.pad(n) + "bool_const\n");
dump_Boolean(out, n+2, val);
}
public void dump_with_types(PrintStream out, int n) {
dump_line(out, n);
out.println(Utilities.pad(n) + "_bool");
dump_Boolean(out, n + 2, val);
dump_type(out, n);
}
}
/** Defines AST constructor 'string_const'.
<p>
See <a href="TreeNode.html">TreeNode</a> for full documentation. */
class string_const extends Expression {
protected AbstractSymbol token;
/** Creates "string_const" AST node.
*
* @param lineNumber the line in the source file from which this node came.
* @param a0 initial value for token
*/
public string_const(int lineNumber, AbstractSymbol a1) {
super(lineNumber);
token = a1;
}
public TreeNode copy() {
return new string_const(lineNumber, copy_AbstractSymbol(token));
}
public void dump(PrintStream out, int n) {
out.print(Utilities.pad(n) + "string_const\n");
dump_AbstractSymbol(out, n+2, token);
}
public void dump_with_types(PrintStream out, int n) {
dump_line(out, n);
out.println(Utilities.pad(n) + "_string");
out.print(Utilities.pad(n + 2) + "\"");
Utilities.printEscapedString(out, token.getString());
out.println("\"");
dump_type(out, n);
}
}
/** Defines AST constructor 'new_'.
<p>
See <a href="TreeNode.html">TreeNode</a> for full documentation. */
class new_ extends Expression {
protected AbstractSymbol type_name;
/** Creates "new_" AST node.
*
* @param lineNumber the line in the source file from which this node came.
* @param a0 initial value for type_name
*/
public new_(int lineNumber, AbstractSymbol a1) {
super(lineNumber);
type_name = a1;
}
public TreeNode copy() {
return new new_(lineNumber, copy_AbstractSymbol(type_name));
}
public void dump(PrintStream out, int n) {
out.print(Utilities.pad(n) + "new_\n");
dump_AbstractSymbol(out, n+2, type_name);
}
public void dump_with_types(PrintStream out, int n) {
dump_line(out, n);
out.println(Utilities.pad(n) + "_new");
dump_AbstractSymbol(out, n + 2, type_name);
dump_type(out, n);
}
public AbstractSymbol getTypeName() { return type_name; }
}
/** Defines AST constructor 'isvoid'.
<p>
See <a href="TreeNode.html">TreeNode</a> for full documentation. */
class isvoid extends Expression {
protected Expression e1;
/** Creates "isvoid" AST node.
*
* @param lineNumber the line in the source file from which this node came.
* @param a0 initial value for e1
*/
public isvoid(int lineNumber, Expression a1) {
super(lineNumber);
e1 = a1;
}
public TreeNode copy() {
return new isvoid(lineNumber, (Expression)e1.copy());
}
public void dump(PrintStream out, int n) {
out.print(Utilities.pad(n) + "isvoid\n");
e1.dump(out, n+2);
}
public void dump_with_types(PrintStream out, int n) {
dump_line(out, n);
out.println(Utilities.pad(n) + "_isvoid");
e1.dump_with_types(out, n + 2);
dump_type(out, n);
}
public Expression getExpression() { return e1; }
}
/** Defines AST constructor 'no_expr'.
<p>
See <a href="TreeNode.html">TreeNode</a> for full documentation. */
class no_expr extends Expression {
/** Creates "no_expr" AST node.
*
* @param lineNumber the line in the source file from which this node came.
*/
public no_expr(int lineNumber) {
super(lineNumber);
}
public TreeNode copy() {
return new no_expr(lineNumber);
}
public void dump(PrintStream out, int n) {
out.print(Utilities.pad(n) + "no_expr\n");
}
public void dump_with_types(PrintStream out, int n) {
dump_line(out, n);
out.println(Utilities.pad(n) + "_no_expr");
dump_type(out, n);
}
}
/** Defines AST constructor 'object'.
<p>
See <a href="TreeNode.html">TreeNode</a> for full documentation. */
class object extends Expression {
protected AbstractSymbol name;
/** Creates "object" AST node.
*
* @param lineNumber the line in the source file from which this node came.
* @param a0 initial value for name
*/
public object(int lineNumber, AbstractSymbol a1) {
super(lineNumber);
name = a1;
}
public TreeNode copy() {
return new object(lineNumber, copy_AbstractSymbol(name));
}
public void dump(PrintStream out, int n) {
out.print(Utilities.pad(n) + "object\n");
dump_AbstractSymbol(out, n+2, name);
}
public void dump_with_types(PrintStream out, int n) {
dump_line(out, n);
out.println(Utilities.pad(n) + "_object");
dump_AbstractSymbol(out, n + 2, name);
dump_type(out, n);
}
public AbstractSymbol getName() { return name; }
}
| true | true | private void traverseExpression(class_c currentClass, Expression expression, MySymbolTable objectSymTab, MySymbolTable methodSymTab) {
if (expression instanceof object) {
if ( ((object)expression).getName() == TreeConstants.self ) {
expression.set_type(TreeConstants.SELF_TYPE);
} else if (objectSymTab.lookup(((object)expression).getName()) == null) {
classTable.semantError(currentClass.getFilename(),expression).println("Undeclared identifier " + ((object)expression).getName());
expression.set_type(TreeConstants.Object_);
} else {
// Set the type of this object from the symbol table, if it exists
expression.set_type((AbstractSymbol)objectSymTab.lookup(((object)expression).getName()));
}
} else if (expression instanceof string_const) {
expression.set_type(TreeConstants.Str);
} else if (expression instanceof bool_const) {
expression.set_type(TreeConstants.Bool);
} else if (expression instanceof int_const) {
expression.set_type(TreeConstants.Int);
} else if (expression instanceof isvoid) {
expression.set_type(TreeConstants.Bool);
traverseExpression(currentClass, ((isvoid)expression).getExpression(), objectSymTab, methodSymTab);
} else if (expression instanceof new_) {
expression.set_type(((new_)expression).getTypeName());
} else if (expression instanceof comp) {
expression.set_type(TreeConstants.Bool);
traverseExpression(currentClass, ((comp)expression).getExpression(), objectSymTab, methodSymTab);
} else if (expression instanceof eq) {
expression.set_type(TreeConstants.Bool);
traverseExpression(currentClass, ((eq)expression).getLHS(), objectSymTab, methodSymTab);
traverseExpression(currentClass, ((eq)expression).getRHS(), objectSymTab, methodSymTab);
} else if (expression instanceof leq) {
expression.set_type(TreeConstants.Bool);
traverseExpression(currentClass, ((leq)expression).getLHS(), objectSymTab, methodSymTab);
traverseExpression(currentClass, ((leq)expression).getRHS(), objectSymTab, methodSymTab);
} else if (expression instanceof lt) {
expression.set_type(TreeConstants.Bool);
traverseExpression(currentClass, ((lt)expression).getLHS(), objectSymTab, methodSymTab);
traverseExpression(currentClass, ((lt)expression).getRHS(), objectSymTab, methodSymTab);
} else if (expression instanceof neg) {
expression.set_type(TreeConstants.Int);
traverseExpression(currentClass, ((neg)expression).getExpression(), objectSymTab, methodSymTab);
} else if (expression instanceof divide) {
expression.set_type(TreeConstants.Int);
traverseExpression(currentClass, ((divide)expression).getLHS(), objectSymTab, methodSymTab);
traverseExpression(currentClass, ((divide)expression).getRHS(), objectSymTab, methodSymTab);
} else if (expression instanceof sub) {
expression.set_type(TreeConstants.Int);
traverseExpression(currentClass, ((sub)expression).getLHS(), objectSymTab, methodSymTab);
traverseExpression(currentClass, ((sub)expression).getRHS(), objectSymTab, methodSymTab);
} else if (expression instanceof mul) {
expression.set_type(TreeConstants.Int);
traverseExpression(currentClass, ((mul)expression).getLHS(), objectSymTab, methodSymTab);
traverseExpression(currentClass, ((mul)expression).getRHS(), objectSymTab, methodSymTab);
} else if (expression instanceof plus) {
expression.set_type(TreeConstants.Int);
traverseExpression(currentClass, ((plus)expression).getLHS(), objectSymTab, methodSymTab);
traverseExpression(currentClass, ((plus)expression).getRHS(), objectSymTab, methodSymTab);
} else if (expression instanceof loop) {
expression.set_type(TreeConstants.Object_);
traverseExpression(currentClass, ((loop)expression).getPredicate(), objectSymTab, methodSymTab);
traverseExpression(currentClass, ((loop)expression).getBody(), objectSymTab, methodSymTab);
} else if (expression instanceof let) {
// Start a new scope, and add ID to Mysymboltable
objectSymTab.enterScope();
let letExpression = (let)expression;
objectSymTab.addId(letExpression.getIdentifier(), letExpression.getType());
traverseExpression(currentClass, letExpression.getInit(), objectSymTab, methodSymTab);
traverseExpression(currentClass, letExpression.getBody(), objectSymTab, methodSymTab);
// The type of let is the type if the last statement in the body
letExpression.set_type(letExpression.getBody().get_type());
objectSymTab.exitScope();
} else if (expression instanceof block) {
// Type of block is type of last expression
Expressions body = ((block)expression).getBody();
AbstractSymbol lastType = null;
for (Enumeration e = body.getElements(); e.hasMoreElements();) {
Expression nextExpression = (Expression)e.nextElement();
traverseExpression(currentClass, nextExpression, objectSymTab, methodSymTab);
lastType = nextExpression.get_type();
}
expression.set_type(lastType);
} else if (expression instanceof static_dispatch) {
static_dispatch e = (static_dispatch)expression;
traverseExpression( currentClass, e.getExpression(), objectSymTab, methodSymTab);
for (Enumeration enumer = e.getActual().getElements(); enumer.hasMoreElements();) {
traverseExpression(currentClass, ((Expression)enumer.nextElement()), objectSymTab, methodSymTab);
}
// TODO: Fill in the type of dispatch here ?
} else if (expression instanceof assign) {
if (objectSymTab.lookup(((assign)expression).getName()) == null) {
classTable.semantError(currentClass.getFilename(),expression).println("Undeclared identifier " + ((assign)expression).getName());
}
Expression e = ((assign)expression).getExpression();
traverseExpression( currentClass, e, objectSymTab, methodSymTab);
expression.set_type(e.get_type());
}
//dispatch
else if (expression instanceof dispatch) {
dispatch e = (dispatch)expression;
traverseExpression(currentClass, e.getExpression(), objectSymTab, methodSymTab);
for (Enumeration en = e.getActual().getElements(); en.hasMoreElements();) {
traverseExpression(currentClass, ((Expression)en.nextElement()), objectSymTab, methodSymTab);
}
}
// if then else statment
else if (expression instanceof cond) {
Expression then_exp = ((cond)expression).getThen();
Expression else_exp = ((cond)expression).getElse();
//traverseExpression(currentClass, ((cond)expression).getPredicate(), objectSymTab, methodSymTab);
traverseExpression(currentClass, then_exp, objectSymTab, methodSymTab);
traverseExpression(currentClass, else_exp, objectSymTab, methodSymTab);
//set final type of cond expression to the lowest common ancestor of then and else expressions
ArrayList<AbstractSymbol> inputTypes = new ArrayList<AbstractSymbol>();
inputTypes.add(then_exp.get_type());
inputTypes.add(else_exp.get_type());
AbstractSymbol finalType = LCA(inputTypes);
expression.set_type(finalType);
} else if (expression instanceof typcase) {
typcase caseExpression = (typcase)expression;
traverseExpression(currentClass, caseExpression.getExpression(), objectSymTab, methodSymTab);
ArrayList<AbstractSymbol> branchTypes = new ArrayList<AbstractSymbol>();
Cases caselist = caseExpression.getCases();
//add all types returned from branch expressions to arraylist
for (Enumeration e = caseList.getElements(); e.hasMoreElements();){
branch c = (branch)e.nextElement();
//recurse on branch expression, add type to list of expressions
Expression branchExp = c.getExpression();
traverseExpression(currentClass, branchExp, objectSymTab, methodSymTab);
AbstractSymbol branchType = branchExp.get_type();
branchTypes.add(branchType);
}
//return the lca of all branch types
AbstractSymbol finalType = LCA(branchTypes);
expression.set_type(finalType);
}
}
| private void traverseExpression(class_c currentClass, Expression expression, MySymbolTable objectSymTab, MySymbolTable methodSymTab) {
if (expression instanceof object) {
if ( ((object)expression).getName() == TreeConstants.self ) {
expression.set_type(TreeConstants.SELF_TYPE);
} else if (objectSymTab.lookup(((object)expression).getName()) == null) {
classTable.semantError(currentClass.getFilename(),expression).println("Undeclared identifier " + ((object)expression).getName());
expression.set_type(TreeConstants.Object_);
} else {
// Set the type of this object from the symbol table, if it exists
expression.set_type((AbstractSymbol)objectSymTab.lookup(((object)expression).getName()));
}
} else if (expression instanceof string_const) {
expression.set_type(TreeConstants.Str);
} else if (expression instanceof bool_const) {
expression.set_type(TreeConstants.Bool);
} else if (expression instanceof int_const) {
expression.set_type(TreeConstants.Int);
} else if (expression instanceof isvoid) {
expression.set_type(TreeConstants.Bool);
traverseExpression(currentClass, ((isvoid)expression).getExpression(), objectSymTab, methodSymTab);
} else if (expression instanceof new_) {
expression.set_type(((new_)expression).getTypeName());
} else if (expression instanceof comp) {
expression.set_type(TreeConstants.Bool);
traverseExpression(currentClass, ((comp)expression).getExpression(), objectSymTab, methodSymTab);
} else if (expression instanceof eq) {
expression.set_type(TreeConstants.Bool);
traverseExpression(currentClass, ((eq)expression).getLHS(), objectSymTab, methodSymTab);
traverseExpression(currentClass, ((eq)expression).getRHS(), objectSymTab, methodSymTab);
} else if (expression instanceof leq) {
expression.set_type(TreeConstants.Bool);
traverseExpression(currentClass, ((leq)expression).getLHS(), objectSymTab, methodSymTab);
traverseExpression(currentClass, ((leq)expression).getRHS(), objectSymTab, methodSymTab);
} else if (expression instanceof lt) {
expression.set_type(TreeConstants.Bool);
traverseExpression(currentClass, ((lt)expression).getLHS(), objectSymTab, methodSymTab);
traverseExpression(currentClass, ((lt)expression).getRHS(), objectSymTab, methodSymTab);
} else if (expression instanceof neg) {
expression.set_type(TreeConstants.Int);
traverseExpression(currentClass, ((neg)expression).getExpression(), objectSymTab, methodSymTab);
} else if (expression instanceof divide) {
expression.set_type(TreeConstants.Int);
traverseExpression(currentClass, ((divide)expression).getLHS(), objectSymTab, methodSymTab);
traverseExpression(currentClass, ((divide)expression).getRHS(), objectSymTab, methodSymTab);
} else if (expression instanceof sub) {
expression.set_type(TreeConstants.Int);
traverseExpression(currentClass, ((sub)expression).getLHS(), objectSymTab, methodSymTab);
traverseExpression(currentClass, ((sub)expression).getRHS(), objectSymTab, methodSymTab);
} else if (expression instanceof mul) {
expression.set_type(TreeConstants.Int);
traverseExpression(currentClass, ((mul)expression).getLHS(), objectSymTab, methodSymTab);
traverseExpression(currentClass, ((mul)expression).getRHS(), objectSymTab, methodSymTab);
} else if (expression instanceof plus) {
expression.set_type(TreeConstants.Int);
traverseExpression(currentClass, ((plus)expression).getLHS(), objectSymTab, methodSymTab);
traverseExpression(currentClass, ((plus)expression).getRHS(), objectSymTab, methodSymTab);
} else if (expression instanceof loop) {
expression.set_type(TreeConstants.Object_);
traverseExpression(currentClass, ((loop)expression).getPredicate(), objectSymTab, methodSymTab);
traverseExpression(currentClass, ((loop)expression).getBody(), objectSymTab, methodSymTab);
} else if (expression instanceof let) {
// Start a new scope, and add ID to Mysymboltable
objectSymTab.enterScope();
let letExpression = (let)expression;
objectSymTab.addId(letExpression.getIdentifier(), letExpression.getType());
traverseExpression(currentClass, letExpression.getInit(), objectSymTab, methodSymTab);
traverseExpression(currentClass, letExpression.getBody(), objectSymTab, methodSymTab);
// The type of let is the type if the last statement in the body
letExpression.set_type(letExpression.getBody().get_type());
objectSymTab.exitScope();
} else if (expression instanceof block) {
// Type of block is type of last expression
Expressions body = ((block)expression).getBody();
AbstractSymbol lastType = null;
for (Enumeration e = body.getElements(); e.hasMoreElements();) {
Expression nextExpression = (Expression)e.nextElement();
traverseExpression(currentClass, nextExpression, objectSymTab, methodSymTab);
lastType = nextExpression.get_type();
}
expression.set_type(lastType);
} else if (expression instanceof static_dispatch) {
static_dispatch e = (static_dispatch)expression;
traverseExpression( currentClass, e.getExpression(), objectSymTab, methodSymTab);
for (Enumeration enumer = e.getActual().getElements(); enumer.hasMoreElements();) {
traverseExpression(currentClass, ((Expression)enumer.nextElement()), objectSymTab, methodSymTab);
}
// TODO: Fill in the type of dispatch here ?
} else if (expression instanceof assign) {
if (objectSymTab.lookup(((assign)expression).getName()) == null) {
classTable.semantError(currentClass.getFilename(),expression).println("Undeclared identifier " + ((assign)expression).getName());
}
Expression e = ((assign)expression).getExpression();
traverseExpression( currentClass, e, objectSymTab, methodSymTab);
expression.set_type(e.get_type());
}
//dispatch
else if (expression instanceof dispatch) {
dispatch e = (dispatch)expression;
traverseExpression(currentClass, e.getExpression(), objectSymTab, methodSymTab);
for (Enumeration en = e.getActual().getElements(); en.hasMoreElements();) {
traverseExpression(currentClass, ((Expression)en.nextElement()), objectSymTab, methodSymTab);
}
}
// if then else statment
else if (expression instanceof cond) {
Expression then_exp = ((cond)expression).getThen();
Expression else_exp = ((cond)expression).getElse();
//traverseExpression(currentClass, ((cond)expression).getPredicate(), objectSymTab, methodSymTab);
traverseExpression(currentClass, then_exp, objectSymTab, methodSymTab);
traverseExpression(currentClass, else_exp, objectSymTab, methodSymTab);
//set final type of cond expression to the lowest common ancestor of then and else expressions
ArrayList<AbstractSymbol> inputTypes = new ArrayList<AbstractSymbol>();
inputTypes.add(then_exp.get_type());
inputTypes.add(else_exp.get_type());
AbstractSymbol finalType = LCA(inputTypes);
expression.set_type(finalType);
} else if (expression instanceof typcase) {
typcase caseExpression = (typcase)expression;
traverseExpression(currentClass, caseExpression.getExpression(), objectSymTab, methodSymTab);
ArrayList<AbstractSymbol> branchTypes = new ArrayList<AbstractSymbol>();
Cases caseList = caseExpression.getCases();
//add all types returned from branch expressions to arraylist
for (Enumeration e = caseList.getElements(); e.hasMoreElements();){
branch c = (branch)e.nextElement();
//recurse on branch expression, add type to list of expressions
Expression branchExp = c.getExpression();
traverseExpression(currentClass, branchExp, objectSymTab, methodSymTab);
AbstractSymbol branchType = branchExp.get_type();
branchTypes.add(branchType);
}
//return the lca of all branch types
AbstractSymbol finalType = LCA(branchTypes);
expression.set_type(finalType);
}
}
|
diff --git a/modules/extension/app-schema/sample-data-access/src/main/java/org/geotools/data/SampleDataAccessFeatureSource.java b/modules/extension/app-schema/sample-data-access/src/main/java/org/geotools/data/SampleDataAccessFeatureSource.java
index 50d92279c7..dd767592b4 100644
--- a/modules/extension/app-schema/sample-data-access/src/main/java/org/geotools/data/SampleDataAccessFeatureSource.java
+++ b/modules/extension/app-schema/sample-data-access/src/main/java/org/geotools/data/SampleDataAccessFeatureSource.java
@@ -1,188 +1,188 @@
/*
* GeoTools - The Open Source Java GIS Toolkit
* http://geotools.org
*
* (C) 2008-2011, Open Source Geospatial Foundation (OSGeo)
*
* 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;
* version 2.1 of the License.
*
* 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.
*/
package org.geotools.data;
import java.awt.RenderingHints;
import java.awt.RenderingHints.Key;
import java.io.IOException;
import java.util.HashSet;
import java.util.Set;
import org.geotools.data.DataAccess;
import org.geotools.data.FeatureListener;
import org.geotools.data.FeatureSource;
import org.geotools.data.Query;
import org.geotools.data.QueryCapabilities;
import org.geotools.data.ResourceInfo;
import org.geotools.feature.FeatureCollection;
import org.geotools.geometry.jts.ReferencedEnvelope;
import org.opengis.feature.Feature;
import org.opengis.feature.type.FeatureType;
import org.opengis.feature.type.Name;
import org.opengis.filter.Filter;
/**
* {@link FeatureSource} for {@link SampleDataAccess}.
*
* @author Ben Caradoc-Davies (CSIRO Earth Science and Resource Engineering)
* @version $Id$
*
*
*
* @source $URL$
* @since 2.6
*/
public class SampleDataAccessFeatureSource implements FeatureSource<FeatureType, Feature> {
/**
* Unsupported operation.
*
* @see org.geotools.data.FeatureSource#addFeatureListener(org.geotools.data.FeatureListener)
*/
public void addFeatureListener(FeatureListener listener) {
throw new UnsupportedOperationException();
}
/**
* Not yet implemented.
*
* @see org.geotools.data.FeatureSource#getBounds()
*/
public ReferencedEnvelope getBounds() throws IOException {
// FIXME implement this
return null;
}
/**
* Not yet implemented.
*
* @see org.geotools.data.FeatureSource#getBounds(org.geotools.data.Query)
*/
public ReferencedEnvelope getBounds(Query query) throws IOException {
// FIXME implement this
return null;
}
/**
* Not yet implemented.
*
* @see org.geotools.data.FeatureSource#getCount(org.geotools.data.Query)
*/
public int getCount(Query query) throws IOException {
// FIXME implement this
return 0;
}
/**
* Not yet implemented.
*
* @see org.geotools.data.FeatureSource#getDataStore()
*/
public DataAccess<FeatureType, Feature> getDataStore() {
// FIXME implement this
return null;
}
/**
* Return a {@link FeatureCollection} containing the sample features.
*
* @see org.geotools.data.FeatureSource#getFeatures()
*/
public FeatureCollection<FeatureType, Feature> getFeatures() throws IOException {
- FeatureCollection<FeatureType, Feature> fc = new SampleDataAccessFeatureCollection();
+ SampleDataAccessFeatureCollection fc = new SampleDataAccessFeatureCollection();
fc.addAll(SampleDataAccessData.createMappedFeatures());
return fc;
}
/**
* Not yet implemented.
*
* @see org.geotools.data.FeatureSource#getFeatures(org.opengis.filter.Filter)
*/
public FeatureCollection<FeatureType, Feature> getFeatures(Filter filter) throws IOException {
// FIXME temporary hack
return getFeatures();
}
/**
* Not yet implemented.
*
* @see org.geotools.data.FeatureSource#getFeatures(org.geotools.data.Query)
*/
public FeatureCollection<FeatureType, Feature> getFeatures(Query query) throws IOException {
// FIXME temporary hack
return getFeatures();
}
/**
* Not yet implemented.
*
* @see org.geotools.data.FeatureSource#getInfo()
*/
public ResourceInfo getInfo() {
// FIXME implement this
return null;
}
/**
* Not yet implemented.
*
* @see org.geotools.data.FeatureSource#getName()
*/
public Name getName() {
return SampleDataAccessData.MAPPEDFEATURE_TYPE_NAME;
}
/**
* Not yet implemented.
*
* @see org.geotools.data.FeatureSource#getQueryCapabilities()
*/
public QueryCapabilities getQueryCapabilities() {
// FIXME implement this
return null;
}
/**
* Return feature type.
*
* @see org.geotools.data.FeatureSource#getSchema()
*/
public FeatureType getSchema() {
return SampleDataAccessData.MAPPEDFEATURE_TYPE;
}
/**
* Return an empty list of no hints.
*
* @see org.geotools.data.FeatureSource#getSupportedHints()
*/
public Set<Key> getSupportedHints() {
return new HashSet<RenderingHints.Key>();
}
/**
* Unsupported operation.
*
* @see org.geotools.data.FeatureSource#removeFeatureListener(org.geotools.data.FeatureListener)
*/
public void removeFeatureListener(FeatureListener listener) {
throw new UnsupportedOperationException();
}
}
| true | true | public FeatureCollection<FeatureType, Feature> getFeatures() throws IOException {
FeatureCollection<FeatureType, Feature> fc = new SampleDataAccessFeatureCollection();
fc.addAll(SampleDataAccessData.createMappedFeatures());
return fc;
}
| public FeatureCollection<FeatureType, Feature> getFeatures() throws IOException {
SampleDataAccessFeatureCollection fc = new SampleDataAccessFeatureCollection();
fc.addAll(SampleDataAccessData.createMappedFeatures());
return fc;
}
|
diff --git a/src/org/biojava/bio/program/ssbind/HSPSummaryStAXHandler.java b/src/org/biojava/bio/program/ssbind/HSPSummaryStAXHandler.java
index 520a8a26e..20ccbbb29 100644
--- a/src/org/biojava/bio/program/ssbind/HSPSummaryStAXHandler.java
+++ b/src/org/biojava/bio/program/ssbind/HSPSummaryStAXHandler.java
@@ -1,113 +1,113 @@
/*
* BioJava development code
*
* This code may be freely distributed and modified under the
* terms of the GNU Lesser General Public Licence. This should
* be distributed with the code. If you do not have a copy,
* see:
*
* http://www.gnu.org/copyleft/lesser.html
*
* Copyright for this code is held jointly by the individual
* authors. These should be listed in @author doc comments.
*
* For more information on the BioJava project and its aims,
* or to join the biojava-l mailing list, visit the home page
* at:
*
* http://www.biojava.org/
*
*/
package org.biojava.bio.program.ssbind;
import org.biojava.bio.search.SearchContentHandler;
import org.biojava.utils.stax.StAXContentHandler;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
/**
* <code>HSPSummaryStAXHandler</code> handles the HSPSummary element
* of BioJava BlastLike XML.
*
* @author Keith James
* @since 1.3
*/
public class HSPSummaryStAXHandler extends SeqSimilarityStAXHandler
{
public static final StAXHandlerFactory HSPSUMMARY_HANDLER_FACTORY =
new StAXHandlerFactory()
{
public StAXContentHandler getHandler(SeqSimilarityStAXAdapter ssContext)
{
return new HSPSummaryStAXHandler(ssContext);
}
};
HSPSummaryStAXHandler(SeqSimilarityStAXAdapter ssContext)
{
super(ssContext);
}
protected void handleStartElement(String nsURI,
String localName,
String qName,
Attributes attrs)
throws SAXException
{
SearchContentHandler sch = ssContext.getSearchContentHandler();
// score, expectValue, numberOfIdentities, alignmentSize and
// percentageIdentity always present in valid XML
sch.addSubHitProperty("score", attrs.getValue("score"));
sch.addSubHitProperty("expectValue", attrs.getValue("expectValue"));
sch.addSubHitProperty("numberOfIdentities",
attrs.getValue("numberOfIdentities"));
sch.addSubHitProperty("alignmentSize",
attrs.getValue("alignmentSize"));
sch.addSubHitProperty("percentageIdentity",
attrs.getValue("percentageIdentity"));
String attr;
attr = attrs.getValue("bitScore");
if (attr != null)
sch.addSubHitProperty("bitScore", attr);
attr = attrs.getValue("pValue");
if (attr != null)
sch.addSubHitProperty("pValue", attr);
- attr = attrs.getValue("numberOfPositives");
+ attr = attrs.getValue("numberOfIdentities");
if (attr != null)
- sch.addSubHitProperty("numberOfPositives", attr);
+ sch.addSubHitProperty("numberOfIdentities", attr);
attr = attrs.getValue("numberOfPositives");
if (attr != null)
sch.addSubHitProperty("numberOfPositives", attr);
attr = attrs.getValue("querySequenceType");
if (attr != null)
sch.addSubHitProperty("querySequenceType", attr);
attr = attrs.getValue("hitSequenceType");
if (attr != null)
sch.addSubHitProperty("subjectSequenceType", attr);
// These are not explicitly set by BLASTP
attr = attrs.getValue("queryStrand");
if (attr != null)
sch.addSubHitProperty("queryStrand", attr);
attr = attrs.getValue("hitStrand");
if (attr != null)
sch.addSubHitProperty("subjectStrand", attr);
attr = attrs.getValue("queryFrame");
if (attr != null)
sch.addSubHitProperty("queryFrame", attr);
attr = attrs.getValue("hitFrame");
if (attr != null)
sch.addSubHitProperty("subjectFrame", attr);
}
}
| false | true | protected void handleStartElement(String nsURI,
String localName,
String qName,
Attributes attrs)
throws SAXException
{
SearchContentHandler sch = ssContext.getSearchContentHandler();
// score, expectValue, numberOfIdentities, alignmentSize and
// percentageIdentity always present in valid XML
sch.addSubHitProperty("score", attrs.getValue("score"));
sch.addSubHitProperty("expectValue", attrs.getValue("expectValue"));
sch.addSubHitProperty("numberOfIdentities",
attrs.getValue("numberOfIdentities"));
sch.addSubHitProperty("alignmentSize",
attrs.getValue("alignmentSize"));
sch.addSubHitProperty("percentageIdentity",
attrs.getValue("percentageIdentity"));
String attr;
attr = attrs.getValue("bitScore");
if (attr != null)
sch.addSubHitProperty("bitScore", attr);
attr = attrs.getValue("pValue");
if (attr != null)
sch.addSubHitProperty("pValue", attr);
attr = attrs.getValue("numberOfPositives");
if (attr != null)
sch.addSubHitProperty("numberOfPositives", attr);
attr = attrs.getValue("numberOfPositives");
if (attr != null)
sch.addSubHitProperty("numberOfPositives", attr);
attr = attrs.getValue("querySequenceType");
if (attr != null)
sch.addSubHitProperty("querySequenceType", attr);
attr = attrs.getValue("hitSequenceType");
if (attr != null)
sch.addSubHitProperty("subjectSequenceType", attr);
// These are not explicitly set by BLASTP
attr = attrs.getValue("queryStrand");
if (attr != null)
sch.addSubHitProperty("queryStrand", attr);
attr = attrs.getValue("hitStrand");
if (attr != null)
sch.addSubHitProperty("subjectStrand", attr);
attr = attrs.getValue("queryFrame");
if (attr != null)
sch.addSubHitProperty("queryFrame", attr);
attr = attrs.getValue("hitFrame");
if (attr != null)
sch.addSubHitProperty("subjectFrame", attr);
}
| protected void handleStartElement(String nsURI,
String localName,
String qName,
Attributes attrs)
throws SAXException
{
SearchContentHandler sch = ssContext.getSearchContentHandler();
// score, expectValue, numberOfIdentities, alignmentSize and
// percentageIdentity always present in valid XML
sch.addSubHitProperty("score", attrs.getValue("score"));
sch.addSubHitProperty("expectValue", attrs.getValue("expectValue"));
sch.addSubHitProperty("numberOfIdentities",
attrs.getValue("numberOfIdentities"));
sch.addSubHitProperty("alignmentSize",
attrs.getValue("alignmentSize"));
sch.addSubHitProperty("percentageIdentity",
attrs.getValue("percentageIdentity"));
String attr;
attr = attrs.getValue("bitScore");
if (attr != null)
sch.addSubHitProperty("bitScore", attr);
attr = attrs.getValue("pValue");
if (attr != null)
sch.addSubHitProperty("pValue", attr);
attr = attrs.getValue("numberOfIdentities");
if (attr != null)
sch.addSubHitProperty("numberOfIdentities", attr);
attr = attrs.getValue("numberOfPositives");
if (attr != null)
sch.addSubHitProperty("numberOfPositives", attr);
attr = attrs.getValue("querySequenceType");
if (attr != null)
sch.addSubHitProperty("querySequenceType", attr);
attr = attrs.getValue("hitSequenceType");
if (attr != null)
sch.addSubHitProperty("subjectSequenceType", attr);
// These are not explicitly set by BLASTP
attr = attrs.getValue("queryStrand");
if (attr != null)
sch.addSubHitProperty("queryStrand", attr);
attr = attrs.getValue("hitStrand");
if (attr != null)
sch.addSubHitProperty("subjectStrand", attr);
attr = attrs.getValue("queryFrame");
if (attr != null)
sch.addSubHitProperty("queryFrame", attr);
attr = attrs.getValue("hitFrame");
if (attr != null)
sch.addSubHitProperty("subjectFrame", attr);
}
|
diff --git a/htroot/yacy/transferRWI.java b/htroot/yacy/transferRWI.java
index 72c8cd151..cc3f5f642 100644
--- a/htroot/yacy/transferRWI.java
+++ b/htroot/yacy/transferRWI.java
@@ -1,214 +1,221 @@
// transferRWI.java
// -----------------------
// part of the AnomicHTTPD caching proxy
// (C) by Michael Peter Christen; [email protected]
// first published on http://www.anomic.de
// Frankfurt, Germany, 2004, 2005
//
// $LastChangedDate$
// $LastChangedRevision$
// $LastChangedBy$
//
// 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
//
// Using this software in any meaning (reading, learning, copying, compiling,
// running) means that you agree that the Author(s) is (are) not responsible
// for cost, loss of data or any harm that may be caused directly or indirectly
// by usage of this softare or this documentation. The usage of this software
// is on your own risk. The installation and usage (starting/running) of this
// software may allow other people or application to access your computer and
// any attached devices and is highly dependent on the configuration of the
// software which must be done by the user of the software; the author(s) is
// (are) also not responsible for proper configuration and usage of the
// software, even if provoked by documentation provided together with
// the software.
//
// Any changes to this file according to the GPL as documented in the file
// gpl.txt aside this file in the shipment you received can be done to the
// lines that follows this copyright notice here, but changes must not be
// done inside the copyright notive above. A re-distribution must contain
// the intact and unchanged copyright notice.
// Contributions and changes to the program code must be marked as such.
// You must compile this file with
// javac -classpath .:../classes transferRWI.java
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import de.anomic.http.httpHeader;
import de.anomic.index.indexEntry;
import de.anomic.index.indexURLEntry;
import de.anomic.plasma.plasmaSwitchboard;
import de.anomic.server.serverCore;
import de.anomic.server.serverObjects;
import de.anomic.server.serverSwitch;
import de.anomic.yacy.yacyCore;
import de.anomic.yacy.yacySeed;
import de.anomic.yacy.yacyDHTAction;
public final class transferRWI {
public static serverObjects respond(httpHeader header, serverObjects post, serverSwitch ss) throws InterruptedException {
if (post == null || ss == null) { return null; }
// return variable that accumulates replacements
final plasmaSwitchboard sb = (plasmaSwitchboard) ss;
final serverObjects prop = new serverObjects();
if (prop == null || sb == null) { return null; }
// request values
final String iam = post.get("iam", ""); // seed hash of requester
// final String youare = (String) post.get("youare", ""); // seed hash of the target peer, needed for network stability
// final String key = (String) post.get("key", ""); // transmission key
final int wordc = Integer.parseInt(post.get("wordc", "")); // number of different words
final int entryc = Integer.parseInt(post.get("entryc", "")); // number of entries in indexes
byte[] indexes = post.get("indexes", "").getBytes(); // the indexes, as list of word entries
boolean granted = sb.getConfig("allowReceiveIndex", "false").equals("true");
boolean blockBlacklist = sb.getConfig("indexReceiveBlockBlacklist", "false").equals("true");
boolean checkLimit = sb.getConfigBool("indexDistribution.transferRWIReceiptLimitEnabled", true);
final long cachelimit = sb.getConfigLong("indexDistribution.dhtReceiptLimit", 1000);
final yacySeed otherPeer = yacyCore.seedDB.get(iam);
final String otherPeerName = iam + ":" + ((otherPeer == null) ? "NULL" : (otherPeer.getName() + "/" + otherPeer.getVersion()));
// response values
String result = "ok";
StringBuffer unknownURLs = new StringBuffer();
int pause = 0;
+ boolean shortCacheFlush = false;
if ((granted) && (sb.wordIndex.busyCacheFlush)) {
// wait a little bit, maybe we got into a short flush slot
- for (int i = 0; i < 20; i++) if (sb.wordIndex.busyCacheFlush) try {Thread.sleep(100);} catch (InterruptedException e) {}
+ for (int i = 0; i < 20; i++) {
+ if (!(sb.wordIndex.busyCacheFlush)) {
+ shortCacheFlush = true;
+ break;
+ }
+ try {Thread.sleep(100);} catch (InterruptedException e) {}
+ }
}
if (!granted) {
// we dont want to receive indexes
sb.getLog().logInfo("Rejecting RWIs from peer " + otherPeerName + ". Not granted.");
result = "not_granted";
pause = 0;
} else if (checkLimit && sb.wordIndex.kSize() > cachelimit) {
// we are too busy to receive indexes
sb.getLog().logInfo("Rejecting RWIs from peer " + otherPeerName + ". We are too busy (buffersize=" + sb.wordIndex.kSize() + ").");
granted = false; // don't accept more words if there are too many words to flush
result = "busy";
pause = 60000;
- } else if ((checkLimit && sb.wordIndex.wSize() > sb.wordIndex.getMaxWordCount()) || (sb.wordIndex.busyCacheFlush)) {
+ } else if ((checkLimit && sb.wordIndex.wSize() > sb.wordIndex.getMaxWordCount()) || ((sb.wordIndex.busyCacheFlush) && (!shortCacheFlush))) {
// we are too busy flushing the ramCache to receive indexes
sb.getLog().logInfo("Rejecting RWIs from peer " + otherPeerName + ". We are too busy (wordcachesize=" + sb.wordIndex.wSize() + ").");
granted = false; // don't accept more words if there are too many words to flush
result = "busy";
pause = 300000;
} else {
// we want and can receive indexes
// log value status (currently added to find outOfMemory error
sb.getLog().logFine("Processing " + indexes.length + " bytes / " + wordc + " words / " + entryc + " entries from " + otherPeerName);
final long startProcess = System.currentTimeMillis();
// decode request
final LinkedList v = new LinkedList();
int s = 0;
int e;
while (s < indexes.length) {
e = s; while (e < indexes.length) if (indexes[e++] < 32) {e--; break;}
if ((e - s) > 0) v.add(new String(indexes, s, e - s));
s = e; while (s < indexes.length) if (indexes[s++] >= 32) {s--; break;}
}
// free memory
indexes = null;
// the value-vector should now have the same length as entryc
if (v.size() != entryc) sb.getLog().logSevere("ERROR WITH ENTRY COUNTER: v=" + v.size() + ", entryc=" + entryc);
// now parse the Strings in the value-vector and write index entries
String estring;
int p;
String wordHash;
String urlHash;
indexEntry iEntry;
int wordhashesSize = v.size();
final HashSet unknownURL = new HashSet();
final HashSet knownURL = new HashSet();
String[] wordhashes = new String[v.size()];
int received = 0;
int blocked = 0;
int receivedURL = 0;
for (int i = 0; i < wordhashesSize; i++) {
serverCore.checkInterruption();
estring = (String) v.removeFirst();
p = estring.indexOf("{");
if (p > 0) {
wordHash = estring.substring(0, p);
wordhashes[received] = wordHash;
iEntry = new indexURLEntry(estring.substring(p));
urlHash = iEntry.urlHash();
if ((blockBlacklist) && (plasmaSwitchboard.urlBlacklist.hashInBlacklistedCache(urlHash))) {
//int deleted = sb.wordIndex.tryRemoveURLs(urlHash);
yacyCore.log.logFine("transferRWI: blocked blacklisted URLHash '" + urlHash + "' from peer " + otherPeerName + "; deleted 1 URL entries from RWIs");
blocked++;
} else {
sb.wordIndex.addEntry(wordHash, iEntry, System.currentTimeMillis(), true);
serverCore.checkInterruption();
if (!(knownURL.contains(urlHash)||unknownURL.contains(urlHash))) {
try {
if (sb.urlPool.loadedURL.exists(urlHash)) {
knownURL.add(urlHash);
} else {
unknownURL.add(urlHash);
}
} catch (Exception ex) {
sb.getLog().logWarning(
"transferRWI: DB-Error while trying to determine if URL with hash '" +
urlHash + "' is known.", ex);
}
receivedURL++;
}
received++;
}
}
}
yacyCore.seedDB.mySeed.incRI(received);
// finally compose the unknownURL hash list
final Iterator it = unknownURL.iterator();
unknownURLs.ensureCapacity(unknownURL.size()*13);
while (it.hasNext()) {
unknownURLs.append(",").append((String) it.next());
}
if (unknownURLs.length() > 0) { unknownURLs.delete(0, 1); }
if (wordhashes.length == 0) {
sb.getLog().logInfo("Received 0 RWIs from " + otherPeerName + ", processed in " + (System.currentTimeMillis() - startProcess) + " milliseconds, requesting " + unknownURL.size() + " URLs");
} else {
final double avdist = (yacyDHTAction.dhtDistance(yacyCore.seedDB.mySeed.hash, wordhashes[0]) + yacyDHTAction.dhtDistance(yacyCore.seedDB.mySeed.hash, wordhashes[received - 1])) / 2.0;
sb.getLog().logInfo("Received " + received + " Entries " + wordc + " Words [" + wordhashes[0] + " .. " + wordhashes[received - 1] + "]/" + avdist + " from " + otherPeerName + ", processed in " + (System.currentTimeMillis() - startProcess) + " milliseconds, requesting " + unknownURL.size() + "/" + receivedURL + " URLs, blocked " + blocked + " RWIs");
}
result = "ok";
if (checkLimit) {
pause = (sb.wordIndex.kSize() < 500) ? 0 : 60 * sb.wordIndex.kSize(); // estimation of necessary pause time
}
}
prop.put("unknownURL", unknownURLs.toString());
prop.put("result", result);
prop.put("pause", Integer.toString(pause));
// return rewrite properties
return prop;
}
}
| false | true | public static serverObjects respond(httpHeader header, serverObjects post, serverSwitch ss) throws InterruptedException {
if (post == null || ss == null) { return null; }
// return variable that accumulates replacements
final plasmaSwitchboard sb = (plasmaSwitchboard) ss;
final serverObjects prop = new serverObjects();
if (prop == null || sb == null) { return null; }
// request values
final String iam = post.get("iam", ""); // seed hash of requester
// final String youare = (String) post.get("youare", ""); // seed hash of the target peer, needed for network stability
// final String key = (String) post.get("key", ""); // transmission key
final int wordc = Integer.parseInt(post.get("wordc", "")); // number of different words
final int entryc = Integer.parseInt(post.get("entryc", "")); // number of entries in indexes
byte[] indexes = post.get("indexes", "").getBytes(); // the indexes, as list of word entries
boolean granted = sb.getConfig("allowReceiveIndex", "false").equals("true");
boolean blockBlacklist = sb.getConfig("indexReceiveBlockBlacklist", "false").equals("true");
boolean checkLimit = sb.getConfigBool("indexDistribution.transferRWIReceiptLimitEnabled", true);
final long cachelimit = sb.getConfigLong("indexDistribution.dhtReceiptLimit", 1000);
final yacySeed otherPeer = yacyCore.seedDB.get(iam);
final String otherPeerName = iam + ":" + ((otherPeer == null) ? "NULL" : (otherPeer.getName() + "/" + otherPeer.getVersion()));
// response values
String result = "ok";
StringBuffer unknownURLs = new StringBuffer();
int pause = 0;
if ((granted) && (sb.wordIndex.busyCacheFlush)) {
// wait a little bit, maybe we got into a short flush slot
for (int i = 0; i < 20; i++) if (sb.wordIndex.busyCacheFlush) try {Thread.sleep(100);} catch (InterruptedException e) {}
}
if (!granted) {
// we dont want to receive indexes
sb.getLog().logInfo("Rejecting RWIs from peer " + otherPeerName + ". Not granted.");
result = "not_granted";
pause = 0;
} else if (checkLimit && sb.wordIndex.kSize() > cachelimit) {
// we are too busy to receive indexes
sb.getLog().logInfo("Rejecting RWIs from peer " + otherPeerName + ". We are too busy (buffersize=" + sb.wordIndex.kSize() + ").");
granted = false; // don't accept more words if there are too many words to flush
result = "busy";
pause = 60000;
} else if ((checkLimit && sb.wordIndex.wSize() > sb.wordIndex.getMaxWordCount()) || (sb.wordIndex.busyCacheFlush)) {
// we are too busy flushing the ramCache to receive indexes
sb.getLog().logInfo("Rejecting RWIs from peer " + otherPeerName + ". We are too busy (wordcachesize=" + sb.wordIndex.wSize() + ").");
granted = false; // don't accept more words if there are too many words to flush
result = "busy";
pause = 300000;
} else {
// we want and can receive indexes
// log value status (currently added to find outOfMemory error
sb.getLog().logFine("Processing " + indexes.length + " bytes / " + wordc + " words / " + entryc + " entries from " + otherPeerName);
final long startProcess = System.currentTimeMillis();
// decode request
final LinkedList v = new LinkedList();
int s = 0;
int e;
while (s < indexes.length) {
e = s; while (e < indexes.length) if (indexes[e++] < 32) {e--; break;}
if ((e - s) > 0) v.add(new String(indexes, s, e - s));
s = e; while (s < indexes.length) if (indexes[s++] >= 32) {s--; break;}
}
// free memory
indexes = null;
// the value-vector should now have the same length as entryc
if (v.size() != entryc) sb.getLog().logSevere("ERROR WITH ENTRY COUNTER: v=" + v.size() + ", entryc=" + entryc);
// now parse the Strings in the value-vector and write index entries
String estring;
int p;
String wordHash;
String urlHash;
indexEntry iEntry;
int wordhashesSize = v.size();
final HashSet unknownURL = new HashSet();
final HashSet knownURL = new HashSet();
String[] wordhashes = new String[v.size()];
int received = 0;
int blocked = 0;
int receivedURL = 0;
for (int i = 0; i < wordhashesSize; i++) {
serverCore.checkInterruption();
estring = (String) v.removeFirst();
p = estring.indexOf("{");
if (p > 0) {
wordHash = estring.substring(0, p);
wordhashes[received] = wordHash;
iEntry = new indexURLEntry(estring.substring(p));
urlHash = iEntry.urlHash();
if ((blockBlacklist) && (plasmaSwitchboard.urlBlacklist.hashInBlacklistedCache(urlHash))) {
//int deleted = sb.wordIndex.tryRemoveURLs(urlHash);
yacyCore.log.logFine("transferRWI: blocked blacklisted URLHash '" + urlHash + "' from peer " + otherPeerName + "; deleted 1 URL entries from RWIs");
blocked++;
} else {
sb.wordIndex.addEntry(wordHash, iEntry, System.currentTimeMillis(), true);
serverCore.checkInterruption();
if (!(knownURL.contains(urlHash)||unknownURL.contains(urlHash))) {
try {
if (sb.urlPool.loadedURL.exists(urlHash)) {
knownURL.add(urlHash);
} else {
unknownURL.add(urlHash);
}
} catch (Exception ex) {
sb.getLog().logWarning(
"transferRWI: DB-Error while trying to determine if URL with hash '" +
urlHash + "' is known.", ex);
}
receivedURL++;
}
received++;
}
}
}
yacyCore.seedDB.mySeed.incRI(received);
// finally compose the unknownURL hash list
final Iterator it = unknownURL.iterator();
unknownURLs.ensureCapacity(unknownURL.size()*13);
while (it.hasNext()) {
unknownURLs.append(",").append((String) it.next());
}
if (unknownURLs.length() > 0) { unknownURLs.delete(0, 1); }
if (wordhashes.length == 0) {
sb.getLog().logInfo("Received 0 RWIs from " + otherPeerName + ", processed in " + (System.currentTimeMillis() - startProcess) + " milliseconds, requesting " + unknownURL.size() + " URLs");
} else {
final double avdist = (yacyDHTAction.dhtDistance(yacyCore.seedDB.mySeed.hash, wordhashes[0]) + yacyDHTAction.dhtDistance(yacyCore.seedDB.mySeed.hash, wordhashes[received - 1])) / 2.0;
sb.getLog().logInfo("Received " + received + " Entries " + wordc + " Words [" + wordhashes[0] + " .. " + wordhashes[received - 1] + "]/" + avdist + " from " + otherPeerName + ", processed in " + (System.currentTimeMillis() - startProcess) + " milliseconds, requesting " + unknownURL.size() + "/" + receivedURL + " URLs, blocked " + blocked + " RWIs");
}
result = "ok";
if (checkLimit) {
pause = (sb.wordIndex.kSize() < 500) ? 0 : 60 * sb.wordIndex.kSize(); // estimation of necessary pause time
}
}
prop.put("unknownURL", unknownURLs.toString());
prop.put("result", result);
prop.put("pause", Integer.toString(pause));
// return rewrite properties
return prop;
}
| public static serverObjects respond(httpHeader header, serverObjects post, serverSwitch ss) throws InterruptedException {
if (post == null || ss == null) { return null; }
// return variable that accumulates replacements
final plasmaSwitchboard sb = (plasmaSwitchboard) ss;
final serverObjects prop = new serverObjects();
if (prop == null || sb == null) { return null; }
// request values
final String iam = post.get("iam", ""); // seed hash of requester
// final String youare = (String) post.get("youare", ""); // seed hash of the target peer, needed for network stability
// final String key = (String) post.get("key", ""); // transmission key
final int wordc = Integer.parseInt(post.get("wordc", "")); // number of different words
final int entryc = Integer.parseInt(post.get("entryc", "")); // number of entries in indexes
byte[] indexes = post.get("indexes", "").getBytes(); // the indexes, as list of word entries
boolean granted = sb.getConfig("allowReceiveIndex", "false").equals("true");
boolean blockBlacklist = sb.getConfig("indexReceiveBlockBlacklist", "false").equals("true");
boolean checkLimit = sb.getConfigBool("indexDistribution.transferRWIReceiptLimitEnabled", true);
final long cachelimit = sb.getConfigLong("indexDistribution.dhtReceiptLimit", 1000);
final yacySeed otherPeer = yacyCore.seedDB.get(iam);
final String otherPeerName = iam + ":" + ((otherPeer == null) ? "NULL" : (otherPeer.getName() + "/" + otherPeer.getVersion()));
// response values
String result = "ok";
StringBuffer unknownURLs = new StringBuffer();
int pause = 0;
boolean shortCacheFlush = false;
if ((granted) && (sb.wordIndex.busyCacheFlush)) {
// wait a little bit, maybe we got into a short flush slot
for (int i = 0; i < 20; i++) {
if (!(sb.wordIndex.busyCacheFlush)) {
shortCacheFlush = true;
break;
}
try {Thread.sleep(100);} catch (InterruptedException e) {}
}
}
if (!granted) {
// we dont want to receive indexes
sb.getLog().logInfo("Rejecting RWIs from peer " + otherPeerName + ". Not granted.");
result = "not_granted";
pause = 0;
} else if (checkLimit && sb.wordIndex.kSize() > cachelimit) {
// we are too busy to receive indexes
sb.getLog().logInfo("Rejecting RWIs from peer " + otherPeerName + ". We are too busy (buffersize=" + sb.wordIndex.kSize() + ").");
granted = false; // don't accept more words if there are too many words to flush
result = "busy";
pause = 60000;
} else if ((checkLimit && sb.wordIndex.wSize() > sb.wordIndex.getMaxWordCount()) || ((sb.wordIndex.busyCacheFlush) && (!shortCacheFlush))) {
// we are too busy flushing the ramCache to receive indexes
sb.getLog().logInfo("Rejecting RWIs from peer " + otherPeerName + ". We are too busy (wordcachesize=" + sb.wordIndex.wSize() + ").");
granted = false; // don't accept more words if there are too many words to flush
result = "busy";
pause = 300000;
} else {
// we want and can receive indexes
// log value status (currently added to find outOfMemory error
sb.getLog().logFine("Processing " + indexes.length + " bytes / " + wordc + " words / " + entryc + " entries from " + otherPeerName);
final long startProcess = System.currentTimeMillis();
// decode request
final LinkedList v = new LinkedList();
int s = 0;
int e;
while (s < indexes.length) {
e = s; while (e < indexes.length) if (indexes[e++] < 32) {e--; break;}
if ((e - s) > 0) v.add(new String(indexes, s, e - s));
s = e; while (s < indexes.length) if (indexes[s++] >= 32) {s--; break;}
}
// free memory
indexes = null;
// the value-vector should now have the same length as entryc
if (v.size() != entryc) sb.getLog().logSevere("ERROR WITH ENTRY COUNTER: v=" + v.size() + ", entryc=" + entryc);
// now parse the Strings in the value-vector and write index entries
String estring;
int p;
String wordHash;
String urlHash;
indexEntry iEntry;
int wordhashesSize = v.size();
final HashSet unknownURL = new HashSet();
final HashSet knownURL = new HashSet();
String[] wordhashes = new String[v.size()];
int received = 0;
int blocked = 0;
int receivedURL = 0;
for (int i = 0; i < wordhashesSize; i++) {
serverCore.checkInterruption();
estring = (String) v.removeFirst();
p = estring.indexOf("{");
if (p > 0) {
wordHash = estring.substring(0, p);
wordhashes[received] = wordHash;
iEntry = new indexURLEntry(estring.substring(p));
urlHash = iEntry.urlHash();
if ((blockBlacklist) && (plasmaSwitchboard.urlBlacklist.hashInBlacklistedCache(urlHash))) {
//int deleted = sb.wordIndex.tryRemoveURLs(urlHash);
yacyCore.log.logFine("transferRWI: blocked blacklisted URLHash '" + urlHash + "' from peer " + otherPeerName + "; deleted 1 URL entries from RWIs");
blocked++;
} else {
sb.wordIndex.addEntry(wordHash, iEntry, System.currentTimeMillis(), true);
serverCore.checkInterruption();
if (!(knownURL.contains(urlHash)||unknownURL.contains(urlHash))) {
try {
if (sb.urlPool.loadedURL.exists(urlHash)) {
knownURL.add(urlHash);
} else {
unknownURL.add(urlHash);
}
} catch (Exception ex) {
sb.getLog().logWarning(
"transferRWI: DB-Error while trying to determine if URL with hash '" +
urlHash + "' is known.", ex);
}
receivedURL++;
}
received++;
}
}
}
yacyCore.seedDB.mySeed.incRI(received);
// finally compose the unknownURL hash list
final Iterator it = unknownURL.iterator();
unknownURLs.ensureCapacity(unknownURL.size()*13);
while (it.hasNext()) {
unknownURLs.append(",").append((String) it.next());
}
if (unknownURLs.length() > 0) { unknownURLs.delete(0, 1); }
if (wordhashes.length == 0) {
sb.getLog().logInfo("Received 0 RWIs from " + otherPeerName + ", processed in " + (System.currentTimeMillis() - startProcess) + " milliseconds, requesting " + unknownURL.size() + " URLs");
} else {
final double avdist = (yacyDHTAction.dhtDistance(yacyCore.seedDB.mySeed.hash, wordhashes[0]) + yacyDHTAction.dhtDistance(yacyCore.seedDB.mySeed.hash, wordhashes[received - 1])) / 2.0;
sb.getLog().logInfo("Received " + received + " Entries " + wordc + " Words [" + wordhashes[0] + " .. " + wordhashes[received - 1] + "]/" + avdist + " from " + otherPeerName + ", processed in " + (System.currentTimeMillis() - startProcess) + " milliseconds, requesting " + unknownURL.size() + "/" + receivedURL + " URLs, blocked " + blocked + " RWIs");
}
result = "ok";
if (checkLimit) {
pause = (sb.wordIndex.kSize() < 500) ? 0 : 60 * sb.wordIndex.kSize(); // estimation of necessary pause time
}
}
prop.put("unknownURL", unknownURLs.toString());
prop.put("result", result);
prop.put("pause", Integer.toString(pause));
// return rewrite properties
return prop;
}
|
diff --git a/us9098/client/src/main/java/com/funambol/client/test/media/MediaRobot.java b/us9098/client/src/main/java/com/funambol/client/test/media/MediaRobot.java
index 0f4f44c3..7f512768 100755
--- a/us9098/client/src/main/java/com/funambol/client/test/media/MediaRobot.java
+++ b/us9098/client/src/main/java/com/funambol/client/test/media/MediaRobot.java
@@ -1,681 +1,683 @@
/*
* Funambol is a mobile platform developed by Funambol, Inc.
* Copyright (C) 2010 Funambol, Inc.
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU Affero General Public License version 3 as published by
* the Free Software Foundation with the addition of the following permission
* added to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED
* WORK IN WHICH THE COPYRIGHT IS OWNED BY FUNAMBOL, FUNAMBOL DISCLAIMS THE
* WARRANTY OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
*
* 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 Affero General Public License
* along with this program; if not, see http://www.gnu.org/licenses or write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301 USA.
*
* You can contact Funambol, Inc. headquarters at 643 Bair Island Road, Suite
* 305, Redwood City, CA 94063, USA, or at email address [email protected].
*
* The interactive user interfaces in modified source and object code versions
* of this program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU Affero General Public License version 3.
*
* In accordance with Section 7(b) of the GNU Affero General Public License
* version 3, these Appropriate Legal Notices must retain the display of the
* "Powered by Funambol" logo. If the display of the logo is not reasonably
* feasible for technical reasons, the Appropriate Legal Notices must display
* the words "Powered by Funambol".
*/
package com.funambol.client.test.media;
import java.util.Enumeration;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import com.funambol.client.source.AppSyncSource;
import com.funambol.client.source.MediaMetadata;
import com.funambol.client.source.FunambolFileSyncSource;
import com.funambol.client.source.AppSyncSourceManager;
import com.funambol.client.test.BasicScriptRunner;
import com.funambol.client.test.Robot;
import com.funambol.client.test.util.TestFileManager;
import com.funambol.client.test.basic.BasicUserCommands;
import com.funambol.client.controller.SourceThumbnailsViewController;
import com.funambol.client.configuration.Configuration;
import com.funambol.client.engine.ItemUploadTask;
import com.funambol.sapisync.SapiSyncHandler;
import com.funambol.sapisync.source.JSONFileObject;
import com.funambol.sapisync.source.JSONSyncItem;
import com.funambol.sapisync.source.JSONSyncSource;
import com.funambol.sapisync.source.FileSyncSource;
import com.funambol.sync.SyncConfig;
import com.funambol.sync.SyncItem;
import com.funambol.sync.SyncSource;
import com.funambol.platform.FileAdapter;
import com.funambol.util.Log;
import com.funambol.util.StringUtil;
import com.funambol.util.ConnectionManager;
import com.funambol.storage.Table;
import com.funambol.storage.TableFactory;
import com.funambol.storage.Tuple;
import com.funambol.org.json.me.JSONArray;
import com.funambol.org.json.me.JSONException;
import com.funambol.org.json.me.JSONObject;
public abstract class MediaRobot extends Robot {
private static final String TAG_LOG = "MediaRobot";
protected AppSyncSourceManager appSourceManager;
protected TestFileManager fileManager;
protected Configuration configuration;
protected SapiSyncHandler sapiSyncHandler = null;
public MediaRobot(AppSyncSourceManager appSourceManager,
Configuration configuration,
TestFileManager fileManager) {
this.appSourceManager = appSourceManager;
this.configuration = configuration;
this.fileManager = fileManager;
}
public MediaRobot(TestFileManager fileManager) {
this.fileManager = fileManager;
}
public void deleteMedia(String type, String filename) throws Exception {
deleteFile(type, filename);
}
public void deleteFile(String type, String filename) throws Exception {
SyncSource ss = getAppSyncSource(type).getSyncSource();
if(ss instanceof FileSyncSource) {
String dirname = ((FileSyncSource)ss).getDirectory();
FileAdapter file = new FileAdapter(getFileFullName(dirname, filename));
if (file.exists()) {
file.delete();
}
} else {
throw new IllegalArgumentException("Invalid SyncSource type: " + ss);
}
}
public void deleteAllMedia(String type) throws Exception {
// We need to cleanup both the metadata table and the filesystem
FunambolFileSyncSource ss = (FunambolFileSyncSource)getAppSyncSource(type).getSyncSource();
Table metadata = ss.getMetadataTable();
try {
metadata.open();
metadata.reset();
metadata.save();
} finally {
metadata.close();
}
deleteAllFiles(type);
}
public void deleteAllFiles(String type) throws Exception {
FunambolFileSyncSource ss = (FunambolFileSyncSource)getAppSyncSource(type).getSyncSource();
String dirname = ((FileSyncSource)ss).getDirectory();
FileAdapter dir = new FileAdapter(dirname, true);
Enumeration files = dir.list(false, false /* Filters hidden files */);
dir.close();
while(files.hasMoreElements()) {
String filename = (String)files.nextElement();
FileAdapter file = new FileAdapter(getFileFullName(dirname, filename));
file.delete();
file.close();
}
}
public void overrideMediaContent(String type, String targetFileName, String sourceFileName) throws Throwable {
FileAdapter file = getMediaOutputStream(type, targetFileName);
OutputStream os = file.openOutputStream();
getMediaFile(sourceFileName, os);
}
public void addMedia(String type, String filename) throws Throwable {
FileAdapter file = getMediaOutputStream(type, filename);
OutputStream os = file.openOutputStream();
getMediaFile(filename, os);
}
private FileAdapter getMediaOutputStream(String type, String filename) throws Throwable {
SyncSource source = getAppSyncSource(type).getSyncSource();
String fullname = null;
if (source instanceof FileSyncSource) {
FileSyncSource fss = (FileSyncSource)source;
filename = getFileNameFromFullName(filename);
fullname = fss.getFileFullName(filename);
} else {
return null;
}
fullname = StringUtil.simplifyFileName(fullname);
FileAdapter f = new FileAdapter(fullname);
return f;
}
public void checkMediaCount(String type, int count) throws Throwable {
int localCount = getFilesCount(type);
if (count != localCount) {
Log.error(TAG_LOG, "Expected " + count + " -- found " + localCount);
}
assertTrue(count == localCount, "Local media items count mismatch");
}
/**
* Add a media to the server. Media content is read based on specified
* file name (a file in application's assets or an online resource).
*
* @param type sync source type
* @param filename a relative path to the resource. BaseUrl parameter on test
* configuration defines if the resource is a local file or is
* an URL. In both cases, file is copied locally and then
* uploaded to the server.
* @throws Throwable
*/
public void addMediaOnServer(String type, String filename) throws Throwable {
//make file available on local storage
ByteArrayOutputStream os = new ByteArrayOutputStream();
String contentType = getMediaFile(filename, os);
byte[] fileContent = os.toByteArray();
int size = fileContent.length;
InputStream is = new ByteArrayInputStream(fileContent);
addMediaOnServerFromStream(type, filename, is, size, contentType, null);
}
public void overrideMediaContentOnServer(String type, String targetFileName, String sourceFileName) throws Throwable {
String itemId = findMediaIdOnServer(type, targetFileName);
ByteArrayOutputStream os = new ByteArrayOutputStream();
String contentType = getMediaFile(sourceFileName, os);
byte[] fileContent = os.toByteArray();
int size = fileContent.length;
InputStream is = new ByteArrayInputStream(fileContent);
addMediaOnServerFromStream(type, targetFileName, is, size, contentType, itemId);
}
/**
* Add a media to the server. Media content is read from a stream.
*
* @param type sync source type
* @param itemName name of the item to add
* @param contentStream stream to the content of the item
* @param contentSize size of the item
* @param contentType mimetype of the content to add
*
* @throws JSONException
*/
protected void addMediaOnServerFromStream(String type, String itemName, InputStream contentStream,
long contentSize, String contentType, String guid)
throws IOException, JSONException {
String fullName = itemName;
itemName = getFileNameFromFullName(itemName);
if (Log.isLoggable(Log.DEBUG)) {
Log.debug(TAG_LOG,
"Adding/updating media on server for source " + getRemoteUri(type) +
" with name " + itemName +
" of type " + contentType +
" and size " + contentSize);
}
// Prepare json item to upload
JSONFileObject jsonFileObject = new JSONFileObject();
jsonFileObject.setName(itemName);
jsonFileObject.setSize(contentSize);
jsonFileObject.setCreationdate(System.currentTimeMillis());
jsonFileObject.setLastModifiedDate(System.currentTimeMillis());
jsonFileObject.setMimetype(contentType);
MediaSyncItem item = new MediaSyncItem("fake_key", "fake_type",
guid != null ? SyncItem.STATE_UPDATED : SyncItem.STATE_NEW, null, jsonFileObject,
contentStream, contentSize);
if (guid != null) {
item.setGuid(guid);
}
SapiSyncHandler sapiHandler = getSapiSyncHandler();
sapiHandler.login(null);
String remoteKey = sapiHandler.prepareItemUpload(item, getRemoteUri(type));
sapiHandler.logout();
item.setGuid(remoteKey);
// We need to create a temporary table for the ItemUploadTask to be able
// to perform the upload
- Table tempTable = TableFactory.getInstance().getStringTable("", MediaMetadata.META_DATA_COL_NAMES,
+ Table tempTable = TableFactory.getInstance().getStringTable("media_robot_table", MediaMetadata.META_DATA_COL_NAMES,
MediaMetadata.META_DATA_COL_TYPES,
0, true);
+ tempTable.open();
Tuple newRow = tempTable.createNewRow();
newRow.setField(newRow.getColIndexOrThrow(MediaMetadata.METADATA_ITEM_PATH), fullName);
newRow.setField(newRow.getColIndexOrThrow(MediaMetadata.METADATA_NAME), itemName);
newRow.setField(newRow.getColIndexOrThrow(MediaMetadata.METADATA_SIZE), contentSize);
newRow.setField(newRow.getColIndexOrThrow(MediaMetadata.METADATA_LAST_MOD), System.currentTimeMillis());
newRow.setField(newRow.getColIndexOrThrow(MediaMetadata.METADATA_MIME), contentType);
newRow.setField(newRow.getColIndexOrThrow(MediaMetadata.METADATA_GUID), remoteKey);
+ newRow.setField(newRow.getColIndexOrThrow(MediaMetadata.METADATA_REMOTE_URI), getRemoteUri(type));
tempTable.insert(newRow);
// Now use the ItemUploadTask to perform the actual upload
try {
int colIdx = newRow.getColIndexOrThrow(MediaMetadata.METADATA_ID);
ItemUploadTask uploadTask = new ItemUploadTask(newRow.getLongField(colIdx),
0, tempTable, configuration);
uploadTask.run();
} finally {
// We can now drop the table
tempTable.close();
tempTable.drop();
}
}
public void deleteMediaOnServer(String type, String filename)
throws Throwable {
SapiSyncHandler sapiHandler = getSapiSyncHandler();
String itemId = findMediaIdOnServer(type, filename);
sapiHandler.login(null);
sapiHandler.deleteItem(itemId, getRemoteUri(type), getDataTag(type));
sapiHandler.logout();
}
private String findMediaIdOnServer(String type, String filename)
throws Throwable {
JSONObject item = findMediaJSONObjectOnServer(type, filename);
if(item != null) {
return item.getString("id");
}
return null;
}
private JSONObject findMediaJSONObjectOnServer(String type, String filename)
throws Throwable {
SapiSyncHandler sapiHandler = getSapiSyncHandler();
sapiHandler.login(null);
try {
SapiSyncHandler.FullSet itemsSet = sapiHandler.getItems(
getRemoteUri(type), getDataTag(type), null, null, null,
null);
JSONArray items = itemsSet.items;
for (int i = 0; i < items.length(); ++i) {
JSONObject item = items.getJSONObject(i);
String aFilename = item.getString("name");
if (filename.equals(aFilename)) {
return item;
}
}
} finally {
sapiHandler.logout();
}
return null;
}
public void checkMediaCountOnServer(String type, int count) throws Throwable
{
SapiSyncHandler sapiHandler = getSapiSyncHandler();
sapiHandler.login(null);
int actualCount = sapiHandler.getItemsCount(getRemoteUri(type), null);
sapiHandler.logout();
assertTrue(actualCount == count, "Items count on server mismatch for " + type);
}
public void deleteAllMediaOnServer(String type) throws Throwable {
SapiSyncHandler sapiHandler = getSapiSyncHandler();
sapiHandler.login(null);
sapiHandler.deleteAllItems(getRemoteUri(type));
sapiHandler.logout();
}
/**
* Fills the server with some data in order to leave no more space for a
* further upload of the same file specified as parameter
*
* @param type
* @param fileName name of the file to use as a reference
* @throws Throwable
*/
public void leaveNoFreeServerQuota(String type, String fileName) throws Throwable {
// get free quota for the current user
SapiSyncHandler sapiHandler = getSapiSyncHandler();
sapiHandler.login(null);
long availableSpace = sapiHandler
.getUserAvailableServerQuota(getRemoteUri(type));
sapiHandler.logout();
//make file available on local storage
ByteArrayOutputStream os = new ByteArrayOutputStream();
String contentType = getMediaFile(fileName, os);
byte[] fileContent = os.toByteArray();
int pictureSize = fileContent.length;
long repetitions = availableSpace / pictureSize;
if (repetitions > 0) {
if (Log.isLoggable(Log.DEBUG)) {
Log.debug(TAG_LOG, "Available user quota is " + availableSpace + ", while picture size is " + pictureSize);
Log.debug(TAG_LOG, "Filling the user quota, please wait...");
}
for (long i=1; i <= repetitions; i++) {
String newFileName = i + fileName;
Log.trace(TAG_LOG, "Upload file " + newFileName + " on server [" + i + "/" + repetitions + "]");
InputStream is = new ByteArrayInputStream(fileContent);
addMediaOnServerFromStream(type, i + newFileName, is, pictureSize, contentType, null);
}
} else {
if (Log.isLoggable(Log.DEBUG)) {
Log.debug(TAG_LOG, "Available user quota is " + availableSpace + ", less that the required. Nothing to do.");
}
}
}
public void interruptItem(String phase, String itemKey, int pos, int itemIdx) {
ConnectionManager.getInstance().setBreakInfo(phase, itemKey, pos, itemIdx);
}
protected AppSyncSourceManager getAppSyncSourceManager() {
return appSourceManager;
}
/**
* Returns the AppSyncSource related to the given data type
*
* @param type
* @return
*/
protected AppSyncSource getAppSyncSource(String type) {
if (StringUtil.equalsIgnoreCase(
BasicUserCommands.SOURCE_NAME_PICTURES, type)) {
return getAppSyncSourceManager().getSource(
AppSyncSourceManager.PICTURES_ID);
} else if (StringUtil.equalsIgnoreCase(
BasicUserCommands.SOURCE_NAME_VIDEOS, type)) {
return getAppSyncSourceManager().getSource(
AppSyncSourceManager.VIDEOS_ID);
} else if (StringUtil.equalsIgnoreCase(
BasicUserCommands.SOURCE_NAME_FILES, type)) {
return getAppSyncSourceManager().getSource(
AppSyncSourceManager.FILES_ID);
} else {
throw new IllegalArgumentException("Invalid type: " + type);
}
}
/**
* Returns the SAPI data tag related to the given data type.
*
* @param type
* @return
*/
private String getRemoteUri(String type) {
return getAppSyncSource(type).getSyncSource().getConfig()
.getRemoteUri();
}
private String getDataTag(String type) {
SyncSource src = getAppSyncSource(type).getSyncSource();
String dataTag = null;
if (src instanceof JSONSyncSource) {
JSONSyncSource jsonSyncSource = (JSONSyncSource) src;
dataTag = jsonSyncSource.getDataTag();
}
return dataTag;
}
private SapiSyncHandler getSapiSyncHandler() {
if (sapiSyncHandler == null) {
SyncConfig syncConfig = getSyncConfig();
sapiSyncHandler = new SapiSyncHandler(
StringUtil.extractAddressFromUrl(syncConfig.getSyncUrl()),
syncConfig.getUserName(), syncConfig.getPassword());
}
return sapiSyncHandler;
}
/**
* This is used to override the item input stream
*/
private class MediaSyncItem extends JSONSyncItem {
private InputStream stream;
private long size;
public MediaSyncItem(String key, String type, char state,
String parent, JSONFileObject jsonFileObject,
InputStream stream, long size) throws JSONException {
super(key, type, state, parent, jsonFileObject);
this.stream = stream;
this.size = size;
}
public InputStream getInputStream() throws IOException {
return stream;
}
public long getObjectSize() {
return size;
}
}
protected String getMediaFile(String filename, OutputStream output)
throws Throwable {
String baseUrl = BasicScriptRunner.getBaseUrl();
String url = baseUrl + "/" + filename;
return fileManager.getFile(url, output);
}
private String getFileFullName(String directory, String name) {
StringBuffer fullname = new StringBuffer();
fullname.append(directory);
if(!directory.endsWith("/")) {
fullname.append("/");
}
fullname.append(name);
return fullname.toString();
}
private String getFileNameFromFullName(String fullName) {
int idx = StringUtil.lastIndexOf(fullName, '/');
String fileName;
if (idx != -1) {
fileName = fullName.substring(idx+1);
} else {
fileName = fullName;
}
return fileName;
}
protected abstract void fillLocalStorage();
protected abstract void restoreLocalStorage();
protected abstract SyncConfig getSyncConfig();
/**
* Creates a temporary file of specified size
*
* @param byteSize size of the file
* @param header header of the file
* @param footer footer of the file
*
* @return name of the file created
* @throws IOException
*/
protected abstract void createFileWithSizeOnDevice(long byteSize, String header, String footer)
throws IOException;
/**
* Creates a file in mediahub directory
*
* @param fileName
* @param fileSize
* @throws IOException
*/
public abstract void createFile(String fileName, long fileSize)
throws Exception;
/**
* Renames a file in the server
*
* @param oldFileName
* @param newFileName
* @throws IOException
*/
public void renameFileOnServer(String type, String oldFileName, String newFileName)
throws Throwable {
SapiSyncHandler sapiHandler = getSapiSyncHandler();
String itemId = findMediaIdOnServer(type, oldFileName);
sapiHandler.login(null);
sapiHandler.updateItemName(getRemoteUri(type), itemId, newFileName);
sapiHandler.logout();
}
/**
* Checks the integrity of a file content on both client and server
* @param filename
* @throws Throwable
*/
public void checkFileContentIntegrity(String type, String fileNameClient,
String fileNameServer) throws Throwable {
JSONObject localItem = findMediaJSONObject(type, fileNameClient);
JSONObject serverItem = findMediaJSONObjectOnServer(type, fileNameServer);
assertTrue(localItem != null, "Item not found on client");
assertTrue(serverItem != null, "Item not found on server");
assertTrue(localItem.getLong("size"), serverItem.getLong("size"),
"Item size mismatch");
}
public void renameFile(String type, String oldFileName, String newFileName) throws Exception {
SyncSource ss = getAppSyncSource(type).getSyncSource();
assertTrue(ss instanceof FileSyncSource, "Invalid source type");
if(ss instanceof FileSyncSource) {
String dirname = ((FileSyncSource)ss).getDirectory();
FileAdapter oldFile = new FileAdapter(getFileFullName(dirname, oldFileName));
assertTrue(oldFile.exists(), "File not found: " + getFileFullName(dirname, oldFileName));
String newFileFullName = getFileFullName(dirname, newFileName);
oldFile.rename(newFileFullName);
}
}
public void checkThumbnailName(String type, int position, String fileName)
throws Throwable {
AppSyncSource appSource = getAppSyncSource(type);
SourceThumbnailsViewController thumbsController =
appSource.getSourceThumbnailsViewController();
String name = thumbsController.getThumbnailNameAt(position);
assertTrue(name, fileName, "Item name mismatch");
}
public void checkDisplayedThumbnailsCount(String type, int count)
throws Throwable {
AppSyncSource appSource = getAppSyncSource(type);
SourceThumbnailsViewController thumbsController =
appSource.getSourceThumbnailsViewController();
int actualCount = thumbsController.getDisplayedThumbnailsCount();
assertTrue(count, actualCount, "Displayed thumbnails count mismatch");
}
public void checkThumbnailsCount(String type, int count)
throws Throwable {
AppSyncSource appSource = getAppSyncSource(type);
SourceThumbnailsViewController thumbsController =
appSource.getSourceThumbnailsViewController();
int actualCount = thumbsController.getThumbnailsCount();
assertTrue(count, actualCount, "Thumbnails count mismatch");
}
private int getFilesCount(String type) throws Exception {
SyncSource ss = getAppSyncSource(type).getSyncSource();
if(ss instanceof FileSyncSource) {
int count = 0;
String dirname = ((FileSyncSource)ss).getDirectory();
FileAdapter dir = new FileAdapter(dirname, true);
Enumeration files = dir.list(false, false /* Filters hidden files */);
dir.close();
while(files.hasMoreElements()) {
String file = (String)files.nextElement();
if (doesMediaBelongToSource(type, file)) {
count++;
}
}
return count;
} else {
throw new IllegalArgumentException("Invalid SyncSource type: " + ss);
}
}
private boolean doesMediaBelongToSource(String type, String file) {
if (BasicUserCommands.SOURCE_NAME_FILES.equals(type)) {
return true;
} else if (BasicUserCommands.SOURCE_NAME_PICTURES.equals(type)) {
// These are all extensions for this type, not only the one we
// support in upload
String extensions[] = {"jpg","jpeg","bmp","gif","png","tiff"};
return isSupportedExtension(extensions, file);
} else if (BasicUserCommands.SOURCE_NAME_VIDEOS.equals(type)) {
// These are all extensions for this type, not only the one we
// support in upload
String extensions[] = {"3gp","mp4","mpeg","flv","swf","avi"};
return isSupportedExtension(extensions, file);
}
throw new IllegalArgumentException("Unknown source type " + type);
}
private boolean isSupportedExtension(String extensions[], String name) {
// If there are no valid extensions defined, then the source does not
// apply any filter
if (extensions == null || extensions.length == 0) {
return true;
}
name = name.toLowerCase();
for(int i=0;i<extensions.length;++i) {
String ext = extensions[i].toLowerCase();
if (name.endsWith(ext)) {
return true;
}
}
return false;
}
protected JSONObject findMediaJSONObject(String type, String filename) throws Exception {
JSONObject result = new JSONObject();
SyncSource ss = getAppSyncSource(type).getSyncSource();
assertTrue(ss instanceof FileSyncSource, "Invalid source type");
if(ss instanceof FileSyncSource) {
String dirname = ((FileSyncSource)ss).getDirectory();
FileAdapter file = new FileAdapter(getFileFullName(dirname, filename));
assertTrue(file.exists(), "File not found: " + getFileFullName(dirname, filename));
result.put("name", getFileNameFromFullName(file.getName()));
result.put("modificationdate", file.lastModified());
result.put("size", file.getSize());
}
return result;
}
}
| false | true | protected void addMediaOnServerFromStream(String type, String itemName, InputStream contentStream,
long contentSize, String contentType, String guid)
throws IOException, JSONException {
String fullName = itemName;
itemName = getFileNameFromFullName(itemName);
if (Log.isLoggable(Log.DEBUG)) {
Log.debug(TAG_LOG,
"Adding/updating media on server for source " + getRemoteUri(type) +
" with name " + itemName +
" of type " + contentType +
" and size " + contentSize);
}
// Prepare json item to upload
JSONFileObject jsonFileObject = new JSONFileObject();
jsonFileObject.setName(itemName);
jsonFileObject.setSize(contentSize);
jsonFileObject.setCreationdate(System.currentTimeMillis());
jsonFileObject.setLastModifiedDate(System.currentTimeMillis());
jsonFileObject.setMimetype(contentType);
MediaSyncItem item = new MediaSyncItem("fake_key", "fake_type",
guid != null ? SyncItem.STATE_UPDATED : SyncItem.STATE_NEW, null, jsonFileObject,
contentStream, contentSize);
if (guid != null) {
item.setGuid(guid);
}
SapiSyncHandler sapiHandler = getSapiSyncHandler();
sapiHandler.login(null);
String remoteKey = sapiHandler.prepareItemUpload(item, getRemoteUri(type));
sapiHandler.logout();
item.setGuid(remoteKey);
// We need to create a temporary table for the ItemUploadTask to be able
// to perform the upload
Table tempTable = TableFactory.getInstance().getStringTable("", MediaMetadata.META_DATA_COL_NAMES,
MediaMetadata.META_DATA_COL_TYPES,
0, true);
Tuple newRow = tempTable.createNewRow();
newRow.setField(newRow.getColIndexOrThrow(MediaMetadata.METADATA_ITEM_PATH), fullName);
newRow.setField(newRow.getColIndexOrThrow(MediaMetadata.METADATA_NAME), itemName);
newRow.setField(newRow.getColIndexOrThrow(MediaMetadata.METADATA_SIZE), contentSize);
newRow.setField(newRow.getColIndexOrThrow(MediaMetadata.METADATA_LAST_MOD), System.currentTimeMillis());
newRow.setField(newRow.getColIndexOrThrow(MediaMetadata.METADATA_MIME), contentType);
newRow.setField(newRow.getColIndexOrThrow(MediaMetadata.METADATA_GUID), remoteKey);
tempTable.insert(newRow);
// Now use the ItemUploadTask to perform the actual upload
try {
int colIdx = newRow.getColIndexOrThrow(MediaMetadata.METADATA_ID);
ItemUploadTask uploadTask = new ItemUploadTask(newRow.getLongField(colIdx),
0, tempTable, configuration);
uploadTask.run();
} finally {
// We can now drop the table
tempTable.close();
tempTable.drop();
}
}
| protected void addMediaOnServerFromStream(String type, String itemName, InputStream contentStream,
long contentSize, String contentType, String guid)
throws IOException, JSONException {
String fullName = itemName;
itemName = getFileNameFromFullName(itemName);
if (Log.isLoggable(Log.DEBUG)) {
Log.debug(TAG_LOG,
"Adding/updating media on server for source " + getRemoteUri(type) +
" with name " + itemName +
" of type " + contentType +
" and size " + contentSize);
}
// Prepare json item to upload
JSONFileObject jsonFileObject = new JSONFileObject();
jsonFileObject.setName(itemName);
jsonFileObject.setSize(contentSize);
jsonFileObject.setCreationdate(System.currentTimeMillis());
jsonFileObject.setLastModifiedDate(System.currentTimeMillis());
jsonFileObject.setMimetype(contentType);
MediaSyncItem item = new MediaSyncItem("fake_key", "fake_type",
guid != null ? SyncItem.STATE_UPDATED : SyncItem.STATE_NEW, null, jsonFileObject,
contentStream, contentSize);
if (guid != null) {
item.setGuid(guid);
}
SapiSyncHandler sapiHandler = getSapiSyncHandler();
sapiHandler.login(null);
String remoteKey = sapiHandler.prepareItemUpload(item, getRemoteUri(type));
sapiHandler.logout();
item.setGuid(remoteKey);
// We need to create a temporary table for the ItemUploadTask to be able
// to perform the upload
Table tempTable = TableFactory.getInstance().getStringTable("media_robot_table", MediaMetadata.META_DATA_COL_NAMES,
MediaMetadata.META_DATA_COL_TYPES,
0, true);
tempTable.open();
Tuple newRow = tempTable.createNewRow();
newRow.setField(newRow.getColIndexOrThrow(MediaMetadata.METADATA_ITEM_PATH), fullName);
newRow.setField(newRow.getColIndexOrThrow(MediaMetadata.METADATA_NAME), itemName);
newRow.setField(newRow.getColIndexOrThrow(MediaMetadata.METADATA_SIZE), contentSize);
newRow.setField(newRow.getColIndexOrThrow(MediaMetadata.METADATA_LAST_MOD), System.currentTimeMillis());
newRow.setField(newRow.getColIndexOrThrow(MediaMetadata.METADATA_MIME), contentType);
newRow.setField(newRow.getColIndexOrThrow(MediaMetadata.METADATA_GUID), remoteKey);
newRow.setField(newRow.getColIndexOrThrow(MediaMetadata.METADATA_REMOTE_URI), getRemoteUri(type));
tempTable.insert(newRow);
// Now use the ItemUploadTask to perform the actual upload
try {
int colIdx = newRow.getColIndexOrThrow(MediaMetadata.METADATA_ID);
ItemUploadTask uploadTask = new ItemUploadTask(newRow.getLongField(colIdx),
0, tempTable, configuration);
uploadTask.run();
} finally {
// We can now drop the table
tempTable.close();
tempTable.drop();
}
}
|
diff --git a/servlet/src/main/java/com/redshape/servlet/dispatchers/http/HttpDispatcher.java b/servlet/src/main/java/com/redshape/servlet/dispatchers/http/HttpDispatcher.java
index 615b1779..e24f9d25 100644
--- a/servlet/src/main/java/com/redshape/servlet/dispatchers/http/HttpDispatcher.java
+++ b/servlet/src/main/java/com/redshape/servlet/dispatchers/http/HttpDispatcher.java
@@ -1,296 +1,296 @@
package com.redshape.servlet.dispatchers.http;
import com.redshape.servlet.actions.exceptions.PageNotFoundException;
import com.redshape.servlet.actions.exceptions.handling.IPageExceptionHandler;
import com.redshape.servlet.core.IHttpRequest;
import com.redshape.servlet.core.IHttpResponse;
import com.redshape.servlet.core.context.IContextSwitcher;
import com.redshape.servlet.core.context.IResponseContext;
import com.redshape.servlet.core.controllers.FrontController;
import com.redshape.servlet.core.controllers.IAction;
import com.redshape.servlet.core.controllers.ProcessingException;
import com.redshape.servlet.core.controllers.registry.IControllersRegistry;
import com.redshape.servlet.dispatchers.DispatchException;
import com.redshape.servlet.dispatchers.interceptors.IDispatcherInterceptor;
import com.redshape.servlet.views.*;
import com.redshape.utils.Commons;
import com.redshape.utils.ResourcesLoader;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import javax.servlet.ServletException;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
/**
* Created by IntelliJ IDEA.
* User: nikelin
* Date: 10/10/10
* Time: 11:21 PM
* To change this template use File | Settings | File Templates.
*/
public class HttpDispatcher implements IHttpDispatcher {
private static final Logger log = Logger.getLogger( HttpDispatcher.class );
private List<IDispatcherInterceptor> interceptors = new ArrayList<IDispatcherInterceptor>();
private IContextSwitcher contextSwitcher;
@Autowired( required = true )
private ResourcesLoader resourcesLoader;
@Autowired( required = true )
private IViewsFactory viewFactory;
@Autowired( required = true )
private IControllersRegistry registry;
private FrontController front;
private ApplicationContext context;
public IPageExceptionHandler exceptionHandler;
public List<IDispatcherInterceptor> getInterceptors() {
return interceptors;
}
public void setInterceptors(List<IDispatcherInterceptor> interceptors) {
this.interceptors = interceptors;
}
public IPageExceptionHandler getExceptionHandler() {
return exceptionHandler;
}
public void setExceptionHandler(IPageExceptionHandler exceptionHandler) {
this.exceptionHandler = exceptionHandler;
}
public IContextSwitcher getContextSwitcher() {
return contextSwitcher;
}
public void setContextSwitcher(IContextSwitcher contextSwitcher) {
this.contextSwitcher = contextSwitcher;
}
public ResourcesLoader getResourcesLoader() {
return resourcesLoader;
}
public void setResourcesLoader(ResourcesLoader resourcesLoader) {
this.resourcesLoader = resourcesLoader;
}
public IViewsFactory getViewFactory() {
return viewFactory;
}
public void setViewFactory(IViewsFactory viewFactory) {
this.viewFactory = viewFactory;
}
public void setRegistry( IControllersRegistry registry ) {
this.registry = registry;
}
protected IControllersRegistry getRegistry() {
return this.registry;
}
public void setFront( FrontController front ) {
this.front = front;
}
protected FrontController getFront() {
if ( this.front == null ) {
this.front = this.getContext().getBean( FrontController.class );
}
return this.front;
}
protected ApplicationContext getContext() {
return this.context;
}
@Override
public void setApplicationContext( ApplicationContext context ) {
this.context = context;
}
protected IView getView( IHttpRequest request ) {
return this.getViewFactory().getView( request );
}
protected void tryRedirectToView( IHttpRequest request,
IHttpResponse response ) throws ProcessingException {
String path = String.format("%s" + File.separator + "%s", request.getController(), request.getAction() );
IView view = this.getView(request);
view.setViewPath( path );
request.getSession().setAttribute("view", view );
request.getSession().setAttribute("layout", this.getFront().getLayout() );
this.getResourcesLoader().setRootDirectory( this.getFront().getLayout().getBasePath() );
try {
String filePath = "views" + File.separator + view.getViewPath() + "." + view.getExtension();
try {
this.getResourcesLoader().loadFile( filePath, true );
} catch ( FileNotFoundException e ) {
try {
view.setViewPath( String.format("%s" + File.separator + "index", request.getController() ) );
this.getResourcesLoader().loadFile( "views" + File.separator + view.getViewPath() + "." + view.getExtension(),
true );
request.setAction("index");
} catch ( FileNotFoundException ex ) {
throw new PageNotFoundException( "View file " + filePath + " not found", ex );
}
}
this._invokeInterceptors( null, view, request, response );
this.redirectToView( view, request, response );
} catch ( ProcessingException e ) {
throw e;
} catch ( Throwable e ) {
throw new ProcessingException( e.getMessage(), e );
}
}
protected void redirectToView( IView view, IHttpRequest request, IHttpResponse response )
throws DispatchException {
try {
IResponseContext context = this.getContextSwitcher().chooseContext( request, view );
if ( context == null ) {
throw new ServletException("Unable to find " +
"appropriate response context");
}
response.setCharacterEncoding("UTF-8");
try {
context.proceedResponse( view, request, response );
} catch ( ProcessingException e ) {
this.processError( e, request, response );
}
} catch ( DispatchException e ) {
throw e;
} catch ( Throwable e ) {
throw new DispatchException( e.getMessage(), e );
}
}
protected void processError( ProcessingException e, IHttpRequest request, IHttpResponse response )
throws DispatchException {
if ( this.getExceptionHandler() == null ) {
throw new DispatchException( e.getMessage(), e );
}
try {
this.getExceptionHandler().handleException( e, request, response );
} catch ( IOException ex ) {
throw new DispatchException( ex.getMessage(), ex );
}
}
@Override
public void dispatch( IHttpRequest request, IHttpResponse response )
throws DispatchException {
try {
ViewHelper.setLocalHttpRequest(request);
if ( request.getRequestURI().endsWith("jsp") ) {
return;
}
IView view = this.getView(request);
view.reset( ResetMode.TRANSIENT );
ILayout layoutView = this.getFront().getLayout();
if ( layoutView.getDispatchAction() != null ) {
layoutView.getDispatchAction().setView(view);
layoutView.getDispatchAction().process();
}
String controllerName = Commons.select( request.getController(), "index" );
if ( controllerName.isEmpty() ) {
controllerName = "index";
}
request.setController(controllerName);
String actionName = Commons.select(request.getAction(), "index");
if ( actionName.isEmpty() ) {
actionName = "index";
}
request.setAction(actionName);
if ( actionName == null ) {
this.tryRedirectToView(request, response);
return;
}
log.info("Requested page: " + controllerName + "/" + actionName );
IAction action = this.getRegistry().getInstance( controllerName, actionName );
if ( action == null ) {
this.tryRedirectToView( request, response );
return;
}
- String viewPath = Commons.select(this.getRegistry().getViewPath(action), view.getViewPath());
+ String viewPath = this.getRegistry().getViewPath(action);
view.setViewPath( viewPath != null ? viewPath.replaceAll("(\\/|\\\\)", "\\" + File.separator ) : controllerName + File.separator + actionName );
log.info( view.getViewPath() );
action.setView(view);
action.setRequest( request );
action.setResponse( response );
action.checkPermissions();
this._invokeInterceptors( null, view, request, response );
action.process();
if ( view.getException() != null
&& this.getContextSwitcher().chooseContext( request, view ).doExceptionsHandling() ) {
this.processError(view.getException(), request, response);
return;
}
if ( view.getRedirection() != null
&& this.getContextSwitcher().chooseContext( request, view ).doRedirectionHandling() ) {
response.sendRedirect( ViewHelper.url(view.getRedirection()) );
}
if ( response.isCommitted() ) {
return;
}
request.getSession().setAttribute("layout", this.getFront().getLayout() );
request.getSession().setAttribute("view", view );
this.redirectToView( view, request, response);
} catch ( ProcessingException e ) {
this.processError(e, request, response);
} catch ( Throwable e ) {
this.processError( new ProcessingException( e.getMessage(), e ), request, response );
}
}
private void _invokeInterceptors( IResponseContext context, IView view,
IHttpRequest request, IHttpResponse response )
throws ProcessingException {
for ( IDispatcherInterceptor interceptor : this.getInterceptors() ) {
interceptor.invoke( context, view, request, response );
}
}
}
| true | true | public void dispatch( IHttpRequest request, IHttpResponse response )
throws DispatchException {
try {
ViewHelper.setLocalHttpRequest(request);
if ( request.getRequestURI().endsWith("jsp") ) {
return;
}
IView view = this.getView(request);
view.reset( ResetMode.TRANSIENT );
ILayout layoutView = this.getFront().getLayout();
if ( layoutView.getDispatchAction() != null ) {
layoutView.getDispatchAction().setView(view);
layoutView.getDispatchAction().process();
}
String controllerName = Commons.select( request.getController(), "index" );
if ( controllerName.isEmpty() ) {
controllerName = "index";
}
request.setController(controllerName);
String actionName = Commons.select(request.getAction(), "index");
if ( actionName.isEmpty() ) {
actionName = "index";
}
request.setAction(actionName);
if ( actionName == null ) {
this.tryRedirectToView(request, response);
return;
}
log.info("Requested page: " + controllerName + "/" + actionName );
IAction action = this.getRegistry().getInstance( controllerName, actionName );
if ( action == null ) {
this.tryRedirectToView( request, response );
return;
}
String viewPath = Commons.select(this.getRegistry().getViewPath(action), view.getViewPath());
view.setViewPath( viewPath != null ? viewPath.replaceAll("(\\/|\\\\)", "\\" + File.separator ) : controllerName + File.separator + actionName );
log.info( view.getViewPath() );
action.setView(view);
action.setRequest( request );
action.setResponse( response );
action.checkPermissions();
this._invokeInterceptors( null, view, request, response );
action.process();
if ( view.getException() != null
&& this.getContextSwitcher().chooseContext( request, view ).doExceptionsHandling() ) {
this.processError(view.getException(), request, response);
return;
}
if ( view.getRedirection() != null
&& this.getContextSwitcher().chooseContext( request, view ).doRedirectionHandling() ) {
response.sendRedirect( ViewHelper.url(view.getRedirection()) );
}
if ( response.isCommitted() ) {
return;
}
request.getSession().setAttribute("layout", this.getFront().getLayout() );
request.getSession().setAttribute("view", view );
this.redirectToView( view, request, response);
} catch ( ProcessingException e ) {
this.processError(e, request, response);
} catch ( Throwable e ) {
this.processError( new ProcessingException( e.getMessage(), e ), request, response );
}
}
| public void dispatch( IHttpRequest request, IHttpResponse response )
throws DispatchException {
try {
ViewHelper.setLocalHttpRequest(request);
if ( request.getRequestURI().endsWith("jsp") ) {
return;
}
IView view = this.getView(request);
view.reset( ResetMode.TRANSIENT );
ILayout layoutView = this.getFront().getLayout();
if ( layoutView.getDispatchAction() != null ) {
layoutView.getDispatchAction().setView(view);
layoutView.getDispatchAction().process();
}
String controllerName = Commons.select( request.getController(), "index" );
if ( controllerName.isEmpty() ) {
controllerName = "index";
}
request.setController(controllerName);
String actionName = Commons.select(request.getAction(), "index");
if ( actionName.isEmpty() ) {
actionName = "index";
}
request.setAction(actionName);
if ( actionName == null ) {
this.tryRedirectToView(request, response);
return;
}
log.info("Requested page: " + controllerName + "/" + actionName );
IAction action = this.getRegistry().getInstance( controllerName, actionName );
if ( action == null ) {
this.tryRedirectToView( request, response );
return;
}
String viewPath = this.getRegistry().getViewPath(action);
view.setViewPath( viewPath != null ? viewPath.replaceAll("(\\/|\\\\)", "\\" + File.separator ) : controllerName + File.separator + actionName );
log.info( view.getViewPath() );
action.setView(view);
action.setRequest( request );
action.setResponse( response );
action.checkPermissions();
this._invokeInterceptors( null, view, request, response );
action.process();
if ( view.getException() != null
&& this.getContextSwitcher().chooseContext( request, view ).doExceptionsHandling() ) {
this.processError(view.getException(), request, response);
return;
}
if ( view.getRedirection() != null
&& this.getContextSwitcher().chooseContext( request, view ).doRedirectionHandling() ) {
response.sendRedirect( ViewHelper.url(view.getRedirection()) );
}
if ( response.isCommitted() ) {
return;
}
request.getSession().setAttribute("layout", this.getFront().getLayout() );
request.getSession().setAttribute("view", view );
this.redirectToView( view, request, response);
} catch ( ProcessingException e ) {
this.processError(e, request, response);
} catch ( Throwable e ) {
this.processError( new ProcessingException( e.getMessage(), e ), request, response );
}
}
|
diff --git a/src/com/herocraftonline/dev/heroes/health/EntityDamageReplacementListener.java b/src/com/herocraftonline/dev/heroes/health/EntityDamageReplacementListener.java
index 45e57582..5e8e5c9f 100644
--- a/src/com/herocraftonline/dev/heroes/health/EntityDamageReplacementListener.java
+++ b/src/com/herocraftonline/dev/heroes/health/EntityDamageReplacementListener.java
@@ -1,142 +1,142 @@
package com.herocraftonline.dev.heroes.health;
import java.util.HashMap;
import java.util.logging.Level;
import org.bukkit.World;
import org.bukkit.entity.CreatureType;
import org.bukkit.entity.Entity;
import org.bukkit.entity.LivingEntity;
import org.bukkit.entity.Player;
import org.bukkit.event.entity.EntityDamageByEntityEvent;
import org.bukkit.event.entity.EntityDamageByProjectileEvent;
import org.bukkit.event.entity.EntityDamageEvent;
import org.bukkit.event.entity.EntityListener;
import com.herocraftonline.dev.heroes.Heroes;
import com.herocraftonline.dev.heroes.persistence.Hero;
import com.herocraftonline.dev.heroes.util.Properties;
public class EntityDamageReplacementListener extends EntityListener {
Heroes plugin;
public HashMap<Integer, Integer> mobHeal = new HashMap<Integer, Integer>();
public EntityDamageReplacementListener(Heroes plugin) {
this.plugin = plugin;
}
public void onEntityDamage(EntityDamageEvent event) {
Properties prop = plugin.getConfigManager().getProperties();
if (event.getEntity() instanceof Player) {
Player player = (Player) event.getEntity();
Hero hero = plugin.getHeroManager().getHero(player);
if (event instanceof EntityDamageByEntityEvent) {
EntityDamageByEntityEvent subEvent = (EntityDamageByEntityEvent) event;
// Player VS Player Damage
if (subEvent.getEntity() instanceof Player) {
Player attacker = (Player) subEvent.getDamager();
if (prop.damages.containsKey(attacker.getItemInHand())) {
event.setCancelled(true);
hero.dealDamage(prop.damages.get(attacker.getItemInHand()));
} else {
- plugin.log(Level.INFO, "You haven't got (" + attacker.getItemInHand().toString() + ") in your damage.yml - defaulting");
+ plugin.log(Level.INFO, "You haven't got (" + attacker.getItemInHand().getType().toString() + ") in your damage.yml - defaulting");
}
}
// Monsters VS Player Damage
if (getCreatureType(subEvent.getDamager()) != null) {
if (prop.damages.containsKey(getCreatureType(subEvent.getDamager()))) {
event.setCancelled(true);
hero.dealDamage(prop.damages.get(getCreatureType(subEvent.getDamager())));
} else {
plugin.log(Level.INFO, "You haven't got (" + getCreatureType(subEvent.getDamager()) + ") in your damage.yml - defaulting");
}
}
} else if (event instanceof EntityDamageByProjectileEvent) {
EntityDamageByProjectileEvent subEvent = (EntityDamageByProjectileEvent) event;
// Projectile VS Player Damage
if (prop.damages.containsKey(subEvent.getProjectile().toString())) {
event.setCancelled(true);
hero.dealDamage(prop.damages.get(subEvent.getProjectile().toString()));
} else {
plugin.log(Level.INFO, "You haven't got (" + subEvent.getProjectile().toString() + ") in your damage.yml - defaulting");
}
} else {
// General enviromental damage
if (prop.damages.containsKey(event.getCause().toString())) {
event.setCancelled(true);
hero.dealDamage(prop.damages.get(event.getCause().toString()));
} else {
plugin.log(Level.INFO, "You haven't got (" + event.getCause().toString() + ") in your damage.yml - defaulting");
}
}
}else {
if (event instanceof EntityDamageByEntityEvent) {
EntityDamageByEntityEvent subEvent = (EntityDamageByEntityEvent) event;
if (getCreatureType(subEvent.getDamager()) != null) {
if (prop.damages.containsKey(getCreatureType(subEvent.getDamager()))) {
event.setCancelled(true);
if(!mobHeal.containsKey(event.getEntity().getEntityId())) {
mobHeal.put(event.getEntity().getEntityId(), 100);
}
damageMob(prop.damages.get(getCreatureType(subEvent.getDamager())), mobHeal.get(event.getEntity().getEntityId()), event.getEntity().getWorld());
} else {
plugin.log(Level.INFO, "You haven't got (" + getCreatureType(subEvent.getDamager()) + ") in your damage.yml - defaulting");
}
}
} else if (event instanceof EntityDamageByProjectileEvent) {
EntityDamageByProjectileEvent subEvent = (EntityDamageByProjectileEvent) event;
if (prop.damages.containsKey(subEvent.getProjectile().toString())) {
event.setCancelled(true);
if(!mobHeal.containsKey(event.getEntity().getEntityId())) {
mobHeal.put(event.getEntity().getEntityId(), 100);
}
damageMob(prop.damages.get(subEvent.getProjectile().toString()), mobHeal.get(event.getEntity().getEntityId()), event.getEntity().getWorld());
} else {
plugin.log(Level.INFO, "You haven't got (" + subEvent.getProjectile().toString() + ") in your damage.yml - defaulting");
}
} else {
if (prop.damages.containsKey(event.getCause().toString())) {
event.setCancelled(true);
if(!mobHeal.containsKey(event.getEntity().getEntityId())) {
mobHeal.put(event.getEntity().getEntityId(), 100);
}
damageMob(prop.damages.get(event.getCause().toString()), mobHeal.get(event.getEntity().getEntityId()), event.getEntity().getWorld());
} else {
plugin.log(Level.INFO, "You haven't got (" + event.getCause().toString() + ") in your damage.yml - defaulting");
}
}
}
}
public CreatureType getCreatureType(Entity entity) {
CreatureType type = null;
try {
Class<?>[] interfaces = entity.getClass().getInterfaces();
for (Class<?> c : interfaces) {
if (LivingEntity.class.isAssignableFrom(c)) {
type = CreatureType.fromName(c.getSimpleName());
return type;
}
}
} catch (IllegalArgumentException e) {
}
return type;
}
public void damageMob(Double damage, int mob, World world) {
mobHeal.put(mob, (int) (mobHeal.get(mob) - damage));
if(mobHeal.get(mob) <= 0) {
for(Entity entity : world.getEntities()) {
if(entity.getEntityId() == mob) {
LivingEntity entityL = (LivingEntity) entity;
entityL.damage(0);
return;
}
}
}
}
}
| true | true | public void onEntityDamage(EntityDamageEvent event) {
Properties prop = plugin.getConfigManager().getProperties();
if (event.getEntity() instanceof Player) {
Player player = (Player) event.getEntity();
Hero hero = plugin.getHeroManager().getHero(player);
if (event instanceof EntityDamageByEntityEvent) {
EntityDamageByEntityEvent subEvent = (EntityDamageByEntityEvent) event;
// Player VS Player Damage
if (subEvent.getEntity() instanceof Player) {
Player attacker = (Player) subEvent.getDamager();
if (prop.damages.containsKey(attacker.getItemInHand())) {
event.setCancelled(true);
hero.dealDamage(prop.damages.get(attacker.getItemInHand()));
} else {
plugin.log(Level.INFO, "You haven't got (" + attacker.getItemInHand().toString() + ") in your damage.yml - defaulting");
}
}
// Monsters VS Player Damage
if (getCreatureType(subEvent.getDamager()) != null) {
if (prop.damages.containsKey(getCreatureType(subEvent.getDamager()))) {
event.setCancelled(true);
hero.dealDamage(prop.damages.get(getCreatureType(subEvent.getDamager())));
} else {
plugin.log(Level.INFO, "You haven't got (" + getCreatureType(subEvent.getDamager()) + ") in your damage.yml - defaulting");
}
}
} else if (event instanceof EntityDamageByProjectileEvent) {
EntityDamageByProjectileEvent subEvent = (EntityDamageByProjectileEvent) event;
// Projectile VS Player Damage
if (prop.damages.containsKey(subEvent.getProjectile().toString())) {
event.setCancelled(true);
hero.dealDamage(prop.damages.get(subEvent.getProjectile().toString()));
} else {
plugin.log(Level.INFO, "You haven't got (" + subEvent.getProjectile().toString() + ") in your damage.yml - defaulting");
}
} else {
// General enviromental damage
if (prop.damages.containsKey(event.getCause().toString())) {
event.setCancelled(true);
hero.dealDamage(prop.damages.get(event.getCause().toString()));
} else {
plugin.log(Level.INFO, "You haven't got (" + event.getCause().toString() + ") in your damage.yml - defaulting");
}
}
}else {
if (event instanceof EntityDamageByEntityEvent) {
EntityDamageByEntityEvent subEvent = (EntityDamageByEntityEvent) event;
if (getCreatureType(subEvent.getDamager()) != null) {
if (prop.damages.containsKey(getCreatureType(subEvent.getDamager()))) {
event.setCancelled(true);
if(!mobHeal.containsKey(event.getEntity().getEntityId())) {
mobHeal.put(event.getEntity().getEntityId(), 100);
}
damageMob(prop.damages.get(getCreatureType(subEvent.getDamager())), mobHeal.get(event.getEntity().getEntityId()), event.getEntity().getWorld());
} else {
plugin.log(Level.INFO, "You haven't got (" + getCreatureType(subEvent.getDamager()) + ") in your damage.yml - defaulting");
}
}
} else if (event instanceof EntityDamageByProjectileEvent) {
EntityDamageByProjectileEvent subEvent = (EntityDamageByProjectileEvent) event;
if (prop.damages.containsKey(subEvent.getProjectile().toString())) {
event.setCancelled(true);
if(!mobHeal.containsKey(event.getEntity().getEntityId())) {
mobHeal.put(event.getEntity().getEntityId(), 100);
}
damageMob(prop.damages.get(subEvent.getProjectile().toString()), mobHeal.get(event.getEntity().getEntityId()), event.getEntity().getWorld());
} else {
plugin.log(Level.INFO, "You haven't got (" + subEvent.getProjectile().toString() + ") in your damage.yml - defaulting");
}
} else {
if (prop.damages.containsKey(event.getCause().toString())) {
event.setCancelled(true);
if(!mobHeal.containsKey(event.getEntity().getEntityId())) {
mobHeal.put(event.getEntity().getEntityId(), 100);
}
damageMob(prop.damages.get(event.getCause().toString()), mobHeal.get(event.getEntity().getEntityId()), event.getEntity().getWorld());
} else {
plugin.log(Level.INFO, "You haven't got (" + event.getCause().toString() + ") in your damage.yml - defaulting");
}
}
}
}
| public void onEntityDamage(EntityDamageEvent event) {
Properties prop = plugin.getConfigManager().getProperties();
if (event.getEntity() instanceof Player) {
Player player = (Player) event.getEntity();
Hero hero = plugin.getHeroManager().getHero(player);
if (event instanceof EntityDamageByEntityEvent) {
EntityDamageByEntityEvent subEvent = (EntityDamageByEntityEvent) event;
// Player VS Player Damage
if (subEvent.getEntity() instanceof Player) {
Player attacker = (Player) subEvent.getDamager();
if (prop.damages.containsKey(attacker.getItemInHand())) {
event.setCancelled(true);
hero.dealDamage(prop.damages.get(attacker.getItemInHand()));
} else {
plugin.log(Level.INFO, "You haven't got (" + attacker.getItemInHand().getType().toString() + ") in your damage.yml - defaulting");
}
}
// Monsters VS Player Damage
if (getCreatureType(subEvent.getDamager()) != null) {
if (prop.damages.containsKey(getCreatureType(subEvent.getDamager()))) {
event.setCancelled(true);
hero.dealDamage(prop.damages.get(getCreatureType(subEvent.getDamager())));
} else {
plugin.log(Level.INFO, "You haven't got (" + getCreatureType(subEvent.getDamager()) + ") in your damage.yml - defaulting");
}
}
} else if (event instanceof EntityDamageByProjectileEvent) {
EntityDamageByProjectileEvent subEvent = (EntityDamageByProjectileEvent) event;
// Projectile VS Player Damage
if (prop.damages.containsKey(subEvent.getProjectile().toString())) {
event.setCancelled(true);
hero.dealDamage(prop.damages.get(subEvent.getProjectile().toString()));
} else {
plugin.log(Level.INFO, "You haven't got (" + subEvent.getProjectile().toString() + ") in your damage.yml - defaulting");
}
} else {
// General enviromental damage
if (prop.damages.containsKey(event.getCause().toString())) {
event.setCancelled(true);
hero.dealDamage(prop.damages.get(event.getCause().toString()));
} else {
plugin.log(Level.INFO, "You haven't got (" + event.getCause().toString() + ") in your damage.yml - defaulting");
}
}
}else {
if (event instanceof EntityDamageByEntityEvent) {
EntityDamageByEntityEvent subEvent = (EntityDamageByEntityEvent) event;
if (getCreatureType(subEvent.getDamager()) != null) {
if (prop.damages.containsKey(getCreatureType(subEvent.getDamager()))) {
event.setCancelled(true);
if(!mobHeal.containsKey(event.getEntity().getEntityId())) {
mobHeal.put(event.getEntity().getEntityId(), 100);
}
damageMob(prop.damages.get(getCreatureType(subEvent.getDamager())), mobHeal.get(event.getEntity().getEntityId()), event.getEntity().getWorld());
} else {
plugin.log(Level.INFO, "You haven't got (" + getCreatureType(subEvent.getDamager()) + ") in your damage.yml - defaulting");
}
}
} else if (event instanceof EntityDamageByProjectileEvent) {
EntityDamageByProjectileEvent subEvent = (EntityDamageByProjectileEvent) event;
if (prop.damages.containsKey(subEvent.getProjectile().toString())) {
event.setCancelled(true);
if(!mobHeal.containsKey(event.getEntity().getEntityId())) {
mobHeal.put(event.getEntity().getEntityId(), 100);
}
damageMob(prop.damages.get(subEvent.getProjectile().toString()), mobHeal.get(event.getEntity().getEntityId()), event.getEntity().getWorld());
} else {
plugin.log(Level.INFO, "You haven't got (" + subEvent.getProjectile().toString() + ") in your damage.yml - defaulting");
}
} else {
if (prop.damages.containsKey(event.getCause().toString())) {
event.setCancelled(true);
if(!mobHeal.containsKey(event.getEntity().getEntityId())) {
mobHeal.put(event.getEntity().getEntityId(), 100);
}
damageMob(prop.damages.get(event.getCause().toString()), mobHeal.get(event.getEntity().getEntityId()), event.getEntity().getWorld());
} else {
plugin.log(Level.INFO, "You haven't got (" + event.getCause().toString() + ") in your damage.yml - defaulting");
}
}
}
}
|
diff --git a/packages/java/rinfo-store/src/main/java/se/lagrummet/rinfo/store/depot/DepotUtil.java b/packages/java/rinfo-store/src/main/java/se/lagrummet/rinfo/store/depot/DepotUtil.java
index 045370f8..6e82471e 100644
--- a/packages/java/rinfo-store/src/main/java/se/lagrummet/rinfo/store/depot/DepotUtil.java
+++ b/packages/java/rinfo-store/src/main/java/se/lagrummet/rinfo/store/depot/DepotUtil.java
@@ -1,44 +1,44 @@
package se.lagrummet.rinfo.store.depot;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.configuration.Configuration;
import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.ConfigurationMap;
import org.apache.commons.configuration.PropertiesConfiguration;
public class DepotUtil {
public static final String DEFAULT_PROPERTIES_PATH = "rinfo-depot.properties";
public static final String DEPOT_CONFIG_SUBSET_KEY = "rinfo.depot";
static {
BeanUtilsURIConverter.registerIfNoURIConverterIsRegistered();
}
public static Depot depotFromConfig() throws ConfigurationException {
return depotFromConfig(DEFAULT_PROPERTIES_PATH, DEPOT_CONFIG_SUBSET_KEY);
}
public static Depot depotFromConfig(String propertiesPath)
throws ConfigurationException {
return depotFromConfig(propertiesPath, DEPOT_CONFIG_SUBSET_KEY);
}
public static Depot depotFromConfig(String propertiesPath, String subsetPrefix)
throws ConfigurationException {
- Depot depot = new FileDepot();
+ FileDepot depot = new FileDepot();
Configuration config = new PropertiesConfiguration(propertiesPath);
if (subsetPrefix != null) {
config = config.subset(subsetPrefix);
}
try {
BeanUtils.populate(depot, new ConfigurationMap(config));
+ depot.initialize();
} catch (Exception e) {
throw new ConfigurationException(e);
}
- depot.initialize();
return depot;
}
}
| false | true | public static Depot depotFromConfig(String propertiesPath, String subsetPrefix)
throws ConfigurationException {
Depot depot = new FileDepot();
Configuration config = new PropertiesConfiguration(propertiesPath);
if (subsetPrefix != null) {
config = config.subset(subsetPrefix);
}
try {
BeanUtils.populate(depot, new ConfigurationMap(config));
} catch (Exception e) {
throw new ConfigurationException(e);
}
depot.initialize();
return depot;
}
| public static Depot depotFromConfig(String propertiesPath, String subsetPrefix)
throws ConfigurationException {
FileDepot depot = new FileDepot();
Configuration config = new PropertiesConfiguration(propertiesPath);
if (subsetPrefix != null) {
config = config.subset(subsetPrefix);
}
try {
BeanUtils.populate(depot, new ConfigurationMap(config));
depot.initialize();
} catch (Exception e) {
throw new ConfigurationException(e);
}
return depot;
}
|
diff --git a/src/com/shade/crash/Ray.java b/src/com/shade/crash/Ray.java
index d22a15c..698bf20 100644
--- a/src/com/shade/crash/Ray.java
+++ b/src/com/shade/crash/Ray.java
@@ -1,65 +1,65 @@
package com.shade.crash;
import org.newdawn.slick.Graphics;
import org.newdawn.slick.geom.Rectangle;
import org.newdawn.slick.geom.Transform;
import org.newdawn.slick.geom.Vector2f;
import org.newdawn.slick.state.StateBasedGame;
import com.shade.base.Entity;
import com.shade.base.Level;
import com.shade.crash.util.CrashGeom;
import com.shade.util.Geom;
public class Ray extends Body {
private float heading;
public Ray(Body one, Body two) {
float w = one.getWidth();
- shape = new Rectangle(one.getCenterX() - w / 2, one.getCenterY(), 2,
+ shape = new Rectangle(one.getCenterX() - w / 2, one.getCenterY(), w,
CrashGeom.distance(one, two));
heading = CrashGeom.calculateAngle(one, two);
Transform t = Transform.createRotateTransform(heading,
one.getCenterX(), one
.getCenterY());
shape = shape.transform(t);
}
public Vector2f getDirection() {
return Geom.calculateVector(1, heading);
}
public void render(StateBasedGame game, Graphics g) {
g.draw(shape);
}
public void addToLevel(Level l) {
// TODO Auto-generated method stub
}
public Role getRole() {
return Role.RAY;
}
public void onCollision(Entity obstacle) {
// TODO Auto-generated method stub
}
public void removeFromLevel(Level l) {
// TODO Auto-generated method stub
}
public void update(StateBasedGame game, int delta) {
// TODO Auto-generated method stub
}
public void repel(Entity repellee) {
// TODO Auto-generated method stub
}
}
| true | true | public Ray(Body one, Body two) {
float w = one.getWidth();
shape = new Rectangle(one.getCenterX() - w / 2, one.getCenterY(), 2,
CrashGeom.distance(one, two));
heading = CrashGeom.calculateAngle(one, two);
Transform t = Transform.createRotateTransform(heading,
one.getCenterX(), one
.getCenterY());
shape = shape.transform(t);
}
| public Ray(Body one, Body two) {
float w = one.getWidth();
shape = new Rectangle(one.getCenterX() - w / 2, one.getCenterY(), w,
CrashGeom.distance(one, two));
heading = CrashGeom.calculateAngle(one, two);
Transform t = Transform.createRotateTransform(heading,
one.getCenterX(), one
.getCenterY());
shape = shape.transform(t);
}
|
diff --git a/src/com/iver/cit/gvsig/ExportTo.java b/src/com/iver/cit/gvsig/ExportTo.java
index 73df525..a0d2847 100644
--- a/src/com/iver/cit/gvsig/ExportTo.java
+++ b/src/com/iver/cit/gvsig/ExportTo.java
@@ -1,757 +1,757 @@
package com.iver.cit.gvsig;
import java.awt.Component;
import java.awt.geom.Point2D;
import java.io.File;
import java.io.IOException;
import java.sql.Types;
import java.util.Vector;
import javax.swing.JComponent;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.ProgressMonitor;
import org.cresques.cts.ICoordTrans;
import com.hardcode.driverManager.Driver;
import com.hardcode.driverManager.DriverLoadException;
import com.hardcode.gdbms.driver.exceptions.FileNotFoundDriverException;
import com.hardcode.gdbms.driver.exceptions.InitializeWriterException;
import com.hardcode.gdbms.driver.exceptions.OpenDriverException;
import com.hardcode.gdbms.driver.exceptions.ReadDriverException;
import com.hardcode.gdbms.engine.data.driver.DriverException;
import com.hardcode.gdbms.engine.values.Value;
import com.iver.andami.PluginServices;
import com.iver.andami.messages.NotificationManager;
import com.iver.andami.plugins.Extension;
import com.iver.cit.gvsig.exceptions.expansionfile.ExpansionFileReadException;
import com.iver.cit.gvsig.exceptions.visitors.VisitorException;
import com.iver.cit.gvsig.fmap.MapContext;
import com.iver.cit.gvsig.fmap.core.DefaultFeature;
import com.iver.cit.gvsig.fmap.core.FShape;
import com.iver.cit.gvsig.fmap.core.IFeature;
import com.iver.cit.gvsig.fmap.core.IGeometry;
import com.iver.cit.gvsig.fmap.core.ShapeFactory;
import com.iver.cit.gvsig.fmap.core.v02.FLabel;
import com.iver.cit.gvsig.fmap.drivers.ConnectionFactory;
import com.iver.cit.gvsig.fmap.drivers.DBException;
import com.iver.cit.gvsig.fmap.drivers.DBLayerDefinition;
import com.iver.cit.gvsig.fmap.drivers.DriverAttributes;
import com.iver.cit.gvsig.fmap.drivers.DriverIOException;
import com.iver.cit.gvsig.fmap.drivers.FieldDescription;
import com.iver.cit.gvsig.fmap.drivers.IConnection;
import com.iver.cit.gvsig.fmap.drivers.ILayerDefinition;
import com.iver.cit.gvsig.fmap.drivers.IVectorialDatabaseDriver;
import com.iver.cit.gvsig.fmap.drivers.SHPLayerDefinition;
import com.iver.cit.gvsig.fmap.drivers.VectorialDriver;
import com.iver.cit.gvsig.fmap.drivers.dxf.DXFMemoryDriver;
import com.iver.cit.gvsig.fmap.drivers.jdbc.postgis.PostGISWriter;
import com.iver.cit.gvsig.fmap.drivers.jdbc.postgis.PostGisDriver;
import com.iver.cit.gvsig.fmap.drivers.shp.IndexedShpDriver;
import com.iver.cit.gvsig.fmap.edition.DefaultRowEdited;
import com.iver.cit.gvsig.fmap.edition.IRowEdited;
import com.iver.cit.gvsig.fmap.edition.IWriter;
import com.iver.cit.gvsig.fmap.edition.writers.dxf.DxfFieldsMapping;
import com.iver.cit.gvsig.fmap.edition.writers.dxf.DxfWriter;
import com.iver.cit.gvsig.fmap.edition.writers.shp.ShpWriter;
import com.iver.cit.gvsig.fmap.layers.FBitSet;
import com.iver.cit.gvsig.fmap.layers.FLayer;
import com.iver.cit.gvsig.fmap.layers.FLayers;
import com.iver.cit.gvsig.fmap.layers.FLyrAnnotation;
import com.iver.cit.gvsig.fmap.layers.FLyrVect;
import com.iver.cit.gvsig.fmap.layers.LayerFactory;
import com.iver.cit.gvsig.fmap.layers.ReadableVectorial;
import com.iver.cit.gvsig.fmap.layers.SelectableDataSource;
import com.iver.cit.gvsig.project.documents.view.IProjectView;
import com.iver.cit.gvsig.project.documents.view.gui.View;
import com.iver.cit.gvsig.vectorialdb.ConnectionSettings;
import com.iver.cit.gvsig.vectorialdb.DlgConnection;
import com.iver.utiles.PostProcessSupport;
import com.iver.utiles.SimpleFileFilter;
import com.iver.utiles.swing.threads.AbstractMonitorableTask;
public class ExportTo extends Extension {
private String lastPath = null;
private class WriterTask extends AbstractMonitorableTask
{
FLyrVect lyrVect;
IWriter writer;
int rowCount;
ReadableVectorial va;
SelectableDataSource sds;
FBitSet bitSet;
MapContext mapContext;
VectorialDriver reader;
public WriterTask(MapContext mapContext, FLyrVect lyr, IWriter writer, Driver reader) throws ReadDriverException
{
this.mapContext = mapContext;
this.lyrVect = lyr;
this.writer = writer;
this.reader = (VectorialDriver) reader;
setInitialStep(0);
setDeterminatedProcess(true);
setStatusMessage(PluginServices.getText(this, "exportando_features"));
va = lyrVect.getSource();
sds = lyrVect.getRecordset();
bitSet = sds.getSelection();
if (bitSet.cardinality() == 0)
rowCount = va.getShapeCount();
else
rowCount = bitSet.cardinality();
setFinalStep(rowCount);
}
public void run() throws Exception {
va.start();
ICoordTrans ct = lyrVect.getCoordTrans();
DriverAttributes attr = va.getDriverAttributes();
boolean bMustClone = false;
if (attr != null) {
if (attr.isLoadedInMemory()) {
bMustClone = attr.isLoadedInMemory();
}
}
if (lyrVect instanceof FLyrAnnotation && lyrVect.getShapeType()!=FShape.POINT) {
SHPLayerDefinition lyrDef=(SHPLayerDefinition)writer.getTableDefinition();
lyrDef.setShapeType(FShape.POINT);
writer.initialize(lyrDef);
}
// Creamos la tabla.
writer.preProcess();
if (bitSet.cardinality() == 0) {
rowCount = va.getShapeCount();
for (int i = 0; i < rowCount; i++) {
IGeometry geom = va.getShape(i);
if (geom == null) {
continue;
}
if (lyrVect instanceof FLyrAnnotation && geom.getGeometryType()!=FShape.POINT) {
Point2D p=FLabel.createLabelPoint((FShape)geom.getInternalShape());
geom=ShapeFactory.createPoint2D(p.getX(),p.getY());
}
if (ct != null) {
if (bMustClone)
geom = geom.cloneGeometry();
geom.reProject(ct);
}
reportStep();
setNote(PluginServices.getText(this, "exporting_") + i);
if (isCanceled())
break;
if (geom != null) {
Value[] values = sds.getRow(i);
IFeature feat = new DefaultFeature(geom, values, "" + i);
DefaultRowEdited edRow = new DefaultRowEdited(feat,
DefaultRowEdited.STATUS_ADDED, i);
writer.process(edRow);
}
}
} else {
int counter = 0;
for (int i = bitSet.nextSetBit(0); i >= 0; i = bitSet
.nextSetBit(i + 1)) {
IGeometry geom = va.getShape(i);
if (geom == null) {
continue;
}
if (lyrVect instanceof FLyrAnnotation && geom.getGeometryType()!=FShape.POINT) {
Point2D p=FLabel.createLabelPoint((FShape)geom.getInternalShape());
geom=ShapeFactory.createPoint2D(p.getX(),p.getY());
}
if (ct != null) {
if (bMustClone)
geom = geom.cloneGeometry();
geom.reProject(ct);
}
reportStep();
setNote(PluginServices.getText(this, "exporting_") + counter);
if (isCanceled())
break;
if (geom != null) {
Value[] values = sds.getRow(i);
IFeature feat = new DefaultFeature(geom, values, "" + i);
DefaultRowEdited edRow = new DefaultRowEdited(feat,
DefaultRowEdited.STATUS_ADDED, i);
writer.process(edRow);
}
}
}
writer.postProcess();
va.stop();
if (reader != null){
int res = JOptionPane.showConfirmDialog(
(JComponent) PluginServices.getMDIManager().getActiveWindow()
, PluginServices.getText(this, "insertar_en_la_vista_la_capa_creada"),
PluginServices.getText(this,"insertar_capa"),
JOptionPane.YES_NO_OPTION);
if (res == JOptionPane.YES_OPTION)
{
PostProcessSupport.executeCalls();
ILayerDefinition lyrDef = (ILayerDefinition) writer.getTableDefinition();
FLayer newLayer = LayerFactory.createLayer(
lyrDef.getName(), reader, mapContext.getProjection());
mapContext.getLayers().addLayer(newLayer);
}
}
}
/* (non-Javadoc)
* @see com.iver.utiles.swing.threads.IMonitorableTask#finished()
*/
public void finished() {
// TODO Auto-generated method stub
}
}
private class MultiWriterTask extends AbstractMonitorableTask{
Vector tasks=new Vector();
public void addTask(WriterTask wt) {
tasks.add(wt);
}
public void run() throws Exception {
for (int i = 0; i < tasks.size(); i++) {
((WriterTask)tasks.get(i)).run();
}
tasks.clear();
}
/* (non-Javadoc)
* @see com.iver.utiles.swing.threads.IMonitorableTask#finished()
*/
public void finished() {
// TODO Auto-generated method stub
}
}
/**
* @see com.iver.andami.plugins.IExtension#initialize()
*/
public void initialize() {
}
/**
* @see com.iver.andami.plugins.IExtension#execute(java.lang.String)
*/
public void execute(String actionCommand) {
com.iver.andami.ui.mdiManager.IWindow f = PluginServices.getMDIManager()
.getActiveWindow();
if (f instanceof View) {
View vista = (View) f;
IProjectView model = vista.getModel();
MapContext mapa = model.getMapContext();
FLayers layers = mapa.getLayers();
FLayer[] actives = layers.getActives();
try {
// NOTA: SI HAY UNA SELECCI�N, SOLO SE SALVAN LOS SELECCIONADOS
for (int i = 0; i < actives.length; i++) {
if (actives[i] instanceof FLyrVect) {
FLyrVect lv = (FLyrVect) actives[i];
int numSelec = lv.getRecordset().getSelection()
.cardinality();
if (numSelec > 0) {
int resp = JOptionPane.showConfirmDialog(
(Component) PluginServices.getMainFrame(),
PluginServices.getText(this,"se_van_a_guardar_") + numSelec
+ PluginServices.getText(this,"features_desea_continuar"),
PluginServices.getText(this,"export_to"), JOptionPane.YES_NO_OPTION);
if (resp != JOptionPane.YES_OPTION) {
continue;
}
} // if numSelec > 0
if (actionCommand.equals("SHP")) {
saveToShp(mapa, lv);
}
if (actionCommand.equals("DXF")) {
saveToDxf(mapa, lv);
}
if (actionCommand.equals("POSTGIS")) {
saveToPostGIS(mapa, lv);
}
} // actives[i]
} // for
} catch (ReadDriverException e) {
NotificationManager.showMessageError(e.getMessage(),e);
}
}
}
public void saveToPostGIS(MapContext mapContext, FLyrVect layer){
try {
String tableName = JOptionPane.showInputDialog(PluginServices
.getText(this, "intro_tablename"));
if (tableName == null)
return;
tableName = tableName.toLowerCase();
DlgConnection dlg = new DlgConnection(new String[]{"PostGIS JDBC Driver"});
dlg.setModal(true);
dlg.setVisible(true);
ConnectionSettings cs = dlg.getConnSettings();
if (cs == null)
return;
IConnection conex = ConnectionFactory.createConnection(cs
.getConnectionString(), cs.getUser(), cs.getPassw());
DBLayerDefinition originalDef = null;
if (layer.getSource().getDriver() instanceof IVectorialDatabaseDriver) {
originalDef=((IVectorialDatabaseDriver) layer.getSource().getDriver()).getLyrDef();
}
DBLayerDefinition dbLayerDef = new DBLayerDefinition();
// Fjp:
// Cambio: En Postgis, el nombre de cat�logo est� siempre vac�o. Es algo heredado de Oracle, que no se usa.
// dbLayerDef.setCatalogName(cs.getDb());
dbLayerDef.setCatalogName("");
// A�adimos el schema dentro del layer definition para poder tenerlo en cuenta.
dbLayerDef.setSchema(cs.getSchema());
dbLayerDef.setTableName(tableName);
dbLayerDef.setName(tableName);
dbLayerDef.setShapeType(layer.getShapeType());
SelectableDataSource sds = layer.getRecordset();
FieldDescription[] fieldsDescrip = sds.getFieldsDescription();
dbLayerDef.setFieldsDesc(fieldsDescrip);
// Creamos el driver. OJO: Hay que a�adir el campo ID a la
// definici�n de campos.
if (originalDef != null){
dbLayerDef.setFieldID(originalDef.getFieldID());
dbLayerDef.setFieldGeometry(originalDef.getFieldGeometry());
}else{
// Search for id field name
int index=0;
String fieldName="gid";
while (findFileByName(fieldsDescrip,fieldName) != -1){
index++;
fieldName="gid"+index;
}
dbLayerDef.setFieldID(fieldName);
// search for geom field name
index=0;
fieldName="the_geom";
while (findFileByName(fieldsDescrip,fieldName) != -1){
index++;
fieldName="the_geom"+index;
}
dbLayerDef.setFieldGeometry(fieldName);
}
// if id field dosen't exist we add it
if (findFileByName(fieldsDescrip,dbLayerDef.getFieldID()) == -1)
{
int numFieldsAnt = fieldsDescrip.length;
FieldDescription[] newFields = new FieldDescription[dbLayerDef.getFieldsDesc().length + 1];
for (int i=0; i < numFieldsAnt; i++)
{
newFields[i] = fieldsDescrip[i];
}
newFields[numFieldsAnt] = new FieldDescription();
newFields[numFieldsAnt].setFieldDecimalCount(0);
newFields[numFieldsAnt].setFieldType(Types.INTEGER);
newFields[numFieldsAnt].setFieldLength(7);
newFields[numFieldsAnt].setFieldName("gid");
dbLayerDef.setFieldsDesc(newFields);
}
// all fields to lowerCase
FieldDescription field;
for (int i=0;i<dbLayerDef.getFieldsDesc().length;i++){
field = dbLayerDef.getFieldsDesc()[i];
field.setFieldName(field.getFieldName().toLowerCase());
}
dbLayerDef.setFieldID(dbLayerDef.getFieldID().toLowerCase());
dbLayerDef.setFieldGeometry(dbLayerDef.getFieldGeometry().toLowerCase());
dbLayerDef.setWhereClause("");
String strSRID = layer.getProjection().getAbrev();
dbLayerDef.setSRID_EPSG(strSRID);
dbLayerDef.setConnection(conex);
PostGISWriter writer=(PostGISWriter)LayerFactory.getWM().getWriter("PostGIS Writer");
writer.setWriteAll(true);
writer.setCreateTable(true);
writer.initialize(dbLayerDef);
PostGisDriver postGISDriver=new PostGisDriver();
postGISDriver.setLyrDef(dbLayerDef);
postGISDriver.open();
PostProcessSupport.clearList();
Object[] params = new Object[2];
params[0] = conex;
params[1] = dbLayerDef;
PostProcessSupport.addToPostProcess(postGISDriver, "setData",
params, 1);
writeFeatures(mapContext, layer, writer, postGISDriver);
} catch (DriverLoadException e) {
NotificationManager.addError(e.getMessage(),e);
} catch (DBException e) {
NotificationManager.showMessageError(e.getLocalizedMessage(),e);
} catch (InitializeWriterException e) {
- NotificationManager.addError(e.getMessage(),e);
+ NotificationManager.showMessageError(e.getMessage(),e);
} catch (ReadDriverException e) {
NotificationManager.addError(e.getMessage(),e);
}
}
/**
* Lanza un thread en background que escribe las features. Cuando termina, pregunta al usuario si quiere
* a�adir la nueva capa a la vista. Para eso necesita un driver de lectura ya configurado.
* @param mapContext
* @param layer
* @param writer
* @param reader
* @throws ReadDriverException
* @throws DriverException
* @throws DriverIOException
*/
private void writeFeatures(MapContext mapContext, FLyrVect layer, IWriter writer, Driver reader) throws ReadDriverException
{
PluginServices.cancelableBackgroundExecution(new WriterTask(mapContext, layer, writer, reader));
}
private void writeMultiFeatures(MapContext mapContext, FLyrVect layers, IWriter[] writers, Driver[] readers) throws ReadDriverException{
MultiWriterTask mwt=new MultiWriterTask();
for (int i=0;i<writers.length;i++) {
mwt.addTask(new WriterTask(mapContext, layers, writers[i], readers[i]));
}
PluginServices.cancelableBackgroundExecution(mwt);
}
/**
* @param layer
* FLyrVect to obtain features. If selection, only selected
* features will be precessed.
* @param writer
* (Must be already initialized)
* @throws ReadDriverException
* @throws ProcessWriterException
* @throws ExpansionFileReadException
* @throws EditionException
* @throws DriverException
* @throws DriverIOException
* @throws com.hardcode.gdbms.engine.data.driver.DriverException
*/
public void writeFeaturesNoThread(FLyrVect layer, IWriter writer) throws ReadDriverException, VisitorException, ExpansionFileReadException{
ReadableVectorial va = layer.getSource();
SelectableDataSource sds = layer.getRecordset();
// Creamos la tabla.
writer.preProcess();
int rowCount;
FBitSet bitSet = layer.getRecordset().getSelection();
if (bitSet.cardinality() == 0)
rowCount = va.getShapeCount();
else
rowCount = bitSet.cardinality();
ProgressMonitor progress = new ProgressMonitor(
(JComponent) PluginServices.getMDIManager().getActiveWindow(),
PluginServices.getText(this, "exportando_features"),
PluginServices.getText(this, "exportando_features"), 0,
rowCount);
progress.setMillisToDecideToPopup(200);
progress.setMillisToPopup(500);
if (bitSet.cardinality() == 0) {
rowCount = va.getShapeCount();
for (int i = 0; i < rowCount; i++) {
IGeometry geom = va.getShape(i);
progress.setProgress(i);
if (progress.isCanceled())
break;
if (geom != null) {
Value[] values = sds.getRow(i);
IFeature feat = new DefaultFeature(geom, values, "" + i);
DefaultRowEdited edRow = new DefaultRowEdited(feat,
IRowEdited.STATUS_ADDED, i);
writer.process(edRow);
}
}
} else {
int counter = 0;
for (int i = bitSet.nextSetBit(0); i >= 0; i = bitSet
.nextSetBit(i + 1)) {
IGeometry geom = va.getShape(i);
progress.setProgress(counter++);
if (progress.isCanceled())
break;
if (geom != null) {
Value[] values = sds.getRow(i);
IFeature feat = new DefaultFeature(geom, values, "" + i);
DefaultRowEdited edRow = new DefaultRowEdited(feat,
IRowEdited.STATUS_ADDED, i);
writer.process(edRow);
}
}
}
writer.postProcess();
progress.close();
}
public void saveToDxf(MapContext mapContext, FLyrVect layer) {
try {
JFileChooser jfc = new JFileChooser(lastPath);
SimpleFileFilter filterShp = new SimpleFileFilter("dxf",
PluginServices.getText(this, "dxf_files"));
jfc.setFileFilter(filterShp);
if (jfc.showSaveDialog((Component) PluginServices.getMainFrame()) == JFileChooser.APPROVE_OPTION) {
File newFile = jfc.getSelectedFile();
String path = newFile.getAbsolutePath();
if (!(path.toLowerCase().endsWith(".dxf"))) {
path = path + ".dxf";
}
newFile = new File(path);
DxfWriter writer = (DxfWriter) LayerFactory.getWM().getWriter(
"DXF Writer");
SHPLayerDefinition lyrDef = new SHPLayerDefinition();
SelectableDataSource sds = layer.getRecordset();
FieldDescription[] fieldsDescrip = sds.getFieldsDescription();
lyrDef.setFieldsDesc(fieldsDescrip);
lyrDef.setFile(newFile);
lyrDef.setName(newFile.getName());
lyrDef.setShapeType(layer.getShapeType());
writer.setFile(newFile);
writer.initialize(lyrDef);
writer.setProjection(layer.getProjection());
DxfFieldsMapping fieldsMapping = new DxfFieldsMapping();
// TODO: Recuperar aqu� los campos del cuadro de di�logo.
writer.setFieldMapping(fieldsMapping);
DXFMemoryDriver dxfDriver=new DXFMemoryDriver();
dxfDriver.open(newFile);
writeFeatures(mapContext, layer, writer, dxfDriver);
String fileName = newFile.getAbsolutePath();
lastPath = fileName.substring(0, fileName.lastIndexOf(File.separatorChar));
}
} catch (ReadDriverException e) {
NotificationManager.addError(e.getMessage(),e);
} catch (InitializeWriterException e) {
NotificationManager.addError(e.getMessage(),e);
} catch (DriverLoadException e) {
NotificationManager.addError(e.getMessage(),e);
}
}
public void saveToShp(MapContext mapContext, FLyrVect layer) {
try {
JFileChooser jfc = new JFileChooser();
SimpleFileFilter filterShp = new SimpleFileFilter("shp",
PluginServices.getText(this, "shp_files"));
jfc.setFileFilter(filterShp);
if (jfc.showSaveDialog((Component) PluginServices.getMainFrame()) == JFileChooser.APPROVE_OPTION) {
File newFile = jfc.getSelectedFile();
String path = newFile.getAbsolutePath();
if( newFile.exists()){
int resp = JOptionPane.showConfirmDialog(
(Component) PluginServices.getMainFrame(),PluginServices.getText(this,"fichero_ya_existe_seguro_desea_guardarlo"),
PluginServices.getText(this,"guardar"), JOptionPane.YES_NO_OPTION);
if (resp != JOptionPane.YES_OPTION) {
return;
}
}
if (!(path.toLowerCase().endsWith(".shp"))) {
path = path + ".shp";
}
newFile = new File(path);
SelectableDataSource sds = layer.getRecordset();
FieldDescription[] fieldsDescrip = sds.getFieldsDescription();
if (layer.getShapeType() == FShape.MULTI) // Exportamos a 3
// ficheros
{
ShpWriter writer1 = (ShpWriter) LayerFactory.getWM().getWriter(
"Shape Writer");
Driver[] drivers=new Driver[3];
ShpWriter[] writers=new ShpWriter[3];
// puntos
String auxPoint = path.replaceFirst("\\.shp", "_points.shp");
SHPLayerDefinition lyrDefPoint = new SHPLayerDefinition();
lyrDefPoint.setFieldsDesc(fieldsDescrip);
File filePoints = new File(auxPoint);
lyrDefPoint.setFile(filePoints);
lyrDefPoint.setName(filePoints.getName());
lyrDefPoint.setShapeType(FShape.POINT);
writer1.setFile(filePoints);
writer1.initialize(lyrDefPoint);
writers[0]=writer1;
drivers[0]=getOpenShpDriver(filePoints);
//drivers[0]=null;
ShpWriter writer2 = (ShpWriter) LayerFactory.getWM().getWriter(
"Shape Writer");
// Lineas
String auxLine = path.replaceFirst("\\.shp", "_line.shp");
SHPLayerDefinition lyrDefLine = new SHPLayerDefinition();
lyrDefLine.setFieldsDesc(fieldsDescrip);
File fileLines = new File(auxLine);
lyrDefLine.setFile(fileLines);
lyrDefLine.setName(fileLines.getName());
lyrDefLine.setShapeType(FShape.LINE);
writer2.setFile(fileLines);
writer2.initialize(lyrDefLine);
writers[1]=writer2;
drivers[1]=getOpenShpDriver(fileLines);
//drivers[1]=null;
ShpWriter writer3 = (ShpWriter) LayerFactory.getWM().getWriter(
"Shape Writer");
// Pol�gonos
String auxPolygon = path.replaceFirst("\\.shp", "_polygons.shp");
SHPLayerDefinition lyrDefPolygon = new SHPLayerDefinition();
lyrDefPolygon.setFieldsDesc(fieldsDescrip);
File filePolygons = new File(auxPolygon);
lyrDefPolygon.setFile(filePolygons);
lyrDefPolygon.setName(filePolygons.getName());
lyrDefPolygon.setShapeType(FShape.POLYGON);
writer3.setFile(filePolygons);
writer3.initialize(lyrDefPolygon);
writers[2]=writer3;
drivers[2]=getOpenShpDriver(filePolygons);
//drivers[2]=null;
writeMultiFeatures(mapContext,layer, writers, drivers);
} else {
ShpWriter writer = (ShpWriter) LayerFactory.getWM().getWriter(
"Shape Writer");
IndexedShpDriver drv = getOpenShpDriver(newFile);
SHPLayerDefinition lyrDef = new SHPLayerDefinition();
lyrDef.setFieldsDesc(fieldsDescrip);
lyrDef.setFile(newFile);
lyrDef.setName(newFile.getName());
lyrDef.setShapeType(layer.getTypeIntVectorLayer());
writer.setFile(newFile);
writer.initialize(lyrDef);
// CODIGO PARA EXPORTAR UN SHP A UN CHARSET DETERMINADO
// ES UTIL PARA QUE UN DBF SE VEA CORRECTAMENTE EN EXCEL, POR EJEMPLO
// Charset resul = (Charset) JOptionPane.showInputDialog((Component)PluginServices.getMDIManager().getActiveWindow(),
// PluginServices.getText(ExportTo.class, "select_charset_for_writing"),
// "Charset", JOptionPane.QUESTION_MESSAGE, null,
// Charset.availableCharsets().values().toArray(),
// writer.getCharsetForWriting().displayName());
// if (resul == null)
// return;
// Charset charset = resul;
// writer.setCharsetForWriting(charset);
writeFeatures(mapContext, layer, writer, drv);
}
}
} catch (InitializeWriterException e) {
NotificationManager.addError(e.getMessage(),e);
} catch (OpenDriverException e) {
NotificationManager.addError(e.getMessage(),e);
} catch (ReadDriverException e) {
NotificationManager.addError(e.getMessage(),e);
} catch (DriverLoadException e) {
NotificationManager.addError(e.getMessage(),e);
}
}
private IndexedShpDriver getOpenShpDriver(File fileShp) throws OpenDriverException {
IndexedShpDriver drv = new IndexedShpDriver();
if (!fileShp.exists()) {
try {
fileShp.createNewFile();
File newFileSHX=new File(fileShp.getAbsolutePath().replaceAll("[.]shp",".shx"));
newFileSHX.createNewFile();
File newFileDBF=new File(fileShp.getAbsolutePath().replaceAll("[.]shp",".dbf"));
newFileDBF.createNewFile();
} catch (IOException e) {
throw new FileNotFoundDriverException("SHP",e,fileShp.getAbsolutePath());
}
}
drv.open(fileShp);
return drv;
}
/**
* @see com.iver.andami.plugins.IExtension#isEnabled()
*/
public boolean isEnabled() {
int status = EditionUtilities.getEditionStatus();
if (( status == EditionUtilities.EDITION_STATUS_ONE_VECTORIAL_LAYER_ACTIVE || status == EditionUtilities.EDITION_STATUS_ONE_VECTORIAL_LAYER_ACTIVE_AND_EDITABLE)
|| (status == EditionUtilities.EDITION_STATUS_MULTIPLE_VECTORIAL_LAYER_ACTIVE)|| (status == EditionUtilities.EDITION_STATUS_MULTIPLE_VECTORIAL_LAYER_ACTIVE_AND_EDITABLE))
{
return true;
}
return false;
}
/**
* @see com.iver.andami.plugins.IExtension#isVisible()
*/
public boolean isVisible() {
com.iver.andami.ui.mdiManager.IWindow f = PluginServices.getMDIManager()
.getActiveWindow();
if (f == null) {
return false;
}
if (f instanceof View)
return true;
return false;
}
private int findFileByName(FieldDescription[] fields, String fieldName){
for (int i=0; i < fields.length; i++)
{
FieldDescription f = fields[i];
if (f.getFieldName().equalsIgnoreCase(fieldName))
{
return i;
}
}
return -1;
}
}
| true | true | public void saveToPostGIS(MapContext mapContext, FLyrVect layer){
try {
String tableName = JOptionPane.showInputDialog(PluginServices
.getText(this, "intro_tablename"));
if (tableName == null)
return;
tableName = tableName.toLowerCase();
DlgConnection dlg = new DlgConnection(new String[]{"PostGIS JDBC Driver"});
dlg.setModal(true);
dlg.setVisible(true);
ConnectionSettings cs = dlg.getConnSettings();
if (cs == null)
return;
IConnection conex = ConnectionFactory.createConnection(cs
.getConnectionString(), cs.getUser(), cs.getPassw());
DBLayerDefinition originalDef = null;
if (layer.getSource().getDriver() instanceof IVectorialDatabaseDriver) {
originalDef=((IVectorialDatabaseDriver) layer.getSource().getDriver()).getLyrDef();
}
DBLayerDefinition dbLayerDef = new DBLayerDefinition();
// Fjp:
// Cambio: En Postgis, el nombre de cat�logo est� siempre vac�o. Es algo heredado de Oracle, que no se usa.
// dbLayerDef.setCatalogName(cs.getDb());
dbLayerDef.setCatalogName("");
// A�adimos el schema dentro del layer definition para poder tenerlo en cuenta.
dbLayerDef.setSchema(cs.getSchema());
dbLayerDef.setTableName(tableName);
dbLayerDef.setName(tableName);
dbLayerDef.setShapeType(layer.getShapeType());
SelectableDataSource sds = layer.getRecordset();
FieldDescription[] fieldsDescrip = sds.getFieldsDescription();
dbLayerDef.setFieldsDesc(fieldsDescrip);
// Creamos el driver. OJO: Hay que a�adir el campo ID a la
// definici�n de campos.
if (originalDef != null){
dbLayerDef.setFieldID(originalDef.getFieldID());
dbLayerDef.setFieldGeometry(originalDef.getFieldGeometry());
}else{
// Search for id field name
int index=0;
String fieldName="gid";
while (findFileByName(fieldsDescrip,fieldName) != -1){
index++;
fieldName="gid"+index;
}
dbLayerDef.setFieldID(fieldName);
// search for geom field name
index=0;
fieldName="the_geom";
while (findFileByName(fieldsDescrip,fieldName) != -1){
index++;
fieldName="the_geom"+index;
}
dbLayerDef.setFieldGeometry(fieldName);
}
// if id field dosen't exist we add it
if (findFileByName(fieldsDescrip,dbLayerDef.getFieldID()) == -1)
{
int numFieldsAnt = fieldsDescrip.length;
FieldDescription[] newFields = new FieldDescription[dbLayerDef.getFieldsDesc().length + 1];
for (int i=0; i < numFieldsAnt; i++)
{
newFields[i] = fieldsDescrip[i];
}
newFields[numFieldsAnt] = new FieldDescription();
newFields[numFieldsAnt].setFieldDecimalCount(0);
newFields[numFieldsAnt].setFieldType(Types.INTEGER);
newFields[numFieldsAnt].setFieldLength(7);
newFields[numFieldsAnt].setFieldName("gid");
dbLayerDef.setFieldsDesc(newFields);
}
// all fields to lowerCase
FieldDescription field;
for (int i=0;i<dbLayerDef.getFieldsDesc().length;i++){
field = dbLayerDef.getFieldsDesc()[i];
field.setFieldName(field.getFieldName().toLowerCase());
}
dbLayerDef.setFieldID(dbLayerDef.getFieldID().toLowerCase());
dbLayerDef.setFieldGeometry(dbLayerDef.getFieldGeometry().toLowerCase());
dbLayerDef.setWhereClause("");
String strSRID = layer.getProjection().getAbrev();
dbLayerDef.setSRID_EPSG(strSRID);
dbLayerDef.setConnection(conex);
PostGISWriter writer=(PostGISWriter)LayerFactory.getWM().getWriter("PostGIS Writer");
writer.setWriteAll(true);
writer.setCreateTable(true);
writer.initialize(dbLayerDef);
PostGisDriver postGISDriver=new PostGisDriver();
postGISDriver.setLyrDef(dbLayerDef);
postGISDriver.open();
PostProcessSupport.clearList();
Object[] params = new Object[2];
params[0] = conex;
params[1] = dbLayerDef;
PostProcessSupport.addToPostProcess(postGISDriver, "setData",
params, 1);
writeFeatures(mapContext, layer, writer, postGISDriver);
} catch (DriverLoadException e) {
NotificationManager.addError(e.getMessage(),e);
} catch (DBException e) {
NotificationManager.showMessageError(e.getLocalizedMessage(),e);
} catch (InitializeWriterException e) {
NotificationManager.addError(e.getMessage(),e);
} catch (ReadDriverException e) {
NotificationManager.addError(e.getMessage(),e);
}
}
| public void saveToPostGIS(MapContext mapContext, FLyrVect layer){
try {
String tableName = JOptionPane.showInputDialog(PluginServices
.getText(this, "intro_tablename"));
if (tableName == null)
return;
tableName = tableName.toLowerCase();
DlgConnection dlg = new DlgConnection(new String[]{"PostGIS JDBC Driver"});
dlg.setModal(true);
dlg.setVisible(true);
ConnectionSettings cs = dlg.getConnSettings();
if (cs == null)
return;
IConnection conex = ConnectionFactory.createConnection(cs
.getConnectionString(), cs.getUser(), cs.getPassw());
DBLayerDefinition originalDef = null;
if (layer.getSource().getDriver() instanceof IVectorialDatabaseDriver) {
originalDef=((IVectorialDatabaseDriver) layer.getSource().getDriver()).getLyrDef();
}
DBLayerDefinition dbLayerDef = new DBLayerDefinition();
// Fjp:
// Cambio: En Postgis, el nombre de cat�logo est� siempre vac�o. Es algo heredado de Oracle, que no se usa.
// dbLayerDef.setCatalogName(cs.getDb());
dbLayerDef.setCatalogName("");
// A�adimos el schema dentro del layer definition para poder tenerlo en cuenta.
dbLayerDef.setSchema(cs.getSchema());
dbLayerDef.setTableName(tableName);
dbLayerDef.setName(tableName);
dbLayerDef.setShapeType(layer.getShapeType());
SelectableDataSource sds = layer.getRecordset();
FieldDescription[] fieldsDescrip = sds.getFieldsDescription();
dbLayerDef.setFieldsDesc(fieldsDescrip);
// Creamos el driver. OJO: Hay que a�adir el campo ID a la
// definici�n de campos.
if (originalDef != null){
dbLayerDef.setFieldID(originalDef.getFieldID());
dbLayerDef.setFieldGeometry(originalDef.getFieldGeometry());
}else{
// Search for id field name
int index=0;
String fieldName="gid";
while (findFileByName(fieldsDescrip,fieldName) != -1){
index++;
fieldName="gid"+index;
}
dbLayerDef.setFieldID(fieldName);
// search for geom field name
index=0;
fieldName="the_geom";
while (findFileByName(fieldsDescrip,fieldName) != -1){
index++;
fieldName="the_geom"+index;
}
dbLayerDef.setFieldGeometry(fieldName);
}
// if id field dosen't exist we add it
if (findFileByName(fieldsDescrip,dbLayerDef.getFieldID()) == -1)
{
int numFieldsAnt = fieldsDescrip.length;
FieldDescription[] newFields = new FieldDescription[dbLayerDef.getFieldsDesc().length + 1];
for (int i=0; i < numFieldsAnt; i++)
{
newFields[i] = fieldsDescrip[i];
}
newFields[numFieldsAnt] = new FieldDescription();
newFields[numFieldsAnt].setFieldDecimalCount(0);
newFields[numFieldsAnt].setFieldType(Types.INTEGER);
newFields[numFieldsAnt].setFieldLength(7);
newFields[numFieldsAnt].setFieldName("gid");
dbLayerDef.setFieldsDesc(newFields);
}
// all fields to lowerCase
FieldDescription field;
for (int i=0;i<dbLayerDef.getFieldsDesc().length;i++){
field = dbLayerDef.getFieldsDesc()[i];
field.setFieldName(field.getFieldName().toLowerCase());
}
dbLayerDef.setFieldID(dbLayerDef.getFieldID().toLowerCase());
dbLayerDef.setFieldGeometry(dbLayerDef.getFieldGeometry().toLowerCase());
dbLayerDef.setWhereClause("");
String strSRID = layer.getProjection().getAbrev();
dbLayerDef.setSRID_EPSG(strSRID);
dbLayerDef.setConnection(conex);
PostGISWriter writer=(PostGISWriter)LayerFactory.getWM().getWriter("PostGIS Writer");
writer.setWriteAll(true);
writer.setCreateTable(true);
writer.initialize(dbLayerDef);
PostGisDriver postGISDriver=new PostGisDriver();
postGISDriver.setLyrDef(dbLayerDef);
postGISDriver.open();
PostProcessSupport.clearList();
Object[] params = new Object[2];
params[0] = conex;
params[1] = dbLayerDef;
PostProcessSupport.addToPostProcess(postGISDriver, "setData",
params, 1);
writeFeatures(mapContext, layer, writer, postGISDriver);
} catch (DriverLoadException e) {
NotificationManager.addError(e.getMessage(),e);
} catch (DBException e) {
NotificationManager.showMessageError(e.getLocalizedMessage(),e);
} catch (InitializeWriterException e) {
NotificationManager.showMessageError(e.getMessage(),e);
} catch (ReadDriverException e) {
NotificationManager.addError(e.getMessage(),e);
}
}
|
diff --git a/src/uk/ac/gla/dcs/tp3/w/algorithm/Main.java b/src/uk/ac/gla/dcs/tp3/w/algorithm/Main.java
index ea5155a..0920c32 100644
--- a/src/uk/ac/gla/dcs/tp3/w/algorithm/Main.java
+++ b/src/uk/ac/gla/dcs/tp3/w/algorithm/Main.java
@@ -1,107 +1,107 @@
package uk.ac.gla.dcs.tp3.w.algorithm;
import uk.ac.gla.dcs.tp3.w.league.*;
import uk.ac.gla.dcs.tp3.w.algorithm.Graph;
/**
* @author gordon
*
*/
public class Main {
/**
* @param args
*/
public static void main(String[] args) {
Team atlanta = new Team();
atlanta.setName("Atlanta");
atlanta.setGamesPlayed(170-8);
atlanta.setPoints(83);
Team philadelphia = new Team();
philadelphia.setName("Philadelphia");
philadelphia.setGamesPlayed(170-4);
philadelphia.setPoints(79);
Team newYork = new Team();
newYork.setName("New York");
newYork.setGamesPlayed(170-7);
newYork.setPoints(78);
Team montreal = new Team();
montreal.setName("Montreal");
montreal.setGamesPlayed(170-7);
montreal.setPoints(76);
Match[] atlantaMatches = new Match[8];
Match[] philadelphiaMatches = new Match[4];
Match[] newYorkMatches = new Match[7];
Match[] montrealMatches = new Match[5];
Match[] allMatches = new Match[12];
int am = 0;
int pm = 0;
int nym = 0;
int mm = 0;
int all = 0;
Match atlVphil = new Match();
atlVphil.setHomeTeam(atlanta);
atlVphil.setAwayTeam(philadelphia);
atlantaMatches[am++] = atlVphil;
philadelphiaMatches[pm++] = atlVphil;
allMatches[all++] = atlVphil;
Match atlVny = new Match();
atlVny.setHomeTeam(atlanta);
- atlVphil.setAwayTeam(newYork);
+ atlVny.setAwayTeam(newYork);
for (int i = 0; i < 6; i++) {
atlantaMatches[am++] = atlVny;
newYorkMatches[nym++] = atlVny;
allMatches[all++] = atlVny;
}
Match atlVmon = new Match();
atlVmon.setHomeTeam(atlanta);
atlVmon.setAwayTeam(montreal);
atlantaMatches[am++] = atlVmon;
montrealMatches[mm++] = atlVmon;
allMatches[all++] = atlVmon;
Match philVmon = new Match();
philVmon.setHomeTeam(philadelphia);
philVmon.setAwayTeam(montreal);
for (int i = 0; i < 3; i++) {
philadelphiaMatches[pm++] = philVmon;
montrealMatches[mm++] = philVmon;
allMatches[all++] = philVmon;
}
Match nyVmon = new Match();
nyVmon.setHomeTeam(newYork);
nyVmon.setAwayTeam(montreal);
newYorkMatches[nym++] = nyVmon;
montrealMatches[mm++] = nyVmon;
allMatches[all++] = nyVmon;
atlanta.setUpcomingMatches(atlantaMatches);
philadelphia.setUpcomingMatches(philadelphiaMatches);
newYork.setUpcomingMatches(newYorkMatches);
montreal.setUpcomingMatches(montrealMatches);
Team[] teams = new Team[4];
teams[0] = atlanta;
teams[1] = philadelphia;
teams[2] = newYork;
teams[3] = montreal;
League l = new League(teams, allMatches);
Graph g = new Graph(l, atlanta);
}
}
| true | true | public static void main(String[] args) {
Team atlanta = new Team();
atlanta.setName("Atlanta");
atlanta.setGamesPlayed(170-8);
atlanta.setPoints(83);
Team philadelphia = new Team();
philadelphia.setName("Philadelphia");
philadelphia.setGamesPlayed(170-4);
philadelphia.setPoints(79);
Team newYork = new Team();
newYork.setName("New York");
newYork.setGamesPlayed(170-7);
newYork.setPoints(78);
Team montreal = new Team();
montreal.setName("Montreal");
montreal.setGamesPlayed(170-7);
montreal.setPoints(76);
Match[] atlantaMatches = new Match[8];
Match[] philadelphiaMatches = new Match[4];
Match[] newYorkMatches = new Match[7];
Match[] montrealMatches = new Match[5];
Match[] allMatches = new Match[12];
int am = 0;
int pm = 0;
int nym = 0;
int mm = 0;
int all = 0;
Match atlVphil = new Match();
atlVphil.setHomeTeam(atlanta);
atlVphil.setAwayTeam(philadelphia);
atlantaMatches[am++] = atlVphil;
philadelphiaMatches[pm++] = atlVphil;
allMatches[all++] = atlVphil;
Match atlVny = new Match();
atlVny.setHomeTeam(atlanta);
atlVphil.setAwayTeam(newYork);
for (int i = 0; i < 6; i++) {
atlantaMatches[am++] = atlVny;
newYorkMatches[nym++] = atlVny;
allMatches[all++] = atlVny;
}
Match atlVmon = new Match();
atlVmon.setHomeTeam(atlanta);
atlVmon.setAwayTeam(montreal);
atlantaMatches[am++] = atlVmon;
montrealMatches[mm++] = atlVmon;
allMatches[all++] = atlVmon;
Match philVmon = new Match();
philVmon.setHomeTeam(philadelphia);
philVmon.setAwayTeam(montreal);
for (int i = 0; i < 3; i++) {
philadelphiaMatches[pm++] = philVmon;
montrealMatches[mm++] = philVmon;
allMatches[all++] = philVmon;
}
Match nyVmon = new Match();
nyVmon.setHomeTeam(newYork);
nyVmon.setAwayTeam(montreal);
newYorkMatches[nym++] = nyVmon;
montrealMatches[mm++] = nyVmon;
allMatches[all++] = nyVmon;
atlanta.setUpcomingMatches(atlantaMatches);
philadelphia.setUpcomingMatches(philadelphiaMatches);
newYork.setUpcomingMatches(newYorkMatches);
montreal.setUpcomingMatches(montrealMatches);
Team[] teams = new Team[4];
teams[0] = atlanta;
teams[1] = philadelphia;
teams[2] = newYork;
teams[3] = montreal;
League l = new League(teams, allMatches);
Graph g = new Graph(l, atlanta);
}
| public static void main(String[] args) {
Team atlanta = new Team();
atlanta.setName("Atlanta");
atlanta.setGamesPlayed(170-8);
atlanta.setPoints(83);
Team philadelphia = new Team();
philadelphia.setName("Philadelphia");
philadelphia.setGamesPlayed(170-4);
philadelphia.setPoints(79);
Team newYork = new Team();
newYork.setName("New York");
newYork.setGamesPlayed(170-7);
newYork.setPoints(78);
Team montreal = new Team();
montreal.setName("Montreal");
montreal.setGamesPlayed(170-7);
montreal.setPoints(76);
Match[] atlantaMatches = new Match[8];
Match[] philadelphiaMatches = new Match[4];
Match[] newYorkMatches = new Match[7];
Match[] montrealMatches = new Match[5];
Match[] allMatches = new Match[12];
int am = 0;
int pm = 0;
int nym = 0;
int mm = 0;
int all = 0;
Match atlVphil = new Match();
atlVphil.setHomeTeam(atlanta);
atlVphil.setAwayTeam(philadelphia);
atlantaMatches[am++] = atlVphil;
philadelphiaMatches[pm++] = atlVphil;
allMatches[all++] = atlVphil;
Match atlVny = new Match();
atlVny.setHomeTeam(atlanta);
atlVny.setAwayTeam(newYork);
for (int i = 0; i < 6; i++) {
atlantaMatches[am++] = atlVny;
newYorkMatches[nym++] = atlVny;
allMatches[all++] = atlVny;
}
Match atlVmon = new Match();
atlVmon.setHomeTeam(atlanta);
atlVmon.setAwayTeam(montreal);
atlantaMatches[am++] = atlVmon;
montrealMatches[mm++] = atlVmon;
allMatches[all++] = atlVmon;
Match philVmon = new Match();
philVmon.setHomeTeam(philadelphia);
philVmon.setAwayTeam(montreal);
for (int i = 0; i < 3; i++) {
philadelphiaMatches[pm++] = philVmon;
montrealMatches[mm++] = philVmon;
allMatches[all++] = philVmon;
}
Match nyVmon = new Match();
nyVmon.setHomeTeam(newYork);
nyVmon.setAwayTeam(montreal);
newYorkMatches[nym++] = nyVmon;
montrealMatches[mm++] = nyVmon;
allMatches[all++] = nyVmon;
atlanta.setUpcomingMatches(atlantaMatches);
philadelphia.setUpcomingMatches(philadelphiaMatches);
newYork.setUpcomingMatches(newYorkMatches);
montreal.setUpcomingMatches(montrealMatches);
Team[] teams = new Team[4];
teams[0] = atlanta;
teams[1] = philadelphia;
teams[2] = newYork;
teams[3] = montreal;
League l = new League(teams, allMatches);
Graph g = new Graph(l, atlanta);
}
|
diff --git a/src/java/net/sf/picard/sam/AbstractAlignmentMerger.java b/src/java/net/sf/picard/sam/AbstractAlignmentMerger.java
index 41c9e963..d85ce90b 100644
--- a/src/java/net/sf/picard/sam/AbstractAlignmentMerger.java
+++ b/src/java/net/sf/picard/sam/AbstractAlignmentMerger.java
@@ -1,408 +1,408 @@
/*
* The MIT License
*
* Copyright (c) 2009 The Broad Institute
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package net.sf.picard.sam;
import net.sf.picard.PicardException;
import net.sf.picard.io.IoUtil;
import net.sf.picard.reference.ReferenceSequenceFileWalker;
import net.sf.picard.util.CigarUtil;
import net.sf.picard.util.Log;
import net.sf.picard.util.PeekableIterator;
import net.sf.samtools.*;
import net.sf.samtools.util.CloseableIterator;
import net.sf.samtools.util.SequenceUtil;
import net.sf.samtools.util.SortingCollection;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;
/**
* Abstract class that coordinates the general task of taking in a set of alignment information,
* possibly in SAM format, possibly in other formats, and merging that with the set of all reads
* for which alignment was attempted, stored in an unmapped SAM file.
*
* The order of processing is as follows:
*
* 1. Get records from the unmapped bam and the alignment data
* 2. Merge the alignment information and public tags ONLY from the aligned SAMRecords
* 3. Do additional modifications -- handle clipping, trimming, etc.
* 4. Fix up mate information on paired reads
* 5. Do a final calculation of the NM and UQ tags.
* 6. Write the records to the output file.
*
* Concrete subclasses which extend AbstractAlignmentMerger should implement getQueryNameSortedAlignedRecords.
* If these records are not in queryname order, mergeAlignment will throw an IllegalStateException.
*
* Subclasses may optionally implement ignoreAlignment(), which can be used to skip over certain alignments.
*
*
* @author [email protected]
*/
public abstract class AbstractAlignmentMerger {
public static final int MAX_RECORDS_IN_RAM = 500000;
private static final char[] RESERVED_ATTRIBUTE_STARTS = {'X','Y', 'Z'};
private final Log log = Log.getInstance(AbstractAlignmentMerger.class);
private final File unmappedBamFile;
private final File targetBamFile;
private SAMSequenceDictionary sequenceDictionary = null;
private ReferenceSequenceFileWalker refSeq = null;
private final boolean clipAdapters;
private final boolean bisulfiteSequence;
private SAMProgramRecord programRecord;
private final boolean alignedReadsOnly;
private final SAMFileHeader header;
private final List<String> attributesToRetain = new ArrayList<String>();
private final File referenceFasta;
private final Integer read1BasesTrimmed;
private final Integer read2BasesTrimmed;
private final List<SamPairUtil.PairOrientation> expectedOrientations;
protected abstract CloseableIterator<SAMRecord> getQuerynameSortedAlignedRecords();
protected boolean ignoreAlignment(SAMRecord sam) { return false; } // default implementation
/**
* Constructor
*
* @param unmappedBamFile The BAM file that was used as the input to the aligner, which will
* include info on all the reads that did not map. Required.
* @param targetBamFile The file to which to write the merged SAM records. Required.
* @param referenceFasta The reference sequence for the map files. Required.
* @param clipAdapters Whether adapters marked in unmapped BAM file should be marked as
* soft clipped in the merged bam. Required.
* @param bisulfiteSequence Whether the reads are bisulfite sequence (used when calculating the
* NM and UQ tags). Required.
* @param alignedReadsOnly Whether to output only those reads that have alignment data
* @param programRecord Program record for taget file SAMRecords created.
* @param attributesToRetain private attributes from the alignment record that should be
* included when merging. This overrides the exclusion of
* attributes whose tags start with the reserved characters
* of X, Y, and Z
* @param read1BasesTrimmed The number of bases trimmed from start of read 1 prior to alignment. Optional.
* @param read2BasesTrimmed The number of bases trimmed from start of read 2 prior to alignment. Optional.
* @param expectedOrientations A List of SamPairUtil.PairOrientations that are expected for
* aligned pairs. Used to determine the properPair flag.
*/
public AbstractAlignmentMerger(final File unmappedBamFile, final File targetBamFile,
final File referenceFasta, final boolean clipAdapters,
final boolean bisulfiteSequence, final boolean alignedReadsOnly,
final SAMProgramRecord programRecord, final List<String> attributesToRetain,
final Integer read1BasesTrimmed, final Integer read2BasesTrimmed,
final List<SamPairUtil.PairOrientation> expectedOrientations) {
IoUtil.assertFileIsReadable(unmappedBamFile);
IoUtil.assertFileIsWritable(targetBamFile);
IoUtil.assertFileIsReadable(referenceFasta);
this.unmappedBamFile = unmappedBamFile;
this.targetBamFile = targetBamFile;
this.referenceFasta = referenceFasta;
this.refSeq = new ReferenceSequenceFileWalker(referenceFasta);
this.sequenceDictionary = refSeq.getSequenceDictionary();
this.clipAdapters = clipAdapters;
this.bisulfiteSequence = bisulfiteSequence;
this.alignedReadsOnly = alignedReadsOnly;
this.programRecord = programRecord;
this.header = new SAMFileHeader();
header.setSortOrder(SAMFileHeader.SortOrder.coordinate);
if (programRecord != null) {
header.addProgramRecord(programRecord);
}
header.setSequenceDictionary(this.sequenceDictionary);
if (attributesToRetain != null) {
this.attributesToRetain.addAll(attributesToRetain);
}
this.read1BasesTrimmed = read1BasesTrimmed;
this.read2BasesTrimmed = read2BasesTrimmed;
this.expectedOrientations = expectedOrientations;
}
/**
* Merges the alignment data with the non-aligned records from the source BAM file.
*/
public void mergeAlignment() {
final SAMRecordQueryNameComparator comparator = new SAMRecordQueryNameComparator();
// Open the file of unmapped records and write the read groups to the the header for the merged file
final SAMFileReader unmappedSam = new SAMFileReader(this.unmappedBamFile);
final CloseableIterator<SAMRecord> unmappedIterator = unmappedSam.iterator();
this.header.setReadGroups(unmappedSam.getFileHeader().getReadGroups());
int aligned = 0;
int unmapped = 0;
// Get the aligned records and set up the first one
final CloseableIterator<SAMRecord> alignedIterator = getQuerynameSortedAlignedRecords();
SAMRecord nextAligned = alignedIterator.hasNext() ? alignedIterator.next() : null;
// Create the sorting collection that will write the records in coordinate order
// to the final bam file
final SortingCollection<SAMRecord> coordinateSorted = SortingCollection.newInstance(
SAMRecord.class, new BAMRecordCodec(header), new SAMRecordCoordinateComparator(),
MAX_RECORDS_IN_RAM);
SAMRecord firstOfPair = null;
while (unmappedIterator.hasNext()) {
final SAMRecord rec = unmappedIterator.next();
if (nextAligned != null && comparator.compare(rec, nextAligned) > 0) {
throw new IllegalStateException("Aligned record iterator (" + nextAligned.getReadName() +
") is behind the unmapped reads (" + rec.getReadName() + ")");
}
rec.setHeader(this.header);
// If the next record is a match and is an acceptable alignment, pull the info over to the unmapped record
if (isMatch(rec, nextAligned)) {
if (!(nextAligned.getReadUnmappedFlag() || ignoreAlignment(nextAligned))) {
setValuesFromAlignment(rec, nextAligned);
updateCigarForTrimmedOrClippedBases(rec, nextAligned);
if (this.programRecord != null) {
rec.setAttribute(ReservedTagConstants.PROGRAM_GROUP_ID,
this.programRecord.getProgramGroupId());
}
aligned++;
}
else {
unmapped++;
}
nextAligned = alignedIterator.hasNext() ? alignedIterator.next() : null;
}
else {
unmapped++;
}
// If it's single-end, then just add it if appropriate
if (!rec.getReadPairedFlag()) {
if (!rec.getReadUnmappedFlag() || !alignedReadsOnly) {
coordinateSorted.add(rec);
}
}
else {
// If it's the first read of a pair, hang on to it until we see its mate next
if (firstOfPair == null) {
firstOfPair = rec;
}
else { // Now we should have the pair, but may not if the aligner used does retain the
// unmapped read from a pair (e.g. Maq)
if (!rec.getReadName().equals(firstOfPair.getReadName())) {
- coordinateSorted.add(firstOfPair);
- firstOfPair = rec;
+ throw new PicardException("Second read from pair not found in unmapped bam: " +
+ rec.getReadName());
}
else {
// IF at least one of the reads is mapped or we are writing them all
if ((!rec.getReadUnmappedFlag() || !firstOfPair.getReadUnmappedFlag()) || !alignedReadsOnly) {
clipForOverlappingReads(rec, firstOfPair);
SamPairUtil.setProperPairAndMateInfo(rec, firstOfPair, header, expectedOrientations);
coordinateSorted.add(firstOfPair);
coordinateSorted.add(rec);
firstOfPair = null;
}
}
}
}
}
unmappedIterator.close();
if (alignedIterator.hasNext()) {
throw new IllegalStateException("Reads remaining on alignment iterator: " + alignedIterator.next().getReadName() + "!");
}
alignedIterator.close();
// Write the records to the output file in coordinate sorted order,
final SAMFileWriter writer = new SAMFileWriterFactory().makeSAMOrBAMWriter(header, true, this.targetBamFile);
int count = 0;
CloseableIterator<SAMRecord> it = coordinateSorted.iterator();
while (it.hasNext()) {
SAMRecord rec = it.next();
if (!rec.getReadUnmappedFlag()) {
if (refSeq != null) {
byte referenceBases[] = refSeq.get(sequenceDictionary.getSequenceIndex(rec.getReferenceName())).getBases();
rec.setAttribute(SAMTag.NM.name(),
SequenceUtil.calculateSamNmTag(rec, referenceBases, 0, bisulfiteSequence));
if (rec.getBaseQualities() != SAMRecord.NULL_QUALS) {
rec.setAttribute(SAMTag.UQ.name(),
SequenceUtil.sumQualitiesOfMismatches(rec, referenceBases, 0, bisulfiteSequence));
}
}
}
writer.addAlignment(rec);
if (++count % 1000000 == 0) {
log.info(count + " SAMRecords written to " + targetBamFile.getName());
}
}
writer.close();
log.info("Wrote " + aligned + " alignment records and " + (alignedReadsOnly ? 0 : unmapped) + " unmapped reads.");
}
/**
* Checks to see whether the ends of the reads overlap and soft clips reads
* them if necessary.
*/
protected void clipForOverlappingReads(final SAMRecord read1, final SAMRecord read2) {
// If both reads are mapped, see if we need to clip the ends due to small
// insert size
if (!(read1.getReadUnmappedFlag() || read2.getReadUnmappedFlag())) {
if (read1.getReadNegativeStrandFlag() != read2.getReadNegativeStrandFlag())
{
final SAMRecord pos = (read1.getReadNegativeStrandFlag()) ? read2 : read1;
final SAMRecord neg = (read1.getReadNegativeStrandFlag()) ? read1 : read2;
// Innies only -- do we need to do anything else about jumping libraries?
if (pos.getAlignmentStart() < neg.getAlignmentEnd()) {
final int posDiff = pos.getAlignmentEnd() - neg.getAlignmentEnd();
final int negDiff = pos.getAlignmentStart() - neg.getAlignmentStart();
if (posDiff > 0) {
CigarUtil.softClip3PrimeEndOfRead(pos, Math.min(pos.getReadLength(),
pos.getReadLength() - posDiff + 1));
}
if (negDiff > 0) {
CigarUtil.softClip3PrimeEndOfRead(neg, Math.min(neg.getReadLength(),
neg.getReadLength() - negDiff + 1));
}
}
}
else {
// TODO: What about RR/FF pairs?
}
}
}
/**
* Determines whether two SAMRecords represent the same read
*/
protected boolean isMatch(final SAMRecord unaligned, final SAMRecord aligned) {
return (aligned != null &&
aligned.getReadName().equals(unaligned.getReadName()) &&
(unaligned.getReadPairedFlag() == false ||
aligned.getFirstOfPairFlag() == unaligned.getFirstOfPairFlag()));
}
/**
* Sets the values from the alignment record on the unaligned BAM record. This
* preserves all data from the unaligned record (ReadGroup, NoiseRead status, etc)
* and adds all the alignment info
*
* @param rec The unaligned read record
* @param alignment The alignment record
*/
protected void setValuesFromAlignment(final SAMRecord rec, final SAMRecord alignment) {
for (final SAMRecord.SAMTagAndValue attr : alignment.getAttributes()) {
// Copy over any non-reserved attributes.
if (!isReservedTag(attr.tag) || this.attributesToRetain.contains(attr.tag)) {
rec.setAttribute(attr.tag, attr.value);
}
}
rec.setReadUnmappedFlag(alignment.getReadUnmappedFlag());
rec.setReferenceName(alignment.getReferenceName());
rec.setAlignmentStart(alignment.getAlignmentStart());
rec.setReadNegativeStrandFlag(alignment.getReadNegativeStrandFlag());
if (!alignment.getReadUnmappedFlag()) {
// only aligned reads should have cigar and mapping quality set
rec.setCigar(alignment.getCigar()); // cigar may change when a
// clipCigar called below
rec.setMappingQuality(alignment.getMappingQuality());
}
if (rec.getReadPairedFlag()) {
rec.setProperPairFlag(alignment.getProperPairFlag());
// Mate info and alignment size will get set by the ClippedPairFixer.
}
// If it's on the negative strand, reverse complement the bases
// and reverse the order of the qualities
if (rec.getReadNegativeStrandFlag()) {
SAMRecordUtil.reverseComplement(rec);
}
}
protected void updateCigarForTrimmedOrClippedBases(final SAMRecord rec, final SAMRecord alignment) {
// If the read maps off the end of the alignment, clip it
SAMSequenceRecord refseq = rec.getHeader().getSequence(rec.getReferenceIndex());
if (rec.getAlignmentEnd() > refseq.getSequenceLength()) {
// 1-based index of first base in read to clip.
int clipFrom = refseq.getSequenceLength() - rec.getAlignmentStart() + 1;
List<CigarElement> newCigarElements = CigarUtil.softClipEndOfRead(clipFrom, rec.getCigar().getCigarElements());
rec.setCigar(new Cigar(newCigarElements));
}
// If the read was trimmed or not all the bases were sent for alignment, clip it
int alignmentReadLength = alignment.getReadLength();
int originalReadLength = rec.getReadLength();
int trimmed = (!rec.getReadPairedFlag()) || rec.getFirstOfPairFlag()
? this.read1BasesTrimmed != null ? this.read1BasesTrimmed : 0
: this.read2BasesTrimmed != null ? this.read2BasesTrimmed : 0;
int notWritten = originalReadLength - (alignmentReadLength + trimmed);
rec.setCigar(CigarUtil.addSoftClippedBasesToEndsOfCigar(
rec.getCigar(), rec.getReadNegativeStrandFlag(), notWritten, trimmed));
// If the adapter sequence is marked and clipAdapter is true, ciip it
if (this.clipAdapters && rec.getAttribute(ReservedTagConstants.XT) != null){
CigarUtil.softClip3PrimeEndOfRead(rec, rec.getIntegerAttribute(ReservedTagConstants.XT));
}
}
protected SAMSequenceDictionary getSequenceDictionary() { return this.sequenceDictionary; }
protected SAMProgramRecord getProgramRecord() { return this.programRecord; }
protected void setProgramRecord(SAMProgramRecord pg ) {
this.programRecord = pg;
this.header.addProgramRecord(pg);
}
protected boolean isReservedTag(String tag) {
for (char c : RESERVED_ATTRIBUTE_STARTS) {
if (tag.charAt(0) == c) return true;
}
return false;
}
protected SAMFileHeader getHeader() { return this.header; }
protected void resetRefSeqFileWalker() {
this.refSeq = new ReferenceSequenceFileWalker(referenceFasta);
}
}
| true | true | public void mergeAlignment() {
final SAMRecordQueryNameComparator comparator = new SAMRecordQueryNameComparator();
// Open the file of unmapped records and write the read groups to the the header for the merged file
final SAMFileReader unmappedSam = new SAMFileReader(this.unmappedBamFile);
final CloseableIterator<SAMRecord> unmappedIterator = unmappedSam.iterator();
this.header.setReadGroups(unmappedSam.getFileHeader().getReadGroups());
int aligned = 0;
int unmapped = 0;
// Get the aligned records and set up the first one
final CloseableIterator<SAMRecord> alignedIterator = getQuerynameSortedAlignedRecords();
SAMRecord nextAligned = alignedIterator.hasNext() ? alignedIterator.next() : null;
// Create the sorting collection that will write the records in coordinate order
// to the final bam file
final SortingCollection<SAMRecord> coordinateSorted = SortingCollection.newInstance(
SAMRecord.class, new BAMRecordCodec(header), new SAMRecordCoordinateComparator(),
MAX_RECORDS_IN_RAM);
SAMRecord firstOfPair = null;
while (unmappedIterator.hasNext()) {
final SAMRecord rec = unmappedIterator.next();
if (nextAligned != null && comparator.compare(rec, nextAligned) > 0) {
throw new IllegalStateException("Aligned record iterator (" + nextAligned.getReadName() +
") is behind the unmapped reads (" + rec.getReadName() + ")");
}
rec.setHeader(this.header);
// If the next record is a match and is an acceptable alignment, pull the info over to the unmapped record
if (isMatch(rec, nextAligned)) {
if (!(nextAligned.getReadUnmappedFlag() || ignoreAlignment(nextAligned))) {
setValuesFromAlignment(rec, nextAligned);
updateCigarForTrimmedOrClippedBases(rec, nextAligned);
if (this.programRecord != null) {
rec.setAttribute(ReservedTagConstants.PROGRAM_GROUP_ID,
this.programRecord.getProgramGroupId());
}
aligned++;
}
else {
unmapped++;
}
nextAligned = alignedIterator.hasNext() ? alignedIterator.next() : null;
}
else {
unmapped++;
}
// If it's single-end, then just add it if appropriate
if (!rec.getReadPairedFlag()) {
if (!rec.getReadUnmappedFlag() || !alignedReadsOnly) {
coordinateSorted.add(rec);
}
}
else {
// If it's the first read of a pair, hang on to it until we see its mate next
if (firstOfPair == null) {
firstOfPair = rec;
}
else { // Now we should have the pair, but may not if the aligner used does retain the
// unmapped read from a pair (e.g. Maq)
if (!rec.getReadName().equals(firstOfPair.getReadName())) {
coordinateSorted.add(firstOfPair);
firstOfPair = rec;
}
else {
// IF at least one of the reads is mapped or we are writing them all
if ((!rec.getReadUnmappedFlag() || !firstOfPair.getReadUnmappedFlag()) || !alignedReadsOnly) {
clipForOverlappingReads(rec, firstOfPair);
SamPairUtil.setProperPairAndMateInfo(rec, firstOfPair, header, expectedOrientations);
coordinateSorted.add(firstOfPair);
coordinateSorted.add(rec);
firstOfPair = null;
}
}
}
}
}
unmappedIterator.close();
if (alignedIterator.hasNext()) {
throw new IllegalStateException("Reads remaining on alignment iterator: " + alignedIterator.next().getReadName() + "!");
}
alignedIterator.close();
// Write the records to the output file in coordinate sorted order,
final SAMFileWriter writer = new SAMFileWriterFactory().makeSAMOrBAMWriter(header, true, this.targetBamFile);
int count = 0;
CloseableIterator<SAMRecord> it = coordinateSorted.iterator();
while (it.hasNext()) {
SAMRecord rec = it.next();
if (!rec.getReadUnmappedFlag()) {
if (refSeq != null) {
byte referenceBases[] = refSeq.get(sequenceDictionary.getSequenceIndex(rec.getReferenceName())).getBases();
rec.setAttribute(SAMTag.NM.name(),
SequenceUtil.calculateSamNmTag(rec, referenceBases, 0, bisulfiteSequence));
if (rec.getBaseQualities() != SAMRecord.NULL_QUALS) {
rec.setAttribute(SAMTag.UQ.name(),
SequenceUtil.sumQualitiesOfMismatches(rec, referenceBases, 0, bisulfiteSequence));
}
}
}
writer.addAlignment(rec);
if (++count % 1000000 == 0) {
log.info(count + " SAMRecords written to " + targetBamFile.getName());
}
}
writer.close();
log.info("Wrote " + aligned + " alignment records and " + (alignedReadsOnly ? 0 : unmapped) + " unmapped reads.");
}
| public void mergeAlignment() {
final SAMRecordQueryNameComparator comparator = new SAMRecordQueryNameComparator();
// Open the file of unmapped records and write the read groups to the the header for the merged file
final SAMFileReader unmappedSam = new SAMFileReader(this.unmappedBamFile);
final CloseableIterator<SAMRecord> unmappedIterator = unmappedSam.iterator();
this.header.setReadGroups(unmappedSam.getFileHeader().getReadGroups());
int aligned = 0;
int unmapped = 0;
// Get the aligned records and set up the first one
final CloseableIterator<SAMRecord> alignedIterator = getQuerynameSortedAlignedRecords();
SAMRecord nextAligned = alignedIterator.hasNext() ? alignedIterator.next() : null;
// Create the sorting collection that will write the records in coordinate order
// to the final bam file
final SortingCollection<SAMRecord> coordinateSorted = SortingCollection.newInstance(
SAMRecord.class, new BAMRecordCodec(header), new SAMRecordCoordinateComparator(),
MAX_RECORDS_IN_RAM);
SAMRecord firstOfPair = null;
while (unmappedIterator.hasNext()) {
final SAMRecord rec = unmappedIterator.next();
if (nextAligned != null && comparator.compare(rec, nextAligned) > 0) {
throw new IllegalStateException("Aligned record iterator (" + nextAligned.getReadName() +
") is behind the unmapped reads (" + rec.getReadName() + ")");
}
rec.setHeader(this.header);
// If the next record is a match and is an acceptable alignment, pull the info over to the unmapped record
if (isMatch(rec, nextAligned)) {
if (!(nextAligned.getReadUnmappedFlag() || ignoreAlignment(nextAligned))) {
setValuesFromAlignment(rec, nextAligned);
updateCigarForTrimmedOrClippedBases(rec, nextAligned);
if (this.programRecord != null) {
rec.setAttribute(ReservedTagConstants.PROGRAM_GROUP_ID,
this.programRecord.getProgramGroupId());
}
aligned++;
}
else {
unmapped++;
}
nextAligned = alignedIterator.hasNext() ? alignedIterator.next() : null;
}
else {
unmapped++;
}
// If it's single-end, then just add it if appropriate
if (!rec.getReadPairedFlag()) {
if (!rec.getReadUnmappedFlag() || !alignedReadsOnly) {
coordinateSorted.add(rec);
}
}
else {
// If it's the first read of a pair, hang on to it until we see its mate next
if (firstOfPair == null) {
firstOfPair = rec;
}
else { // Now we should have the pair, but may not if the aligner used does retain the
// unmapped read from a pair (e.g. Maq)
if (!rec.getReadName().equals(firstOfPair.getReadName())) {
throw new PicardException("Second read from pair not found in unmapped bam: " +
rec.getReadName());
}
else {
// IF at least one of the reads is mapped or we are writing them all
if ((!rec.getReadUnmappedFlag() || !firstOfPair.getReadUnmappedFlag()) || !alignedReadsOnly) {
clipForOverlappingReads(rec, firstOfPair);
SamPairUtil.setProperPairAndMateInfo(rec, firstOfPair, header, expectedOrientations);
coordinateSorted.add(firstOfPair);
coordinateSorted.add(rec);
firstOfPair = null;
}
}
}
}
}
unmappedIterator.close();
if (alignedIterator.hasNext()) {
throw new IllegalStateException("Reads remaining on alignment iterator: " + alignedIterator.next().getReadName() + "!");
}
alignedIterator.close();
// Write the records to the output file in coordinate sorted order,
final SAMFileWriter writer = new SAMFileWriterFactory().makeSAMOrBAMWriter(header, true, this.targetBamFile);
int count = 0;
CloseableIterator<SAMRecord> it = coordinateSorted.iterator();
while (it.hasNext()) {
SAMRecord rec = it.next();
if (!rec.getReadUnmappedFlag()) {
if (refSeq != null) {
byte referenceBases[] = refSeq.get(sequenceDictionary.getSequenceIndex(rec.getReferenceName())).getBases();
rec.setAttribute(SAMTag.NM.name(),
SequenceUtil.calculateSamNmTag(rec, referenceBases, 0, bisulfiteSequence));
if (rec.getBaseQualities() != SAMRecord.NULL_QUALS) {
rec.setAttribute(SAMTag.UQ.name(),
SequenceUtil.sumQualitiesOfMismatches(rec, referenceBases, 0, bisulfiteSequence));
}
}
}
writer.addAlignment(rec);
if (++count % 1000000 == 0) {
log.info(count + " SAMRecords written to " + targetBamFile.getName());
}
}
writer.close();
log.info("Wrote " + aligned + " alignment records and " + (alignedReadsOnly ? 0 : unmapped) + " unmapped reads.");
}
|
diff --git a/src/at/ac/prog/calculator/engine/CalcParser.java b/src/at/ac/prog/calculator/engine/CalcParser.java
index 8353c29..c55656b 100644
--- a/src/at/ac/prog/calculator/engine/CalcParser.java
+++ b/src/at/ac/prog/calculator/engine/CalcParser.java
@@ -1,197 +1,197 @@
package at.ac.prog.calculator.engine;
import java.util.ArrayList;
import java.util.regex.Pattern;
import at.ac.prog.calculator.engine.exception.CalcParsingException;
public class CalcParser {
private ArrayList<String> parsedElems;
private final CalcStack stack = new CalcStack();
public CalcParser() {
parsedElems = new ArrayList<String>();
}
/**
* For debug purposes.
*/
public void clear() {
this.parsedElems.clear();
this.stack.clear();
}
public void parse(String command) throws CalcParsingException {
command = command.replaceAll("\\s+", " ");
String newElem = null;
int numOpenBrackets = 0;
boolean readSpecialCharacter = false;
for (int i = 0; i < command.length(); i++) {
// DEBUG: System.out.println("TESTING: " + command.charAt(i));
if(readSpecialCharacter == true) {
switch(command.charAt(i)) {
case 'n': {//line feed
parsedElems.add("\n");
break;
}
case 't': { //tabulator
parsedElems.add("\t");
break;
}
case 'r': { //carriage return
parsedElems.add("\r");
break;
}
case ' ': {//space
parsedElems.add(" ");
break;
}
case '\\': { //backslash
parsedElems.add("\\");
break;
} default: {
if(isOperator("" + command.charAt(i))) {
parsedElems.add("\\" + (command.charAt(i)));
} else {
throw new CalcParsingException("Invalid escape character: " + command.charAt(i));
}
}
}
readSpecialCharacter = false;
continue;
}
switch(command.charAt(i)) {
case '[': {
- //catch the special case where a digit is in front of an opening bracket and we are NOT inside a bracket (e.g. '9[2*]@'
+ //catch the special case where a digit is in front of an opening bracket and we are NOT inside a bracket (e.g. '9[2*]@')
if(newElem != null && numOpenBrackets == 0) {
parsedElems.add(newElem);
newElem = null;
}
if(numOpenBrackets != 0) {
newElem += command.charAt(i);
numOpenBrackets++;
} else {
newElem = String.valueOf(command.charAt(i));
numOpenBrackets = 1;
}
break;
} case ']': {
if(numOpenBrackets == 1) {
newElem += command.charAt(i);
numOpenBrackets = 0;
parsedElems.add(newElem);
newElem = null;
} else {
newElem += command.charAt(i);
numOpenBrackets--;
}
break;
} default: {
if(numOpenBrackets != 0) {
newElem += command.charAt(i);
}
else {
switch(command.charAt(i)) {
case ' ':
if(newElem != null) {
parsedElems.add(newElem);
newElem = null;
}
break;
default:
Pattern pattern = Pattern.compile("\\d");
if ((pattern.matcher(String.valueOf(command.charAt(i)))).matches() == true) {
if((newElem != null) && (isNumeric(newElem) == true)) {
newElem += command.charAt(i);
} else {
newElem = String.valueOf(command.charAt(i));
}
break;
} else {
if(isNumeric(newElem) == true) {
parsedElems.add(newElem);
newElem = null;
}
}
pattern = Pattern.compile("\\+|-|\\*|/|%|&|=|<|>|~|!|#|@|\"|'|\\|");
if ((pattern.matcher(String.valueOf(command.charAt(i)))).matches() == true) {
parsedElems.add(String.valueOf(command.charAt(i)));
} else if(command.charAt(i) == '?') {
parsedElems.add(String.valueOf(command.charAt(i)));
} else if(command.charAt(i) == '\\') {
readSpecialCharacter = true;
} else {
parsedElems.add(String.valueOf(command.charAt(i))); //Printable ASCII Characters
}
break;
}
}
}
}
}
//we need this, because we could be parsing an expression such as 0, and after the 0 has been parsed,
//the loop stops without adding newElem to the list of parsed elements.
if(newElem != null) {
parsedElems.add(newElem);
}
if(numOpenBrackets > 0) {
throw new CalcParsingException("closingBracket not found");
}
//Convert the current input list of parsed element into a stack.
createStack();
}
public static boolean isNumeric(String str) {
try {
Integer.parseInt(str);
} catch(NumberFormatException nfe) {
return false;
}
return true;
}
private void createStack() {
String first;
while(parsedElems.size() > 0 && (first = parsedElems.remove(0)) != null) {
Integer integer = null;
try {
integer = Integer.parseInt(first);
} catch(NumberFormatException e) { }
if(integer != null) {
stack.push(integer);
} else {
if(first.length() == 2 && first.charAt(0) == '\\') {
char c = first.charAt(1);
stack.push(new Integer(c));
} else if(first.length() == 1 && !isOperator(first)) {
char c = first.charAt(0);
stack.push(new Integer(c));
} else {
stack.push(first); //we got an operator or an expression
}
}
}
assert(parsedElems.size() == 0);
}
public boolean isOperator(String token) {
Pattern pattern = Pattern.compile("\\+|-|\\*|/|%|&|=|<|>|~|!|#|@|\"|'|\\||\\?");
return pattern.matcher(token).matches();
}
public void debugOutput() {
System.out.println("---------------------------------- DEBUG -------------------------------------");
int i;
for(i = 0; i < this.stack.size(); i++) {
System.out.println("Element Stack" + i + ": " + this.stack.get(i));
}
}
public CalcStack getStack() {
return stack;
}
}
| true | true | public void parse(String command) throws CalcParsingException {
command = command.replaceAll("\\s+", " ");
String newElem = null;
int numOpenBrackets = 0;
boolean readSpecialCharacter = false;
for (int i = 0; i < command.length(); i++) {
// DEBUG: System.out.println("TESTING: " + command.charAt(i));
if(readSpecialCharacter == true) {
switch(command.charAt(i)) {
case 'n': {//line feed
parsedElems.add("\n");
break;
}
case 't': { //tabulator
parsedElems.add("\t");
break;
}
case 'r': { //carriage return
parsedElems.add("\r");
break;
}
case ' ': {//space
parsedElems.add(" ");
break;
}
case '\\': { //backslash
parsedElems.add("\\");
break;
} default: {
if(isOperator("" + command.charAt(i))) {
parsedElems.add("\\" + (command.charAt(i)));
} else {
throw new CalcParsingException("Invalid escape character: " + command.charAt(i));
}
}
}
readSpecialCharacter = false;
continue;
}
switch(command.charAt(i)) {
case '[': {
//catch the special case where a digit is in front of an opening bracket and we are NOT inside a bracket (e.g. '9[2*]@'
if(newElem != null && numOpenBrackets == 0) {
parsedElems.add(newElem);
newElem = null;
}
if(numOpenBrackets != 0) {
newElem += command.charAt(i);
numOpenBrackets++;
} else {
newElem = String.valueOf(command.charAt(i));
numOpenBrackets = 1;
}
break;
} case ']': {
if(numOpenBrackets == 1) {
newElem += command.charAt(i);
numOpenBrackets = 0;
parsedElems.add(newElem);
newElem = null;
} else {
newElem += command.charAt(i);
numOpenBrackets--;
}
break;
} default: {
if(numOpenBrackets != 0) {
newElem += command.charAt(i);
}
else {
switch(command.charAt(i)) {
case ' ':
if(newElem != null) {
parsedElems.add(newElem);
newElem = null;
}
break;
default:
Pattern pattern = Pattern.compile("\\d");
if ((pattern.matcher(String.valueOf(command.charAt(i)))).matches() == true) {
if((newElem != null) && (isNumeric(newElem) == true)) {
newElem += command.charAt(i);
} else {
newElem = String.valueOf(command.charAt(i));
}
break;
} else {
if(isNumeric(newElem) == true) {
parsedElems.add(newElem);
newElem = null;
}
}
pattern = Pattern.compile("\\+|-|\\*|/|%|&|=|<|>|~|!|#|@|\"|'|\\|");
if ((pattern.matcher(String.valueOf(command.charAt(i)))).matches() == true) {
parsedElems.add(String.valueOf(command.charAt(i)));
} else if(command.charAt(i) == '?') {
parsedElems.add(String.valueOf(command.charAt(i)));
} else if(command.charAt(i) == '\\') {
readSpecialCharacter = true;
} else {
parsedElems.add(String.valueOf(command.charAt(i))); //Printable ASCII Characters
}
break;
}
}
}
}
}
//we need this, because we could be parsing an expression such as 0, and after the 0 has been parsed,
//the loop stops without adding newElem to the list of parsed elements.
if(newElem != null) {
parsedElems.add(newElem);
}
if(numOpenBrackets > 0) {
throw new CalcParsingException("closingBracket not found");
}
//Convert the current input list of parsed element into a stack.
createStack();
}
| public void parse(String command) throws CalcParsingException {
command = command.replaceAll("\\s+", " ");
String newElem = null;
int numOpenBrackets = 0;
boolean readSpecialCharacter = false;
for (int i = 0; i < command.length(); i++) {
// DEBUG: System.out.println("TESTING: " + command.charAt(i));
if(readSpecialCharacter == true) {
switch(command.charAt(i)) {
case 'n': {//line feed
parsedElems.add("\n");
break;
}
case 't': { //tabulator
parsedElems.add("\t");
break;
}
case 'r': { //carriage return
parsedElems.add("\r");
break;
}
case ' ': {//space
parsedElems.add(" ");
break;
}
case '\\': { //backslash
parsedElems.add("\\");
break;
} default: {
if(isOperator("" + command.charAt(i))) {
parsedElems.add("\\" + (command.charAt(i)));
} else {
throw new CalcParsingException("Invalid escape character: " + command.charAt(i));
}
}
}
readSpecialCharacter = false;
continue;
}
switch(command.charAt(i)) {
case '[': {
//catch the special case where a digit is in front of an opening bracket and we are NOT inside a bracket (e.g. '9[2*]@')
if(newElem != null && numOpenBrackets == 0) {
parsedElems.add(newElem);
newElem = null;
}
if(numOpenBrackets != 0) {
newElem += command.charAt(i);
numOpenBrackets++;
} else {
newElem = String.valueOf(command.charAt(i));
numOpenBrackets = 1;
}
break;
} case ']': {
if(numOpenBrackets == 1) {
newElem += command.charAt(i);
numOpenBrackets = 0;
parsedElems.add(newElem);
newElem = null;
} else {
newElem += command.charAt(i);
numOpenBrackets--;
}
break;
} default: {
if(numOpenBrackets != 0) {
newElem += command.charAt(i);
}
else {
switch(command.charAt(i)) {
case ' ':
if(newElem != null) {
parsedElems.add(newElem);
newElem = null;
}
break;
default:
Pattern pattern = Pattern.compile("\\d");
if ((pattern.matcher(String.valueOf(command.charAt(i)))).matches() == true) {
if((newElem != null) && (isNumeric(newElem) == true)) {
newElem += command.charAt(i);
} else {
newElem = String.valueOf(command.charAt(i));
}
break;
} else {
if(isNumeric(newElem) == true) {
parsedElems.add(newElem);
newElem = null;
}
}
pattern = Pattern.compile("\\+|-|\\*|/|%|&|=|<|>|~|!|#|@|\"|'|\\|");
if ((pattern.matcher(String.valueOf(command.charAt(i)))).matches() == true) {
parsedElems.add(String.valueOf(command.charAt(i)));
} else if(command.charAt(i) == '?') {
parsedElems.add(String.valueOf(command.charAt(i)));
} else if(command.charAt(i) == '\\') {
readSpecialCharacter = true;
} else {
parsedElems.add(String.valueOf(command.charAt(i))); //Printable ASCII Characters
}
break;
}
}
}
}
}
//we need this, because we could be parsing an expression such as 0, and after the 0 has been parsed,
//the loop stops without adding newElem to the list of parsed elements.
if(newElem != null) {
parsedElems.add(newElem);
}
if(numOpenBrackets > 0) {
throw new CalcParsingException("closingBracket not found");
}
//Convert the current input list of parsed element into a stack.
createStack();
}
|
diff --git a/eapli.ExpenseManager/src/Persistence/PersistenceFactory.java b/eapli.ExpenseManager/src/Persistence/PersistenceFactory.java
index 519e991..e07aec3 100644
--- a/eapli.ExpenseManager/src/Persistence/PersistenceFactory.java
+++ b/eapli.ExpenseManager/src/Persistence/PersistenceFactory.java
@@ -1,53 +1,53 @@
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package Persistence;
import java.io.FileInputStream;
import java.util.Properties;
/**
*
* @author i060752
*/
public class PersistenceFactory {
private PersistenceFactory() {
//vai ao ficheiro propriedades - expensemanager.properties- obter a
//a factory associada ao tipo de persistencia a usar.
//Por omissão JpaRepositoryFactory
try{
FileInputStream propFile = new FileInputStream("expensemanager.properties");
Properties p = new Properties(System.getProperties());
p.load(propFile);
System.setProperties(p);
} catch(Exception e) {
- System.setProperty("PERSIST", "persistence.JpaRepositoryFactory");
+ System.setProperty("PERSIST", "Persistence.JpaRepositoryFactory");
//System.setProperty("PERSIST", "persistence.InMemoryRepositoryFactory");
}
}
//LAZY LOADING – create only when needed
private static PersistenceFactory instance = null;
public static PersistenceFactory getInstance() {
if (instance == null) {
instance = new PersistenceFactory ();
}
return instance;
}
public IRepositoryFactory buildRepositoryFactory(){
String desc = System.getProperty("PERSIST");
try
{
return (IRepositoryFactory) Class.forName(desc).newInstance();
} catch(Exception ex)
{
return null;
}
}
}
| true | true | private PersistenceFactory() {
//vai ao ficheiro propriedades - expensemanager.properties- obter a
//a factory associada ao tipo de persistencia a usar.
//Por omissão JpaRepositoryFactory
try{
FileInputStream propFile = new FileInputStream("expensemanager.properties");
Properties p = new Properties(System.getProperties());
p.load(propFile);
System.setProperties(p);
} catch(Exception e) {
System.setProperty("PERSIST", "persistence.JpaRepositoryFactory");
//System.setProperty("PERSIST", "persistence.InMemoryRepositoryFactory");
}
}
| private PersistenceFactory() {
//vai ao ficheiro propriedades - expensemanager.properties- obter a
//a factory associada ao tipo de persistencia a usar.
//Por omissão JpaRepositoryFactory
try{
FileInputStream propFile = new FileInputStream("expensemanager.properties");
Properties p = new Properties(System.getProperties());
p.load(propFile);
System.setProperties(p);
} catch(Exception e) {
System.setProperty("PERSIST", "Persistence.JpaRepositoryFactory");
//System.setProperty("PERSIST", "persistence.InMemoryRepositoryFactory");
}
}
|
diff --git a/src/java/com/threerings/editor/PathProperty.java b/src/java/com/threerings/editor/PathProperty.java
index 8246f92f..b68a95ac 100644
--- a/src/java/com/threerings/editor/PathProperty.java
+++ b/src/java/com/threerings/editor/PathProperty.java
@@ -1,519 +1,519 @@
//
// $Id$
//
// Clyde library - tools for developing networked games
// Copyright (C) 2005-2010 Three Rings Design, Inc.
//
// Redistribution and use in source and binary forms, with or without modification, are permitted
// provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this list of
// conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright notice, this list of
// conditions and the following disclaimer in the documentation and/or other materials provided
// with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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.threerings.editor;
import java.lang.reflect.Array;
import java.lang.reflect.Field;
import java.lang.reflect.Member;
import java.lang.reflect.Method;
import java.lang.reflect.Type;
import java.io.IOException;
import java.io.StreamTokenizer;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.List;
import com.samskivert.util.ClassUtil;
import com.samskivert.util.StringUtil;
import com.threerings.config.ConfigManager;
import com.threerings.config.ConfigReference;
import com.threerings.config.ManagedConfig;
import com.threerings.config.Parameter;
import com.threerings.config.ParameterizedConfig;
import com.threerings.editor.util.PropertyUtil;
import static com.threerings.editor.Log.*;
/**
* A property that
*/
public class PathProperty extends Property
{
/**
* Attempts to resolve the provided path into a property chain, returning <code>null</code>
* on failure.
*/
public static Property[] createPath (ConfigManager cfgmgr, Object object, String path)
{
// create the tokenizer for the path
StreamTokenizer tok = new StreamTokenizer(new StringReader(path));
tok.ordinaryChar('/');
tok.ordinaryChar('.');
tok.ordinaryChar('\'');
tok.wordChars('_', '_');
// step through the path components
ArrayList<Property> props = new ArrayList<Property>();
try {
while (tok.nextToken() != StreamTokenizer.TT_EOF) {
if (tok.ttype != StreamTokenizer.TT_WORD) {
log.warning("Unexpected token [path=" + path + ", token=" + tok + "].");
return null;
}
Property prop = getProperty(cfgmgr, object, tok);
if (prop == null) {
return null;
}
props.add(prop);
object = prop.get(object);
}
} catch (IOException e) {
log.warning("Error parsing path [path=" + path + "].", e);
return null;
}
// do not return a zero-length array
int size = props.size();
return (size == 0) ? null : props.toArray(new Property[size]);
}
/**
* Creates a new path property.
*
* @param cfgmgr the config manager to use when resolving references.
* @param name the name of the property.
* @param reference the reference object from which we derive our property chains.
* @param paths the list of paths.
* @throws InvalidPathsException if none of the supplied paths are valid.
*/
public PathProperty (
ConfigManager cfgmgr, String name, Object reference, String... paths)
throws InvalidPathsException
{
_name = name;
// attempt to resolve each path, storing the successes
ArrayList<Property[]> list = new ArrayList<Property[]>(paths.length);
for (String path : paths) {
// the final component must be editable
Property[] props = createPath(cfgmgr, reference, path);
if (props != null && props[props.length - 1].getAnnotation() != null) {
list.add(props);
}
}
if (list.isEmpty()) {
throw new InvalidPathsException(StringUtil.toString(paths));
}
_paths = list.toArray(new Property[list.size()][]);
}
@Override // documentation inherited
public boolean shouldTranslateName ()
{
return false;
}
@Override // documentation inherited
public String getColorName ()
{
Property[] path = _paths[0];
return path[path.length - 1].getColorName();
}
@Override // documentation inherited
public Member getMember ()
{
Property[] path = _paths[0];
return path[path.length - 1].getMember();
}
@Override // documentation inherited
public Object getMemberObject (Object object)
{
Property[] path = _paths[0];
int last = path.length - 1;
for (int ii = 0; ii < last; ii++) {
object = path[ii].get(object);
}
return path[last].getMemberObject(object);
}
@Override // documentation inherited
public Class getType ()
{
Property[] path = _paths[0];
return path[path.length - 1].getType();
}
@Override // documentation inherited
public Type getGenericType ()
{
Property[] path = _paths[0];
return path[path.length - 1].getGenericType();
}
@Override // documentation inherited
public String getMode ()
{
return PropertyUtil.getMode(_paths[0]);
}
@Override // documentation inherited
public String getUnits ()
{
return PropertyUtil.getUnits(_paths[0]);
}
@Override // documentation inherited
public double getMinimum ()
{
return PropertyUtil.getMinimum(_paths[0]);
}
@Override // documentation inherited
public double getMaximum ()
{
return PropertyUtil.getMaximum(_paths[0]);
}
@Override // documentation inherited
public double getStep ()
{
return PropertyUtil.getStep(_paths[0]);
}
@Override // documentation inherited
public double getScale ()
{
return PropertyUtil.getScale(_paths[0]);
}
@Override // documentation inherited
public int getMinSize ()
{
return PropertyUtil.getMinSize(_paths[0]);
}
@Override // documentation inherited
public int getMaxSize ()
{
return PropertyUtil.getMaxSize(_paths[0]);
}
@Override // documentation inherited
public Object get (Object object)
{
for (Property property : _paths[0]) {
object = property.get(object);
}
return object;
}
@Override // documentation inherited
public void set (Object object, Object value)
{
for (int ii = 0; ii < _paths.length; ii++) {
Property[] path = _paths[ii];
Object obj = object;
int last = path.length - 1;
for (int jj = 0; jj < last; jj++) {
obj = path[jj].get(obj);
}
// use some simple coercion rules on the paths after the first
Property plast = path[last];
plast.set(obj, ii == 0 ? value : coerce(value, plast.getType()));
}
}
/**
* Attempts to find and return the named property, returning <code>null</code> on failure.
*/
protected static Property getProperty (
ConfigManager cfgmgr, Object object, StreamTokenizer tok)
throws IOException
{
if (object == null) {
return null;
}
// first token is the name of the property
String name = tok.sval;
// first search the (cached) editable properties
Class clazz = object.getClass();
Property[] props = Introspector.getProperties(clazz);
for (Property prop : props) {
if (prop.getName().equals(name)) {
return getProperty(cfgmgr, object, prop, tok);
}
}
// then look for a normal field or getter
for (Class<?> sclazz = clazz; sclazz != null; sclazz = sclazz.getSuperclass()) {
try {
Field field = sclazz.getDeclaredField(name);
field.setAccessible(true);
return getProperty(cfgmgr, object, new FieldProperty(field), tok);
} catch (NoSuchFieldException e) { }
try {
Method method = sclazz.getDeclaredMethod(name);
method.setAccessible(true);
// a slight abuse of MethodProperty: use another reference to the getter instead
// of a setter so that we don't have to check for a null setter in getAnnotation.
// the set method should never be called
return getProperty(cfgmgr, object, new MethodProperty(method, method), tok);
} catch (NoSuchMethodException e) { }
}
log.warning("Failed to find property.", "name", name, "object", object);
return null;
}
/**
* Provides additional handling for subscripts.
*/
protected static Property getProperty (
final ConfigManager cfgmgr, Object object, final Property base, StreamTokenizer tok)
throws IOException
{
if (tok.nextToken() != '[') {
return base;
}
Object value = base.get(object);
if (value == null) {
return null;
}
Property prop = null;
if (tok.nextToken() == StreamTokenizer.TT_NUMBER) {
final int idx = (int)tok.nval;
if (value instanceof List) {
if (idx >= 0 && idx < ((List)value).size()) {
prop = new IndexProperty(base, idx) {
public Object get (Object object) {
return ((List)base.get(object)).get(idx);
}
public void set (Object object, Object value) {
@SuppressWarnings("unchecked") List<Object> list =
(List<Object>)base.get(object);
list.set(idx, value);
}
};
}
} else if (value.getClass().isArray()) {
if (idx >= 0 && idx < Array.getLength(value)) {
prop = new IndexProperty(base, idx) {
public Object get (Object object) {
return Array.get(base.get(object), idx);
}
public void set (Object object, Object value) {
Array.set(base.get(object), idx, value);
}
};
}
}
} else if (tok.ttype == '"' && value instanceof ConfigReference) {
final String arg = tok.sval;
final @SuppressWarnings("unchecked") Class<ManagedConfig> clazz =
(Class<ManagedConfig>)base.getArgumentType(ConfigReference.class);
if (clazz == null) {
log.warning("Couldn't determine config reference type.", "ref", value);
return null;
}
@SuppressWarnings("unchecked") ConfigReference<ManagedConfig> ref =
(ConfigReference<ManagedConfig>)value;
if (cfgmgr == null) {
log.warning("No config manager available.", "ref", value);
return null;
}
- ManagedConfig config = cfgmgr.getConfig(clazz, ref);
+ ManagedConfig config = (ref == null) ? null : cfgmgr.getConfig(clazz, ref.getName());
if (!(config instanceof ParameterizedConfig)) {
return null;
}
ParameterizedConfig pconfig = (ParameterizedConfig)config;
Parameter parameter = pconfig.getParameter(arg);
if (parameter == null) {
return null;
}
final Property aprop = parameter.getArgumentProperty(pconfig);
if (aprop == null) {
return null;
}
prop = new Property () { {
_name = base.getName() + "[\"" + arg.replace("\"", "\\\"") + "\"]";
}
public Member getMember () {
return aprop.getMember();
}
public Object getMemberObject (Object object) {
ConfigReference<ManagedConfig> ref = getReference(object);
Property prop = getArgumentProperty(ref);
return (prop == null) ? null : prop.getMemberObject(ref.getArguments());
}
public Class getType () {
return aprop.getType();
}
public Type getGenericType () {
return aprop.getGenericType();
}
public Object get (Object object) {
ConfigReference<ManagedConfig> ref = getReference(object);
Property prop = getArgumentProperty(ref);
return (prop == null) ? null : prop.get(ref.getArguments());
}
public void set (Object object, Object value) {
ConfigReference<ManagedConfig> ref = getReference(object);
Property prop = getArgumentProperty(ref);
if (prop != null) {
prop.set(ref.getArguments(), value);
}
}
@SuppressWarnings("unchecked")
protected ConfigReference<ManagedConfig> getReference (Object object) {
return (ConfigReference<ManagedConfig>)base.get(object);
}
protected Property getArgumentProperty (ConfigReference<ManagedConfig> ref) {
ManagedConfig config = (ref == null) ?
null : cfgmgr.getConfig(clazz, ref.getName());
if (!(config instanceof ParameterizedConfig)) {
return null;
}
ParameterizedConfig pconfig = (ParameterizedConfig)config;
Parameter parameter = pconfig.getParameter(arg);
if (parameter == null) {
return null;
}
return parameter.getArgumentProperty(pconfig);
}
};
}
if (tok.nextToken() != ']') {
log.warning("Missing matching bracket [token=" + tok + "].");
return null;
}
return (prop == null) ? null : getProperty(cfgmgr, object, prop, tok);
}
/**
* Coerces the supplied value to the given type.
*/
protected static Object coerce (Object value, Class type)
{
if (type.isPrimitive()) {
type = ClassUtil.objectEquivalentOf(type);
}
if (value == null || type.isInstance(value)) {
return value;
} else if (value instanceof String) {
if (type == Byte.class) {
try {
return Byte.valueOf((String)value);
} catch (NumberFormatException e) {
return Byte.valueOf((byte)0);
}
} else if (type == Double.class) {
try {
return Double.valueOf((String)value);
} catch (NumberFormatException e) {
return Double.valueOf(0.0);
}
} else if (type == Float.class) {
try {
return Float.valueOf((String)value);
} catch (NumberFormatException e) {
return Float.valueOf(0f);
}
} else if (type == Integer.class) {
try {
return Integer.valueOf((String)value);
} catch (NumberFormatException e) {
return Integer.valueOf(0);
}
} else if (type == Long.class) {
try {
return Long.valueOf((String)value);
} catch (NumberFormatException e) {
return Long.valueOf(0L);
}
} else if (type == Short.class) {
try {
return Short.valueOf((String)value);
} catch (NumberFormatException e) {
return Short.valueOf((short)0);
}
}
} else if (value instanceof Number) {
if (type == Byte.class) {
return ((Number)value).byteValue();
} else if (type == Double.class) {
return ((Number)value).doubleValue();
} else if (type == Float.class) {
return ((Number)value).floatValue();
} else if (type == Integer.class) {
return ((Number)value).intValue();
} else if (type == Long.class) {
return ((Number)value).longValue();
} else if (type == Short.class) {
return ((Number)value).shortValue();
} else if (type == String.class) {
return value.toString();
}
}
throw new IllegalArgumentException("Can't coerce " + value + " to " + type);
}
/**
* Superclass for properties addressing components of other properties.
*/
protected static abstract class IndexProperty extends Property
{
public IndexProperty (Property base, int idx)
{
_name = (_base = base).getName() + "[" + idx + "]";
}
@Override // documentation inherited
public boolean shouldTranslateName ()
{
return false;
}
@Override // documentation inherited
public Member getMember ()
{
return _base.getMember();
}
@Override // documentation inherited
public Class getType ()
{
return _base.getComponentType();
}
@Override // documentation inherited
public Type getGenericType ()
{
return _base.getGenericComponentType();
}
/** The base property. */
protected Property _base;
}
/** The property chains for each path. */
protected Property[][] _paths;
}
| true | true | protected static Property getProperty (
final ConfigManager cfgmgr, Object object, final Property base, StreamTokenizer tok)
throws IOException
{
if (tok.nextToken() != '[') {
return base;
}
Object value = base.get(object);
if (value == null) {
return null;
}
Property prop = null;
if (tok.nextToken() == StreamTokenizer.TT_NUMBER) {
final int idx = (int)tok.nval;
if (value instanceof List) {
if (idx >= 0 && idx < ((List)value).size()) {
prop = new IndexProperty(base, idx) {
public Object get (Object object) {
return ((List)base.get(object)).get(idx);
}
public void set (Object object, Object value) {
@SuppressWarnings("unchecked") List<Object> list =
(List<Object>)base.get(object);
list.set(idx, value);
}
};
}
} else if (value.getClass().isArray()) {
if (idx >= 0 && idx < Array.getLength(value)) {
prop = new IndexProperty(base, idx) {
public Object get (Object object) {
return Array.get(base.get(object), idx);
}
public void set (Object object, Object value) {
Array.set(base.get(object), idx, value);
}
};
}
}
} else if (tok.ttype == '"' && value instanceof ConfigReference) {
final String arg = tok.sval;
final @SuppressWarnings("unchecked") Class<ManagedConfig> clazz =
(Class<ManagedConfig>)base.getArgumentType(ConfigReference.class);
if (clazz == null) {
log.warning("Couldn't determine config reference type.", "ref", value);
return null;
}
@SuppressWarnings("unchecked") ConfigReference<ManagedConfig> ref =
(ConfigReference<ManagedConfig>)value;
if (cfgmgr == null) {
log.warning("No config manager available.", "ref", value);
return null;
}
ManagedConfig config = cfgmgr.getConfig(clazz, ref);
if (!(config instanceof ParameterizedConfig)) {
return null;
}
ParameterizedConfig pconfig = (ParameterizedConfig)config;
Parameter parameter = pconfig.getParameter(arg);
if (parameter == null) {
return null;
}
final Property aprop = parameter.getArgumentProperty(pconfig);
if (aprop == null) {
return null;
}
prop = new Property () { {
_name = base.getName() + "[\"" + arg.replace("\"", "\\\"") + "\"]";
}
public Member getMember () {
return aprop.getMember();
}
public Object getMemberObject (Object object) {
ConfigReference<ManagedConfig> ref = getReference(object);
Property prop = getArgumentProperty(ref);
return (prop == null) ? null : prop.getMemberObject(ref.getArguments());
}
public Class getType () {
return aprop.getType();
}
public Type getGenericType () {
return aprop.getGenericType();
}
public Object get (Object object) {
ConfigReference<ManagedConfig> ref = getReference(object);
Property prop = getArgumentProperty(ref);
return (prop == null) ? null : prop.get(ref.getArguments());
}
public void set (Object object, Object value) {
ConfigReference<ManagedConfig> ref = getReference(object);
Property prop = getArgumentProperty(ref);
if (prop != null) {
prop.set(ref.getArguments(), value);
}
}
@SuppressWarnings("unchecked")
protected ConfigReference<ManagedConfig> getReference (Object object) {
return (ConfigReference<ManagedConfig>)base.get(object);
}
protected Property getArgumentProperty (ConfigReference<ManagedConfig> ref) {
ManagedConfig config = (ref == null) ?
null : cfgmgr.getConfig(clazz, ref.getName());
if (!(config instanceof ParameterizedConfig)) {
return null;
}
ParameterizedConfig pconfig = (ParameterizedConfig)config;
Parameter parameter = pconfig.getParameter(arg);
if (parameter == null) {
return null;
}
return parameter.getArgumentProperty(pconfig);
}
};
}
if (tok.nextToken() != ']') {
log.warning("Missing matching bracket [token=" + tok + "].");
return null;
}
return (prop == null) ? null : getProperty(cfgmgr, object, prop, tok);
}
| protected static Property getProperty (
final ConfigManager cfgmgr, Object object, final Property base, StreamTokenizer tok)
throws IOException
{
if (tok.nextToken() != '[') {
return base;
}
Object value = base.get(object);
if (value == null) {
return null;
}
Property prop = null;
if (tok.nextToken() == StreamTokenizer.TT_NUMBER) {
final int idx = (int)tok.nval;
if (value instanceof List) {
if (idx >= 0 && idx < ((List)value).size()) {
prop = new IndexProperty(base, idx) {
public Object get (Object object) {
return ((List)base.get(object)).get(idx);
}
public void set (Object object, Object value) {
@SuppressWarnings("unchecked") List<Object> list =
(List<Object>)base.get(object);
list.set(idx, value);
}
};
}
} else if (value.getClass().isArray()) {
if (idx >= 0 && idx < Array.getLength(value)) {
prop = new IndexProperty(base, idx) {
public Object get (Object object) {
return Array.get(base.get(object), idx);
}
public void set (Object object, Object value) {
Array.set(base.get(object), idx, value);
}
};
}
}
} else if (tok.ttype == '"' && value instanceof ConfigReference) {
final String arg = tok.sval;
final @SuppressWarnings("unchecked") Class<ManagedConfig> clazz =
(Class<ManagedConfig>)base.getArgumentType(ConfigReference.class);
if (clazz == null) {
log.warning("Couldn't determine config reference type.", "ref", value);
return null;
}
@SuppressWarnings("unchecked") ConfigReference<ManagedConfig> ref =
(ConfigReference<ManagedConfig>)value;
if (cfgmgr == null) {
log.warning("No config manager available.", "ref", value);
return null;
}
ManagedConfig config = (ref == null) ? null : cfgmgr.getConfig(clazz, ref.getName());
if (!(config instanceof ParameterizedConfig)) {
return null;
}
ParameterizedConfig pconfig = (ParameterizedConfig)config;
Parameter parameter = pconfig.getParameter(arg);
if (parameter == null) {
return null;
}
final Property aprop = parameter.getArgumentProperty(pconfig);
if (aprop == null) {
return null;
}
prop = new Property () { {
_name = base.getName() + "[\"" + arg.replace("\"", "\\\"") + "\"]";
}
public Member getMember () {
return aprop.getMember();
}
public Object getMemberObject (Object object) {
ConfigReference<ManagedConfig> ref = getReference(object);
Property prop = getArgumentProperty(ref);
return (prop == null) ? null : prop.getMemberObject(ref.getArguments());
}
public Class getType () {
return aprop.getType();
}
public Type getGenericType () {
return aprop.getGenericType();
}
public Object get (Object object) {
ConfigReference<ManagedConfig> ref = getReference(object);
Property prop = getArgumentProperty(ref);
return (prop == null) ? null : prop.get(ref.getArguments());
}
public void set (Object object, Object value) {
ConfigReference<ManagedConfig> ref = getReference(object);
Property prop = getArgumentProperty(ref);
if (prop != null) {
prop.set(ref.getArguments(), value);
}
}
@SuppressWarnings("unchecked")
protected ConfigReference<ManagedConfig> getReference (Object object) {
return (ConfigReference<ManagedConfig>)base.get(object);
}
protected Property getArgumentProperty (ConfigReference<ManagedConfig> ref) {
ManagedConfig config = (ref == null) ?
null : cfgmgr.getConfig(clazz, ref.getName());
if (!(config instanceof ParameterizedConfig)) {
return null;
}
ParameterizedConfig pconfig = (ParameterizedConfig)config;
Parameter parameter = pconfig.getParameter(arg);
if (parameter == null) {
return null;
}
return parameter.getArgumentProperty(pconfig);
}
};
}
if (tok.nextToken() != ']') {
log.warning("Missing matching bracket [token=" + tok + "].");
return null;
}
return (prop == null) ? null : getProperty(cfgmgr, object, prop, tok);
}
|
diff --git a/addon-jpa/src/main/java/org/springframework/roo/addon/jpa/JpaOperationsImpl.java b/addon-jpa/src/main/java/org/springframework/roo/addon/jpa/JpaOperationsImpl.java
index 09ce2588a..1a01d3b24 100644
--- a/addon-jpa/src/main/java/org/springframework/roo/addon/jpa/JpaOperationsImpl.java
+++ b/addon-jpa/src/main/java/org/springframework/roo/addon/jpa/JpaOperationsImpl.java
@@ -1,814 +1,814 @@
package org.springframework.roo.addon.jpa;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.List;
import java.util.Properties;
import java.util.SortedSet;
import java.util.TreeSet;
import java.util.logging.Logger;
import javax.xml.parsers.DocumentBuilder;
import org.apache.felix.scr.annotations.Component;
import org.apache.felix.scr.annotations.Reference;
import org.apache.felix.scr.annotations.Service;
import org.springframework.roo.addon.propfiles.PropFileOperations;
import org.springframework.roo.file.monitor.event.FileDetails;
import org.springframework.roo.metadata.MetadataService;
import org.springframework.roo.process.manager.FileManager;
import org.springframework.roo.process.manager.MutableFile;
import org.springframework.roo.project.Dependency;
import org.springframework.roo.project.Filter;
import org.springframework.roo.project.Path;
import org.springframework.roo.project.PathResolver;
import org.springframework.roo.project.Plugin;
import org.springframework.roo.project.ProjectMetadata;
import org.springframework.roo.project.ProjectOperations;
import org.springframework.roo.project.Property;
import org.springframework.roo.project.Repository;
import org.springframework.roo.project.Resource;
import org.springframework.roo.support.logging.HandlerUtils;
import org.springframework.roo.support.util.Assert;
import org.springframework.roo.support.util.FileCopyUtils;
import org.springframework.roo.support.util.StringUtils;
import org.springframework.roo.support.util.TemplateUtils;
import org.springframework.roo.support.util.XmlUtils;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
/**
* Provides JPA configuration operations.
*
* @author Stefan Schmidt
* @author Alan Stewart
* @since 1.0
*/
@Component
@Service
public class JpaOperationsImpl implements JpaOperations {
private static final Logger logger = HandlerUtils.getLogger(JpaOperationsImpl.class);
private static final String GAE_PERSISTENCE_UNIT_NAME = "transactions-optional";
private static final String PERSISTENCE_UNIT_NAME = "persistenceUnit";
@Reference private FileManager fileManager;
@Reference private PathResolver pathResolver;
@Reference private MetadataService metadataService;
@Reference private ProjectOperations projectOperations;
@Reference private PropFileOperations propFileOperations;
public boolean isJpaInstallationPossible() {
return metadataService.get(ProjectMetadata.getProjectIdentifier()) != null && !fileManager.exists(pathResolver.getIdentifier(Path.SRC_MAIN_RESOURCES, "META-INF/persistence.xml"));
}
public boolean isJpaInstalled() {
return metadataService.get(ProjectMetadata.getProjectIdentifier()) != null && fileManager.exists(pathResolver.getIdentifier(Path.SRC_MAIN_RESOURCES, "META-INF/persistence.xml"));
}
public boolean hasDatabaseProperties() {
return fileManager.exists(getDatabasePropertiesPath());
}
public SortedSet<String> getDatabaseProperties() {
if (fileManager.exists(getDatabasePropertiesPath())) {
return propFileOperations.getPropertyKeys(Path.SPRING_CONFIG_ROOT, "database.properties", true);
} else {
return getPropertiesFromDataNucleusConfiguration();
}
}
private String getDatabasePropertiesPath() {
return pathResolver.getIdentifier(Path.SPRING_CONFIG_ROOT, "database.properties");
}
public void configureJpa(OrmProvider ormProvider, JdbcDatabase database, String jndi, String applicationId, String databaseName, String userName, String password, String persistenceUnit) {
Assert.notNull(ormProvider, "ORM provider required");
Assert.notNull(database, "JDBC database required");
// Parse the configuration.xml file
Element configuration = XmlUtils.getConfiguration(getClass());
// Remove unnecessary artifacts not specific to current database and JPA provider
cleanup(configuration, ormProvider, database);
updateApplicationContext(ormProvider, database, jndi);
updatePersistenceXml(ormProvider, database, databaseName, userName, password, persistenceUnit);
updateGaeXml(ormProvider, database, applicationId);
updateVMforceConfigProperties(ormProvider, database, userName, password);
if (!StringUtils.hasText(jndi)) {
updateDatabaseProperties(ormProvider, database, databaseName, userName, password);
}
updateLog4j(ormProvider);
updatePomProperties(configuration, ormProvider, database);
updateDependencies(configuration, ormProvider, database);
updateRepositories(configuration, ormProvider, database);
updatePluginRepositories(configuration, ormProvider, database);
updateFilters(configuration, ormProvider, database);
updateResources(configuration, ormProvider, database);
updateBuildPlugins(configuration, ormProvider, database);
}
private void updateApplicationContext(OrmProvider ormProvider, JdbcDatabase database, String jndi) {
String contextPath = pathResolver.getIdentifier(Path.SPRING_CONFIG_ROOT, "applicationContext.xml");
MutableFile contextMutableFile = null;
Document appCtx;
try {
if (fileManager.exists(contextPath)) {
contextMutableFile = fileManager.updateFile(contextPath);
appCtx = XmlUtils.getDocumentBuilder().parse(contextMutableFile.getInputStream());
} else {
throw new IllegalStateException("Could not acquire applicationContext.xml in " + contextPath);
}
} catch (Exception e) {
throw new IllegalStateException(e);
}
Element root = appCtx.getDocumentElement();
// Checking for existence of configurations, if found abort
Element dataSource = XmlUtils.findFirstElement("/beans/bean[@id = 'dataSource']", root);
Element dataSourceJndi = XmlUtils.findFirstElement("/beans/jndi-lookup[@id = 'dataSource']", root);
if (ormProvider == OrmProvider.DATANUCLEUS || ormProvider == OrmProvider.DATANUCLEUS_2) {
if (dataSource != null) {
root.removeChild(dataSource);
}
if (dataSourceJndi != null) {
root.removeChild(dataSourceJndi);
}
} else if (!StringUtils.hasText(jndi) && dataSource == null) {
dataSource = appCtx.createElement("bean");
dataSource.setAttribute("class", "org.apache.commons.dbcp.BasicDataSource");
dataSource.setAttribute("destroy-method", "close");
dataSource.setAttribute("id", "dataSource");
dataSource.appendChild(createPropertyElement("driverClassName", "${database.driverClassName}", appCtx));
dataSource.appendChild(createPropertyElement("url", "${database.url}", appCtx));
dataSource.appendChild(createPropertyElement("username", "${database.username}", appCtx));
dataSource.appendChild(createPropertyElement("password", "${database.password}", appCtx));
root.appendChild(dataSource);
if (dataSourceJndi != null) {
dataSourceJndi.getParentNode().removeChild(dataSourceJndi);
}
} else if (StringUtils.hasText(jndi)) {
if (dataSourceJndi == null) {
dataSourceJndi = appCtx.createElement("jee:jndi-lookup");
dataSourceJndi.setAttribute("id", "dataSource");
root.appendChild(dataSourceJndi);
}
dataSourceJndi.setAttribute("jndi-name", jndi);
if (dataSource != null) {
dataSource.getParentNode().removeChild(dataSource);
}
}
if (dataSource != null) {
Element validationQueryElement = XmlUtils.findFirstElement("property[@name = 'validationQuery']", dataSource);
Element testOnBorrowElement = XmlUtils.findFirstElement("property[@name = 'testOnBorrow']", dataSource);
if (database != JdbcDatabase.MYSQL && validationQueryElement != null && testOnBorrowElement != null) {
dataSource.removeChild(validationQueryElement);
dataSource.removeChild(testOnBorrowElement);
} else if (database == JdbcDatabase.MYSQL && validationQueryElement == null && testOnBorrowElement == null) {
dataSource.appendChild(createPropertyElement("validationQuery", "SELECT 1 FROM DUAL", appCtx));
dataSource.appendChild(createPropertyElement("testOnBorrow", "true", appCtx));
}
}
Element transactionManager = XmlUtils.findFirstElement("/beans/bean[@id = 'transactionManager']", root);
if (transactionManager == null) {
transactionManager = appCtx.createElement("bean");
transactionManager.setAttribute("id", "transactionManager");
transactionManager.setAttribute("class", "org.springframework.orm.jpa.JpaTransactionManager");
transactionManager.appendChild(createRefElement("entityManagerFactory", "entityManagerFactory", appCtx));
root.appendChild(transactionManager);
}
Element aspectJTxManager = XmlUtils.findFirstElement("/beans/annotation-driven", root);
if (aspectJTxManager == null) {
aspectJTxManager = appCtx.createElement("tx:annotation-driven");
aspectJTxManager.setAttribute("mode", "aspectj");
aspectJTxManager.setAttribute("transaction-manager", "transactionManager");
root.appendChild(aspectJTxManager);
}
Element entityManagerFactory = XmlUtils.findFirstElement("/beans/bean[@id = 'entityManagerFactory']", root);
if (entityManagerFactory != null) {
root.removeChild(entityManagerFactory);
}
entityManagerFactory = appCtx.createElement("bean");
entityManagerFactory.setAttribute("id", "entityManagerFactory");
if (database == JdbcDatabase.GOOGLE_APP_ENGINE) {
entityManagerFactory.setAttribute("class", "org.springframework.orm.jpa.LocalEntityManagerFactoryBean");
entityManagerFactory.appendChild(createPropertyElement("persistenceUnitName", GAE_PERSISTENCE_UNIT_NAME, appCtx));
} else {
entityManagerFactory.setAttribute("class", "org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean");
if (ormProvider == OrmProvider.DATANUCLEUS || ormProvider == OrmProvider.DATANUCLEUS_2) {
entityManagerFactory.appendChild(createPropertyElement("persistenceUnitName", PERSISTENCE_UNIT_NAME, appCtx));
} else {
entityManagerFactory.appendChild(createRefElement("dataSource", "dataSource", appCtx));
}
}
root.appendChild(entityManagerFactory);
XmlUtils.removeTextNodes(root);
XmlUtils.writeXml(contextMutableFile.getOutputStream(), appCtx);
}
private void updatePersistenceXml(OrmProvider ormProvider, JdbcDatabase database, String databaseName, String userName, String password, String persistenceUnit) {
String persistencePath = pathResolver.getIdentifier(Path.SRC_MAIN_RESOURCES, "META-INF/persistence.xml");
MutableFile persistenceMutableFile = null;
Document persistence;
try {
if (fileManager.exists(persistencePath)) {
persistenceMutableFile = fileManager.updateFile(persistencePath);
persistence = XmlUtils.getDocumentBuilder().parse(persistenceMutableFile.getInputStream());
} else {
persistenceMutableFile = fileManager.createFile(persistencePath);
InputStream templateInputStream = TemplateUtils.getTemplate(getClass(), "persistence-template.xml");
Assert.notNull(templateInputStream, "Could not acquire peristence.xml template");
persistence = XmlUtils.getDocumentBuilder().parse(templateInputStream);
}
} catch (Exception e) {
throw new IllegalStateException(e);
}
Properties dialects = new Properties();
try {
InputStream dialectsInputStream = TemplateUtils.getTemplate(getClass(), "jpa-dialects.properties");
Assert.notNull(dialectsInputStream, "Could not acquire jpa-dialects.properties");
dialects.load(dialectsInputStream);
} catch (Exception e) {
throw new IllegalStateException(e);
}
Element root = persistence.getDocumentElement();
Element persistenceElement = XmlUtils.findFirstElement("/persistence", root);
Assert.notNull(persistenceElement, "No persistence element found");
Element persistenceUnitElement;
if (StringUtils.hasText(persistenceUnit)) {
persistenceUnitElement = XmlUtils.findFirstElement("persistence-unit[@name = '" + persistenceUnit + "']", persistenceElement);
if (persistenceUnitElement == null) {
persistenceUnitElement = persistence.createElement("persistence-unit");
persistenceElement.appendChild(persistenceUnitElement);
}
} else {
persistenceUnitElement = XmlUtils.findFirstElement("persistence-unit[@name = '" + (database == JdbcDatabase.GOOGLE_APP_ENGINE ? GAE_PERSISTENCE_UNIT_NAME : PERSISTENCE_UNIT_NAME) + "']", persistenceElement);
if (persistenceUnitElement == null) {
persistenceUnitElement = XmlUtils.findFirstElement("persistence-unit", persistenceElement);
}
}
Assert.notNull(persistenceUnitElement, "No persistence-unit elements found");
while (persistenceUnitElement.getFirstChild() != null) {
persistenceUnitElement.removeChild(persistenceUnitElement.getFirstChild());
}
// Set attributes for DataNuclueus 1.1.x/GAE-specific requirements
switch (ormProvider) {
case DATANUCLEUS:
persistenceElement.setAttribute("version", "1.0");
persistenceElement.setAttribute("xsi:schemaLocation", "http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd");
break;
default:
persistenceElement.setAttribute("version", "2.0");
persistenceElement.setAttribute("xsi:schemaLocation", "http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd");
break;
}
// Add provider element
Element provider = persistence.createElement("provider");
switch (database) {
case GOOGLE_APP_ENGINE:
persistenceUnitElement.setAttribute("name", GAE_PERSISTENCE_UNIT_NAME);
persistenceUnitElement.removeAttribute("transaction-type");
provider.setTextContent(ormProvider.getAlternateAdapter());
break;
case VMFORCE:
- persistenceUnitElement.setAttribute("name", "PERSISTENCE_UNIT_NAME");
+ persistenceUnitElement.setAttribute("name", PERSISTENCE_UNIT_NAME);
persistenceUnitElement.removeAttribute("transaction-type");
provider.setTextContent(ormProvider.getAdapter());
break;
default:
persistenceUnitElement.setAttribute("name", (StringUtils.hasText(persistenceUnit) ? persistenceUnit : PERSISTENCE_UNIT_NAME));
persistenceUnitElement.setAttribute("transaction-type", "RESOURCE_LOCAL");
provider.setTextContent(ormProvider.getAdapter());
break;
}
persistenceUnitElement.appendChild(provider);
// Add properties
Element properties = persistence.createElement("properties");
switch (ormProvider) {
case HIBERNATE:
properties.appendChild(createPropertyElement("hibernate.dialect", dialects.getProperty(ormProvider.name() + "." + database.name()), persistence));
properties.appendChild(persistence.createComment("value='create' to build a new database on each run; value='update' to modify an existing database; value='create-drop' means the same as 'create' but also drops tables when Hibernate closes; value='validate' makes no changes to the database")); // ROO-627
String hbm2dll = "create";
if (database == JdbcDatabase.DB2400) {
hbm2dll = "validate";
}
properties.appendChild(createPropertyElement("hibernate.hbm2ddl.auto", hbm2dll, persistence));
properties.appendChild(createPropertyElement("hibernate.ejb.naming_strategy", "org.hibernate.cfg.ImprovedNamingStrategy", persistence));
break;
case OPENJPA:
properties.appendChild(createPropertyElement("openjpa.jdbc.DBDictionary", dialects.getProperty(ormProvider.name() + "." + database.name()), persistence));
properties.appendChild(persistence.createComment("value='buildSchema' to runtime forward map the DDL SQL; value='validate' makes no changes to the database")); // ROO-627
properties.appendChild(createPropertyElement("openjpa.jdbc.SynchronizeMappings", "buildSchema", persistence));
properties.appendChild(createPropertyElement("openjpa.RuntimeUnenhancedClasses", "supported", persistence));
break;
case ECLIPSELINK:
properties.appendChild(createPropertyElement("eclipselink.target-database", dialects.getProperty(ormProvider.name() + "." + database.name()), persistence));
properties.appendChild(persistence.createComment("value='drop-and-create-tables' to build a new database on each run; value='create-tables' creates new tables if needed; value='none' makes no changes to the database")); // ROO-627
properties.appendChild(createPropertyElement("eclipselink.ddl-generation", "drop-and-create-tables", persistence));
properties.appendChild(createPropertyElement("eclipselink.ddl-generation.output-mode", "database", persistence));
properties.appendChild(createPropertyElement("eclipselink.weaving", "static", persistence));
break;
case DATANUCLEUS:
case DATANUCLEUS_2:
String connectionString = database.getConnectionString();
switch (database) {
case GOOGLE_APP_ENGINE:
properties.appendChild(createPropertyElement("datanucleus.NontransactionalRead", "true", persistence));
properties.appendChild(createPropertyElement("datanucleus.NontransactionalWrite", "true", persistence));
break;
case VMFORCE:
userName = "${sfdc.userName}";
password = "${sfdc.password}";
properties.appendChild(createPropertyElement("datanucleus.Optimistic", "false", persistence));
properties.appendChild(createPropertyElement("datanucleus.datastoreTransactionDelayOperations", "true", persistence));
properties.appendChild(createPropertyElement("sfdcConnectionName", "DefaultSFDCConnection", persistence));
break;
default:
properties.appendChild(createPropertyElement("datanucleus.ConnectionDriverName", database.getDriverClassName(), persistence));
ProjectMetadata projectMetadata = (ProjectMetadata) metadataService.get(ProjectMetadata.getProjectIdentifier());
connectionString = connectionString.replace("TO_BE_CHANGED_BY_ADDON", projectMetadata.getProjectName());
switch (database) {
case HYPERSONIC_IN_MEMORY:
case HYPERSONIC_PERSISTENT:
case H2_IN_MEMORY:
userName = StringUtils.hasText(userName) ? userName : "sa";
break;
case DERBY:
break;
default:
logger.warning("Please enter your database details in src/main/resources/META-INF/persistence.xml.");
break;
}
properties.appendChild(createPropertyElement("datanucleus.storeManagerType", "rdbms", persistence));
}
properties.appendChild(createPropertyElement("datanucleus.ConnectionURL", connectionString, persistence));
properties.appendChild(createPropertyElement("datanucleus.ConnectionUserName", userName, persistence));
properties.appendChild(createPropertyElement("datanucleus.ConnectionPassword", password, persistence));
properties.appendChild(createPropertyElement("datanucleus.autoCreateSchema", "false", persistence));
properties.appendChild(createPropertyElement("datanucleus.autoCreateTables", "true", persistence));
properties.appendChild(createPropertyElement("datanucleus.autoCreateColumns", "false", persistence));
properties.appendChild(createPropertyElement("datanucleus.autoCreateConstraints", "false", persistence));
properties.appendChild(createPropertyElement("datanucleus.validateTables", "false", persistence));
properties.appendChild(createPropertyElement("datanucleus.validateConstraints", "false", persistence));
properties.appendChild(createPropertyElement("datanucleus.jpa.addClassTransformer", "false", persistence));
break;
}
persistenceUnitElement.appendChild(properties);
XmlUtils.writeXml(persistenceMutableFile.getOutputStream(), persistence);
}
private void updateGaeXml(OrmProvider ormProvider, JdbcDatabase database, String applicationId) {
String appenginePath = pathResolver.getIdentifier(Path.SRC_MAIN_WEBAPP, "WEB-INF/appengine-web.xml");
boolean appenginePathExists = fileManager.exists(appenginePath);
String loggingPropertiesPath = pathResolver.getIdentifier(Path.SRC_MAIN_WEBAPP, "WEB-INF/logging.properties");
boolean loggingPropertiesPathExists = fileManager.exists(loggingPropertiesPath);
if (database != JdbcDatabase.GOOGLE_APP_ENGINE) {
if (appenginePathExists) {
fileManager.delete(appenginePath);
}
if (loggingPropertiesPathExists) {
fileManager.delete(loggingPropertiesPath);
}
return;
} else {
MutableFile appengineMutableFile = null;
Document appengine;
try {
if (appenginePathExists) {
appengineMutableFile = fileManager.updateFile(appenginePath);
appengine = XmlUtils.getDocumentBuilder().parse(appengineMutableFile.getInputStream());
} else {
appengineMutableFile = fileManager.createFile(appenginePath);
InputStream templateInputStream = TemplateUtils.getTemplate(getClass(), "appengine-web-template.xml");
Assert.notNull(templateInputStream, "Could not acquire appengine-web.xml template");
appengine = XmlUtils.getDocumentBuilder().parse(templateInputStream);
}
} catch (Exception e) {
throw new IllegalStateException(e);
}
Element rootElement = appengine.getDocumentElement();
Element applicationElement = XmlUtils.findFirstElement("/appengine-web-app/application", rootElement);
applicationElement.setTextContent(StringUtils.hasText(applicationId) ? applicationId : getProjectName());
XmlUtils.writeXml(appengineMutableFile.getOutputStream(), appengine);
if (!loggingPropertiesPathExists) {
try {
InputStream templateInputStream = TemplateUtils.getTemplate(getClass(), "logging.properties");
FileCopyUtils.copy(templateInputStream, fileManager.createFile(loggingPropertiesPath).getOutputStream());
} catch (IOException e) {
throw new IllegalStateException(e);
}
}
}
}
private void updateDatabaseProperties(OrmProvider ormProvider, JdbcDatabase database, String databaseName, String userName, String password) {
String databasePath = getDatabasePropertiesPath();
boolean databaseExists = fileManager.exists(databasePath);
if (ormProvider == OrmProvider.DATANUCLEUS || ormProvider == OrmProvider.DATANUCLEUS_2) {
if (databaseExists) {
fileManager.delete(databasePath);
}
return;
}
MutableFile databaseMutableFile = null;
Properties props = new Properties();
try {
if (databaseExists) {
databaseMutableFile = fileManager.updateFile(databasePath);
props.load(databaseMutableFile.getInputStream());
} else {
databaseMutableFile = fileManager.createFile(databasePath);
InputStream templateInputStream = TemplateUtils.getTemplate(getClass(), "database-template.properties");
Assert.notNull(templateInputStream, "Could not acquire database properties template");
props.load(templateInputStream);
}
} catch (IOException ioe) {
throw new IllegalStateException(ioe);
}
props.put("database.driverClassName", database.getDriverClassName());
ProjectMetadata projectMetadata = (ProjectMetadata) metadataService.get(ProjectMetadata.getProjectIdentifier());
String connectionString = database.getConnectionString();
connectionString = connectionString.replace("TO_BE_CHANGED_BY_ADDON", projectMetadata.getProjectName());
if (StringUtils.hasText(databaseName)) {
// Oracle uses a different connection URL - see ROO-1203
String dbDelimiter = database == JdbcDatabase.ORACLE ? ":" : "/";
connectionString += databaseName.startsWith(dbDelimiter) ? databaseName : dbDelimiter + databaseName;
}
props.put("database.url", connectionString);
String dbPropsMsg = "Please enter your database details in src/main/resources/META-INF/spring/database.properties.";
switch (database) {
case HYPERSONIC_IN_MEMORY:
case HYPERSONIC_PERSISTENT:
case H2_IN_MEMORY:
userName = StringUtils.hasText(userName) ? userName : "sa";
break;
case DERBY:
break;
case SYBASE:
userName = StringUtils.hasText(userName) ? userName : "sa";
logger.warning(dbPropsMsg);
break;
default:
logger.warning(dbPropsMsg);
break;
}
props.put("database.username", StringUtils.trimToEmpty(userName));
props.put("database.password", StringUtils.trimToEmpty(password));
try {
props.store(databaseMutableFile.getOutputStream(), "Updated at " + new Date());
} catch (IOException ioe) {
throw new IllegalStateException(ioe);
}
}
private void updateVMforceConfigProperties(OrmProvider ormProvider, JdbcDatabase database, String userName, String password) {
String configPath = pathResolver.getIdentifier(Path.SRC_MAIN_RESOURCES, "config.properties");
boolean configExists = fileManager.exists(configPath);
if (database != JdbcDatabase.VMFORCE) {
if (configExists) {
fileManager.delete(configPath);
}
return;
}
MutableFile configMutableFile = null;
Properties props = new Properties();
try {
if (configExists) {
configMutableFile = fileManager.updateFile(configPath);
props.load(configMutableFile.getInputStream());
} else {
configMutableFile = fileManager.createFile(configPath);
InputStream templateInputStream = TemplateUtils.getTemplate(getClass(), "config-template.properties");
Assert.notNull(templateInputStream, "Could not acquire config properties template");
props.load(templateInputStream);
}
} catch (IOException ioe) {
throw new IllegalStateException(ioe);
}
props.put("sfdc.userName", StringUtils.trimToEmpty(userName));
props.put("sfdc.password", StringUtils.trimToEmpty(password));
try {
props.store(configMutableFile.getOutputStream(), "Updated at " + new Date());
} catch (IOException ioe) {
throw new IllegalStateException(ioe);
}
}
private void updateLog4j(OrmProvider ormProvider) {
try {
String log4jPath = pathResolver.getIdentifier(Path.SRC_MAIN_RESOURCES, "log4j.properties");
if (fileManager.exists(log4jPath)) {
MutableFile log4jMutableFile = fileManager.updateFile(log4jPath);
Properties props = new Properties();
props.load(log4jMutableFile.getInputStream());
final String dnKey = "log4j.category.DataNucleus";
if (ormProvider == OrmProvider.DATANUCLEUS && !props.containsKey(dnKey)) {
props.put(dnKey, "WARN");
props.store(log4jMutableFile.getOutputStream(), "Updated at " + new Date());
} else if (ormProvider != OrmProvider.DATANUCLEUS && props.containsKey(dnKey)) {
props.remove(dnKey);
props.store(log4jMutableFile.getOutputStream(), "Updated at " + new Date());
}
}
} catch (IOException ioe) {
throw new IllegalStateException(ioe);
}
}
private void updatePomProperties(Element configuration, OrmProvider ormProvider, JdbcDatabase database) {
List<Element> databaseProperties = XmlUtils.findElements(getDbXPath(database) + "/properties/*", configuration);
for (Element property : databaseProperties) {
projectOperations.addProperty(new Property(property));
}
List<Element> providerProperties = XmlUtils.findElements(getProviderXPath(ormProvider) + "/properties/*", configuration);
for (Element property : providerProperties) {
projectOperations.addProperty(new Property(property));
}
}
private void updateDependencies(Element configuration, OrmProvider ormProvider, JdbcDatabase database) {
List<Element> databaseDependencies = XmlUtils.findElements(getDbXPath(database) + "/dependencies/dependency", configuration);
for (Element dependencyElement : databaseDependencies) {
projectOperations.dependencyUpdate(new Dependency(dependencyElement));
}
List<Element> ormDependencies = XmlUtils.findElements(getProviderXPath(ormProvider) + "/dependencies/dependency", configuration);
for (Element dependencyElement : ormDependencies) {
projectOperations.dependencyUpdate(new Dependency(dependencyElement));
}
// Hard coded to JPA & Hibernate Validator for now
List<Element> jpaDependencies = XmlUtils.findElements("/configuration/persistence/provider[@id = 'JPA']/dependencies/dependency", configuration);
for (Element dependencyElement : jpaDependencies) {
projectOperations.dependencyUpdate(new Dependency(dependencyElement));
}
List<Element> springDependencies = XmlUtils.findElements("/configuration/spring/dependencies/dependency", configuration);
for (Element dependencyElement : springDependencies) {
projectOperations.dependencyUpdate(new Dependency(dependencyElement));
}
if (database == JdbcDatabase.ORACLE || database == JdbcDatabase.DB2) {
logger.warning("The " + database.name() + " JDBC driver is not available in public maven repositories. Please adjust the pom.xml dependency to suit your needs");
}
}
private String getProjectName() {
return ((ProjectMetadata) metadataService.get(ProjectMetadata.getProjectIdentifier())).getProjectName();
}
private void updateRepositories(Element configuration, OrmProvider ormProvider, JdbcDatabase database) {
List<Element> databaseRepositories = XmlUtils.findElements(getDbXPath(database) + "/repositories/repository", configuration);
for (Element repositoryElement : databaseRepositories) {
projectOperations.addRepository(new Repository(repositoryElement));
}
List<Element> ormRepositories = XmlUtils.findElements(getProviderXPath(ormProvider) + "/repositories/repository", configuration);
for (Element repositoryElement : ormRepositories) {
projectOperations.addRepository(new Repository(repositoryElement));
}
List<Element> jpaRepositories = XmlUtils.findElements("/configuration/persistence/provider[@id='JPA']/repositories/repository", configuration);
for (Element repositoryElement : jpaRepositories) {
projectOperations.addRepository(new Repository(repositoryElement));
}
}
private void updatePluginRepositories(Element configuration, OrmProvider ormProvider, JdbcDatabase database) {
List<Element> databasePluginRepositories = XmlUtils.findElements(getDbXPath(database) + "/pluginRepositories/pluginRepository", configuration);
for (Element pluginRepositoryElement : databasePluginRepositories) {
projectOperations.addPluginRepository(new Repository(pluginRepositoryElement));
}
List<Element> ormPluginRepositories = XmlUtils.findElements(getProviderXPath(ormProvider) + "/pluginRepositories/pluginRepository", configuration);
for (Element pluginRepositoryElement : ormPluginRepositories) {
projectOperations.addPluginRepository(new Repository(pluginRepositoryElement));
}
}
private void updateFilters(Element configuration, OrmProvider ormProvider, JdbcDatabase database) {
List<Element> databaseFilters = XmlUtils.findElements(getDbXPath(database) + "/filters/filter", configuration);
for (Element filterElement : databaseFilters) {
projectOperations.addFilter(new Filter(filterElement));
}
List<Element> ormFilters = XmlUtils.findElements(getProviderXPath(ormProvider) + "/filters/filter", configuration);
for (Element filterElement : ormFilters) {
projectOperations.addFilter(new Filter(filterElement));
}
}
private void updateResources(Element configuration, OrmProvider ormProvider, JdbcDatabase database) {
List<Element> databaseResources = XmlUtils.findElements(getDbXPath(database) + "/resources/resource", configuration);
for (Element resourceElement : databaseResources) {
projectOperations.addResource(new Resource(resourceElement));
}
List<Element> ormResources = XmlUtils.findElements(getProviderXPath(ormProvider) + "/resources/resource", configuration);
for (Element resourceElement : ormResources) {
projectOperations.addResource(new Resource(resourceElement));
}
}
private void updateBuildPlugins(Element configuration, OrmProvider ormProvider, JdbcDatabase database) {
List<Element> databasePlugins = XmlUtils.findElements(getDbXPath(database) + "/plugins/plugin", configuration);
for (Element pluginElement : databasePlugins) {
projectOperations.addBuildPlugin(new Plugin(pluginElement));
}
List<Element> ormPlugins = XmlUtils.findElements(getProviderXPath(ormProvider) + "/plugins/plugin", configuration);
for (Element pluginElement : ormPlugins) {
projectOperations.addBuildPlugin(new Plugin(pluginElement));
}
if (database == JdbcDatabase.GOOGLE_APP_ENGINE) {
updateEclipsePlugin(true);
}
}
private void updateEclipsePlugin(boolean addBuildCommand) {
String pomPath = pathResolver.getIdentifier(Path.ROOT, "pom.xml");
MutableFile pomMutableFile = null;
Document pom;
try {
if (fileManager.exists(pomPath)) {
pomMutableFile = fileManager.updateFile(pomPath);
pom = XmlUtils.getDocumentBuilder().parse(pomMutableFile.getInputStream());
} else {
throw new IllegalStateException("Could not acquire pom.xml in " + pomPath);
}
} catch (Exception e) {
throw new IllegalStateException(e);
}
Element root = pom.getDocumentElement();
String gaeBuildCommandName = "com.google.appengine.eclipse.core.enhancerbuilder";
Element additionalBuildcommandsElement = XmlUtils.findFirstElement("/project/build/plugins/plugin[artifactId = 'maven-eclipse-plugin']/configuration/additionalBuildcommands", root);
Assert.notNull(additionalBuildcommandsElement, "additionalBuildcommands element of the maven-eclipse-plugin reqired");
Element buildCommandElement = XmlUtils.findFirstElement("buildCommand[name = '" + gaeBuildCommandName + "']", additionalBuildcommandsElement);
if (addBuildCommand && buildCommandElement == null) {
Element nameElement = pom.createElement("name");
nameElement.setTextContent(gaeBuildCommandName);
buildCommandElement = pom.createElement("buildCommand");
buildCommandElement.appendChild(nameElement);
additionalBuildcommandsElement.appendChild(buildCommandElement);
XmlUtils.writeXml(pomMutableFile.getOutputStream(), pom);
}
if (!addBuildCommand && buildCommandElement != null) {
additionalBuildcommandsElement.removeChild(buildCommandElement);
XmlUtils.writeXml(pomMutableFile.getOutputStream(), pom);
}
}
private void cleanup(Element configuration, OrmProvider ormProvider, JdbcDatabase database) {
for (JdbcDatabase jdbcDatabase : JdbcDatabase.values()) {
if (!jdbcDatabase.getKey().equals(database.getKey()) && !jdbcDatabase.getDriverClassName().equals(database.getDriverClassName())) {
List<Element> dependencies = XmlUtils.findElements(getDbXPath(jdbcDatabase) + "/dependencies/dependency", configuration);
for (Element dependencyElement : dependencies) {
projectOperations.removeDependency(new Dependency(dependencyElement));
}
List<Element> filters = XmlUtils.findElements(getDbXPath(jdbcDatabase) + "/filters/filter", configuration);
for (Element filterElement : filters) {
projectOperations.removeFilter(new Filter(filterElement));
}
List<Element> plugins = XmlUtils.findElements(getDbXPath(jdbcDatabase) + "/plugins/plugin", configuration);
for (Element pluginElement : plugins) {
projectOperations.removeBuildPlugin(new Plugin(pluginElement));
}
}
}
for (OrmProvider provider : OrmProvider.values()) {
if (provider != ormProvider) {
// List<Element> pomProperties = XmlUtils.findElements("/configuration/ormProviders/provider[@id = '" + provider.name() + "']/properties/*", configuration);
// for (Element propertyElement : pomProperties) {
// projectOperations.removeProperty(new Property(propertyElement));
// }
List<Element> dependencies = XmlUtils.findElements(getProviderXPath(provider) + "/dependencies/dependency", configuration);
for (Element dependencyElement : dependencies) {
projectOperations.removeDependency(new Dependency(dependencyElement));
}
List<Element> filters = XmlUtils.findElements(getProviderXPath(provider) + "/filters/filter", configuration);
for (Element filterElement : filters) {
projectOperations.removeFilter(new Filter(filterElement));
}
List<Element> plugins = XmlUtils.findElements(getProviderXPath(provider) + "/plugins/plugin", configuration);
for (Element pluginElement : plugins) {
projectOperations.removeBuildPlugin(new Plugin(pluginElement));
}
}
}
if (database != JdbcDatabase.GOOGLE_APP_ENGINE) {
updateEclipsePlugin(false);
}
}
private String getDbXPath(JdbcDatabase database) {
return "/configuration/databases/database[@id = '" + database.getKey() + "']";
}
private String getProviderXPath(OrmProvider provider) {
return "/configuration/ormProviders/provider[@id = '" + provider.name() + "']";
}
private Element createPropertyElement(String name, String value, Document doc) {
Element property = doc.createElement("property");
property.setAttribute("name", name);
property.setAttribute("value", value);
return property;
}
private Element createRefElement(String name, String value, Document doc) {
Element property = doc.createElement("property");
property.setAttribute("name", name);
property.setAttribute("ref", value);
return property;
}
private SortedSet<String> getPropertiesFromDataNucleusConfiguration() {
String persistenceXmlPath = pathResolver.getIdentifier(Path.SRC_MAIN_RESOURCES, "META-INF/persistence.xml");
if (!fileManager.exists(persistenceXmlPath)) {
throw new IllegalStateException("Failed to find " + persistenceXmlPath);
}
FileDetails fileDetails = fileManager.readFile(persistenceXmlPath);
Document document = null;
try {
InputStream is = new FileInputStream(fileDetails.getFile());
DocumentBuilder builder = XmlUtils.getDocumentBuilder();
builder.setErrorHandler(null);
document = builder.parse(is);
} catch (Exception e) {
throw new IllegalStateException(e);
}
List<Element> propertyElements = XmlUtils.findElements("/persistence/persistence-unit/properties/property", document.getDocumentElement());
Assert.notEmpty(propertyElements, "Failed to find property elements in " + persistenceXmlPath);
SortedSet<String> properties = new TreeSet<String>();
for (Element propertyElement : propertyElements) {
String key = propertyElement.getAttribute("name");
String value = propertyElement.getAttribute("value");
if ("datanucleus.ConnectionDriverName".equals(key)) {
properties.add("datanucleus.ConnectionDriverName = " + value);
}
if ("datanucleus.ConnectionURL".equals(key)) {
properties.add("datanucleus.ConnectionURL = " + value);
}
if ("datanucleus.ConnectionUserName".equals(key)) {
properties.add("datanucleus.ConnectionUserName = " + value);
}
if ("datanucleus.ConnectionPassword".equals(key)) {
properties.add("datanucleus.ConnectionPassword = " + value);
}
}
return properties;
}
}
| true | true | private void updatePersistenceXml(OrmProvider ormProvider, JdbcDatabase database, String databaseName, String userName, String password, String persistenceUnit) {
String persistencePath = pathResolver.getIdentifier(Path.SRC_MAIN_RESOURCES, "META-INF/persistence.xml");
MutableFile persistenceMutableFile = null;
Document persistence;
try {
if (fileManager.exists(persistencePath)) {
persistenceMutableFile = fileManager.updateFile(persistencePath);
persistence = XmlUtils.getDocumentBuilder().parse(persistenceMutableFile.getInputStream());
} else {
persistenceMutableFile = fileManager.createFile(persistencePath);
InputStream templateInputStream = TemplateUtils.getTemplate(getClass(), "persistence-template.xml");
Assert.notNull(templateInputStream, "Could not acquire peristence.xml template");
persistence = XmlUtils.getDocumentBuilder().parse(templateInputStream);
}
} catch (Exception e) {
throw new IllegalStateException(e);
}
Properties dialects = new Properties();
try {
InputStream dialectsInputStream = TemplateUtils.getTemplate(getClass(), "jpa-dialects.properties");
Assert.notNull(dialectsInputStream, "Could not acquire jpa-dialects.properties");
dialects.load(dialectsInputStream);
} catch (Exception e) {
throw new IllegalStateException(e);
}
Element root = persistence.getDocumentElement();
Element persistenceElement = XmlUtils.findFirstElement("/persistence", root);
Assert.notNull(persistenceElement, "No persistence element found");
Element persistenceUnitElement;
if (StringUtils.hasText(persistenceUnit)) {
persistenceUnitElement = XmlUtils.findFirstElement("persistence-unit[@name = '" + persistenceUnit + "']", persistenceElement);
if (persistenceUnitElement == null) {
persistenceUnitElement = persistence.createElement("persistence-unit");
persistenceElement.appendChild(persistenceUnitElement);
}
} else {
persistenceUnitElement = XmlUtils.findFirstElement("persistence-unit[@name = '" + (database == JdbcDatabase.GOOGLE_APP_ENGINE ? GAE_PERSISTENCE_UNIT_NAME : PERSISTENCE_UNIT_NAME) + "']", persistenceElement);
if (persistenceUnitElement == null) {
persistenceUnitElement = XmlUtils.findFirstElement("persistence-unit", persistenceElement);
}
}
Assert.notNull(persistenceUnitElement, "No persistence-unit elements found");
while (persistenceUnitElement.getFirstChild() != null) {
persistenceUnitElement.removeChild(persistenceUnitElement.getFirstChild());
}
// Set attributes for DataNuclueus 1.1.x/GAE-specific requirements
switch (ormProvider) {
case DATANUCLEUS:
persistenceElement.setAttribute("version", "1.0");
persistenceElement.setAttribute("xsi:schemaLocation", "http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd");
break;
default:
persistenceElement.setAttribute("version", "2.0");
persistenceElement.setAttribute("xsi:schemaLocation", "http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd");
break;
}
// Add provider element
Element provider = persistence.createElement("provider");
switch (database) {
case GOOGLE_APP_ENGINE:
persistenceUnitElement.setAttribute("name", GAE_PERSISTENCE_UNIT_NAME);
persistenceUnitElement.removeAttribute("transaction-type");
provider.setTextContent(ormProvider.getAlternateAdapter());
break;
case VMFORCE:
persistenceUnitElement.setAttribute("name", "PERSISTENCE_UNIT_NAME");
persistenceUnitElement.removeAttribute("transaction-type");
provider.setTextContent(ormProvider.getAdapter());
break;
default:
persistenceUnitElement.setAttribute("name", (StringUtils.hasText(persistenceUnit) ? persistenceUnit : PERSISTENCE_UNIT_NAME));
persistenceUnitElement.setAttribute("transaction-type", "RESOURCE_LOCAL");
provider.setTextContent(ormProvider.getAdapter());
break;
}
persistenceUnitElement.appendChild(provider);
// Add properties
Element properties = persistence.createElement("properties");
switch (ormProvider) {
case HIBERNATE:
properties.appendChild(createPropertyElement("hibernate.dialect", dialects.getProperty(ormProvider.name() + "." + database.name()), persistence));
properties.appendChild(persistence.createComment("value='create' to build a new database on each run; value='update' to modify an existing database; value='create-drop' means the same as 'create' but also drops tables when Hibernate closes; value='validate' makes no changes to the database")); // ROO-627
String hbm2dll = "create";
if (database == JdbcDatabase.DB2400) {
hbm2dll = "validate";
}
properties.appendChild(createPropertyElement("hibernate.hbm2ddl.auto", hbm2dll, persistence));
properties.appendChild(createPropertyElement("hibernate.ejb.naming_strategy", "org.hibernate.cfg.ImprovedNamingStrategy", persistence));
break;
case OPENJPA:
properties.appendChild(createPropertyElement("openjpa.jdbc.DBDictionary", dialects.getProperty(ormProvider.name() + "." + database.name()), persistence));
properties.appendChild(persistence.createComment("value='buildSchema' to runtime forward map the DDL SQL; value='validate' makes no changes to the database")); // ROO-627
properties.appendChild(createPropertyElement("openjpa.jdbc.SynchronizeMappings", "buildSchema", persistence));
properties.appendChild(createPropertyElement("openjpa.RuntimeUnenhancedClasses", "supported", persistence));
break;
case ECLIPSELINK:
properties.appendChild(createPropertyElement("eclipselink.target-database", dialects.getProperty(ormProvider.name() + "." + database.name()), persistence));
properties.appendChild(persistence.createComment("value='drop-and-create-tables' to build a new database on each run; value='create-tables' creates new tables if needed; value='none' makes no changes to the database")); // ROO-627
properties.appendChild(createPropertyElement("eclipselink.ddl-generation", "drop-and-create-tables", persistence));
properties.appendChild(createPropertyElement("eclipselink.ddl-generation.output-mode", "database", persistence));
properties.appendChild(createPropertyElement("eclipselink.weaving", "static", persistence));
break;
case DATANUCLEUS:
case DATANUCLEUS_2:
String connectionString = database.getConnectionString();
switch (database) {
case GOOGLE_APP_ENGINE:
properties.appendChild(createPropertyElement("datanucleus.NontransactionalRead", "true", persistence));
properties.appendChild(createPropertyElement("datanucleus.NontransactionalWrite", "true", persistence));
break;
case VMFORCE:
userName = "${sfdc.userName}";
password = "${sfdc.password}";
properties.appendChild(createPropertyElement("datanucleus.Optimistic", "false", persistence));
properties.appendChild(createPropertyElement("datanucleus.datastoreTransactionDelayOperations", "true", persistence));
properties.appendChild(createPropertyElement("sfdcConnectionName", "DefaultSFDCConnection", persistence));
break;
default:
properties.appendChild(createPropertyElement("datanucleus.ConnectionDriverName", database.getDriverClassName(), persistence));
ProjectMetadata projectMetadata = (ProjectMetadata) metadataService.get(ProjectMetadata.getProjectIdentifier());
connectionString = connectionString.replace("TO_BE_CHANGED_BY_ADDON", projectMetadata.getProjectName());
switch (database) {
case HYPERSONIC_IN_MEMORY:
case HYPERSONIC_PERSISTENT:
case H2_IN_MEMORY:
userName = StringUtils.hasText(userName) ? userName : "sa";
break;
case DERBY:
break;
default:
logger.warning("Please enter your database details in src/main/resources/META-INF/persistence.xml.");
break;
}
properties.appendChild(createPropertyElement("datanucleus.storeManagerType", "rdbms", persistence));
}
properties.appendChild(createPropertyElement("datanucleus.ConnectionURL", connectionString, persistence));
properties.appendChild(createPropertyElement("datanucleus.ConnectionUserName", userName, persistence));
properties.appendChild(createPropertyElement("datanucleus.ConnectionPassword", password, persistence));
properties.appendChild(createPropertyElement("datanucleus.autoCreateSchema", "false", persistence));
properties.appendChild(createPropertyElement("datanucleus.autoCreateTables", "true", persistence));
properties.appendChild(createPropertyElement("datanucleus.autoCreateColumns", "false", persistence));
properties.appendChild(createPropertyElement("datanucleus.autoCreateConstraints", "false", persistence));
properties.appendChild(createPropertyElement("datanucleus.validateTables", "false", persistence));
properties.appendChild(createPropertyElement("datanucleus.validateConstraints", "false", persistence));
properties.appendChild(createPropertyElement("datanucleus.jpa.addClassTransformer", "false", persistence));
break;
}
persistenceUnitElement.appendChild(properties);
XmlUtils.writeXml(persistenceMutableFile.getOutputStream(), persistence);
}
| private void updatePersistenceXml(OrmProvider ormProvider, JdbcDatabase database, String databaseName, String userName, String password, String persistenceUnit) {
String persistencePath = pathResolver.getIdentifier(Path.SRC_MAIN_RESOURCES, "META-INF/persistence.xml");
MutableFile persistenceMutableFile = null;
Document persistence;
try {
if (fileManager.exists(persistencePath)) {
persistenceMutableFile = fileManager.updateFile(persistencePath);
persistence = XmlUtils.getDocumentBuilder().parse(persistenceMutableFile.getInputStream());
} else {
persistenceMutableFile = fileManager.createFile(persistencePath);
InputStream templateInputStream = TemplateUtils.getTemplate(getClass(), "persistence-template.xml");
Assert.notNull(templateInputStream, "Could not acquire peristence.xml template");
persistence = XmlUtils.getDocumentBuilder().parse(templateInputStream);
}
} catch (Exception e) {
throw new IllegalStateException(e);
}
Properties dialects = new Properties();
try {
InputStream dialectsInputStream = TemplateUtils.getTemplate(getClass(), "jpa-dialects.properties");
Assert.notNull(dialectsInputStream, "Could not acquire jpa-dialects.properties");
dialects.load(dialectsInputStream);
} catch (Exception e) {
throw new IllegalStateException(e);
}
Element root = persistence.getDocumentElement();
Element persistenceElement = XmlUtils.findFirstElement("/persistence", root);
Assert.notNull(persistenceElement, "No persistence element found");
Element persistenceUnitElement;
if (StringUtils.hasText(persistenceUnit)) {
persistenceUnitElement = XmlUtils.findFirstElement("persistence-unit[@name = '" + persistenceUnit + "']", persistenceElement);
if (persistenceUnitElement == null) {
persistenceUnitElement = persistence.createElement("persistence-unit");
persistenceElement.appendChild(persistenceUnitElement);
}
} else {
persistenceUnitElement = XmlUtils.findFirstElement("persistence-unit[@name = '" + (database == JdbcDatabase.GOOGLE_APP_ENGINE ? GAE_PERSISTENCE_UNIT_NAME : PERSISTENCE_UNIT_NAME) + "']", persistenceElement);
if (persistenceUnitElement == null) {
persistenceUnitElement = XmlUtils.findFirstElement("persistence-unit", persistenceElement);
}
}
Assert.notNull(persistenceUnitElement, "No persistence-unit elements found");
while (persistenceUnitElement.getFirstChild() != null) {
persistenceUnitElement.removeChild(persistenceUnitElement.getFirstChild());
}
// Set attributes for DataNuclueus 1.1.x/GAE-specific requirements
switch (ormProvider) {
case DATANUCLEUS:
persistenceElement.setAttribute("version", "1.0");
persistenceElement.setAttribute("xsi:schemaLocation", "http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd");
break;
default:
persistenceElement.setAttribute("version", "2.0");
persistenceElement.setAttribute("xsi:schemaLocation", "http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd");
break;
}
// Add provider element
Element provider = persistence.createElement("provider");
switch (database) {
case GOOGLE_APP_ENGINE:
persistenceUnitElement.setAttribute("name", GAE_PERSISTENCE_UNIT_NAME);
persistenceUnitElement.removeAttribute("transaction-type");
provider.setTextContent(ormProvider.getAlternateAdapter());
break;
case VMFORCE:
persistenceUnitElement.setAttribute("name", PERSISTENCE_UNIT_NAME);
persistenceUnitElement.removeAttribute("transaction-type");
provider.setTextContent(ormProvider.getAdapter());
break;
default:
persistenceUnitElement.setAttribute("name", (StringUtils.hasText(persistenceUnit) ? persistenceUnit : PERSISTENCE_UNIT_NAME));
persistenceUnitElement.setAttribute("transaction-type", "RESOURCE_LOCAL");
provider.setTextContent(ormProvider.getAdapter());
break;
}
persistenceUnitElement.appendChild(provider);
// Add properties
Element properties = persistence.createElement("properties");
switch (ormProvider) {
case HIBERNATE:
properties.appendChild(createPropertyElement("hibernate.dialect", dialects.getProperty(ormProvider.name() + "." + database.name()), persistence));
properties.appendChild(persistence.createComment("value='create' to build a new database on each run; value='update' to modify an existing database; value='create-drop' means the same as 'create' but also drops tables when Hibernate closes; value='validate' makes no changes to the database")); // ROO-627
String hbm2dll = "create";
if (database == JdbcDatabase.DB2400) {
hbm2dll = "validate";
}
properties.appendChild(createPropertyElement("hibernate.hbm2ddl.auto", hbm2dll, persistence));
properties.appendChild(createPropertyElement("hibernate.ejb.naming_strategy", "org.hibernate.cfg.ImprovedNamingStrategy", persistence));
break;
case OPENJPA:
properties.appendChild(createPropertyElement("openjpa.jdbc.DBDictionary", dialects.getProperty(ormProvider.name() + "." + database.name()), persistence));
properties.appendChild(persistence.createComment("value='buildSchema' to runtime forward map the DDL SQL; value='validate' makes no changes to the database")); // ROO-627
properties.appendChild(createPropertyElement("openjpa.jdbc.SynchronizeMappings", "buildSchema", persistence));
properties.appendChild(createPropertyElement("openjpa.RuntimeUnenhancedClasses", "supported", persistence));
break;
case ECLIPSELINK:
properties.appendChild(createPropertyElement("eclipselink.target-database", dialects.getProperty(ormProvider.name() + "." + database.name()), persistence));
properties.appendChild(persistence.createComment("value='drop-and-create-tables' to build a new database on each run; value='create-tables' creates new tables if needed; value='none' makes no changes to the database")); // ROO-627
properties.appendChild(createPropertyElement("eclipselink.ddl-generation", "drop-and-create-tables", persistence));
properties.appendChild(createPropertyElement("eclipselink.ddl-generation.output-mode", "database", persistence));
properties.appendChild(createPropertyElement("eclipselink.weaving", "static", persistence));
break;
case DATANUCLEUS:
case DATANUCLEUS_2:
String connectionString = database.getConnectionString();
switch (database) {
case GOOGLE_APP_ENGINE:
properties.appendChild(createPropertyElement("datanucleus.NontransactionalRead", "true", persistence));
properties.appendChild(createPropertyElement("datanucleus.NontransactionalWrite", "true", persistence));
break;
case VMFORCE:
userName = "${sfdc.userName}";
password = "${sfdc.password}";
properties.appendChild(createPropertyElement("datanucleus.Optimistic", "false", persistence));
properties.appendChild(createPropertyElement("datanucleus.datastoreTransactionDelayOperations", "true", persistence));
properties.appendChild(createPropertyElement("sfdcConnectionName", "DefaultSFDCConnection", persistence));
break;
default:
properties.appendChild(createPropertyElement("datanucleus.ConnectionDriverName", database.getDriverClassName(), persistence));
ProjectMetadata projectMetadata = (ProjectMetadata) metadataService.get(ProjectMetadata.getProjectIdentifier());
connectionString = connectionString.replace("TO_BE_CHANGED_BY_ADDON", projectMetadata.getProjectName());
switch (database) {
case HYPERSONIC_IN_MEMORY:
case HYPERSONIC_PERSISTENT:
case H2_IN_MEMORY:
userName = StringUtils.hasText(userName) ? userName : "sa";
break;
case DERBY:
break;
default:
logger.warning("Please enter your database details in src/main/resources/META-INF/persistence.xml.");
break;
}
properties.appendChild(createPropertyElement("datanucleus.storeManagerType", "rdbms", persistence));
}
properties.appendChild(createPropertyElement("datanucleus.ConnectionURL", connectionString, persistence));
properties.appendChild(createPropertyElement("datanucleus.ConnectionUserName", userName, persistence));
properties.appendChild(createPropertyElement("datanucleus.ConnectionPassword", password, persistence));
properties.appendChild(createPropertyElement("datanucleus.autoCreateSchema", "false", persistence));
properties.appendChild(createPropertyElement("datanucleus.autoCreateTables", "true", persistence));
properties.appendChild(createPropertyElement("datanucleus.autoCreateColumns", "false", persistence));
properties.appendChild(createPropertyElement("datanucleus.autoCreateConstraints", "false", persistence));
properties.appendChild(createPropertyElement("datanucleus.validateTables", "false", persistence));
properties.appendChild(createPropertyElement("datanucleus.validateConstraints", "false", persistence));
properties.appendChild(createPropertyElement("datanucleus.jpa.addClassTransformer", "false", persistence));
break;
}
persistenceUnitElement.appendChild(properties);
XmlUtils.writeXml(persistenceMutableFile.getOutputStream(), persistence);
}
|
diff --git a/content-tool/tool/src/java/org/sakaiproject/content/tool/ResourcesAction.java b/content-tool/tool/src/java/org/sakaiproject/content/tool/ResourcesAction.java
index 0486f88a..6555d10a 100644
--- a/content-tool/tool/src/java/org/sakaiproject/content/tool/ResourcesAction.java
+++ b/content-tool/tool/src/java/org/sakaiproject/content/tool/ResourcesAction.java
@@ -1,13265 +1,13265 @@
/**********************************************************************************
* $URL$
* $Id$
***********************************************************************************
*
* Copyright (c) 2003, 2004, 2005, 2006 The Sakai Foundation.
*
* Licensed under the Educational Community 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.opensource.org/licenses/ecl1.php
*
* 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.sakaiproject.content.tool;
import java.io.IOException;
import java.io.StringReader;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.SortedSet;
import java.util.Stack;
import java.util.TreeSet;
import java.util.Vector;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
import org.sakaiproject.authz.api.PermissionsHelper;
import org.sakaiproject.authz.cover.AuthzGroupService;
import org.sakaiproject.authz.cover.SecurityService;
import org.sakaiproject.cheftool.Context;
import org.sakaiproject.cheftool.JetspeedRunData;
import org.sakaiproject.cheftool.PagedResourceHelperAction;
import org.sakaiproject.cheftool.PortletConfig;
import org.sakaiproject.cheftool.RunData;
import org.sakaiproject.cheftool.VelocityPortlet;
import org.sakaiproject.cheftool.VelocityPortletPaneledAction;
import org.sakaiproject.component.cover.ComponentManager;
import org.sakaiproject.component.cover.ServerConfigurationService;
import org.sakaiproject.content.api.ContentCollection;
import org.sakaiproject.content.api.ContentCollectionEdit;
import org.sakaiproject.content.api.ContentEntity;
import org.sakaiproject.content.api.ContentResource;
import org.sakaiproject.content.api.ContentResourceEdit;
import org.sakaiproject.content.api.ContentResourceFilter;
import org.sakaiproject.content.api.FilePickerHelper;
import org.sakaiproject.content.api.GroupAwareEdit;
import org.sakaiproject.content.api.GroupAwareEntity;
import org.sakaiproject.content.api.GroupAwareEntity.AccessMode;
import org.sakaiproject.content.cover.ContentHostingService;
import org.sakaiproject.content.cover.ContentTypeImageService;
import org.sakaiproject.entity.api.Entity;
import org.sakaiproject.entity.api.EntityPropertyNotDefinedException;
import org.sakaiproject.entity.api.EntityPropertyTypeException;
import org.sakaiproject.entity.api.Reference;
import org.sakaiproject.entity.api.ResourceProperties;
import org.sakaiproject.entity.api.ResourcePropertiesEdit;
import org.sakaiproject.entity.cover.EntityManager;
import org.sakaiproject.event.api.SessionState;
import org.sakaiproject.event.api.UsageSession;
import org.sakaiproject.event.cover.NotificationService;
import org.sakaiproject.event.cover.UsageSessionService;
import org.sakaiproject.exception.IdInvalidException;
import org.sakaiproject.exception.IdLengthException;
import org.sakaiproject.exception.IdUniquenessException;
import org.sakaiproject.exception.IdUnusedException;
import org.sakaiproject.exception.IdUsedException;
import org.sakaiproject.exception.InUseException;
import org.sakaiproject.exception.InconsistentException;
import org.sakaiproject.exception.OverQuotaException;
import org.sakaiproject.exception.PermissionException;
import org.sakaiproject.exception.ServerOverloadException;
import org.sakaiproject.exception.TypeException;
import org.sakaiproject.metaobj.shared.control.SchemaBean;
import org.sakaiproject.metaobj.shared.mgt.HomeFactory;
import org.sakaiproject.metaobj.shared.mgt.StructuredArtifactValidationService;
import org.sakaiproject.metaobj.shared.mgt.home.StructuredArtifactHomeInterface;
import org.sakaiproject.metaobj.shared.model.ElementBean;
import org.sakaiproject.metaobj.shared.model.ValidationError;
import org.sakaiproject.metaobj.utils.xml.SchemaNode;
import org.sakaiproject.site.api.Group;
import org.sakaiproject.site.api.Site;
import org.sakaiproject.site.cover.SiteService;
import org.sakaiproject.time.api.Time;
import org.sakaiproject.time.api.TimeBreakdown;
import org.sakaiproject.time.cover.TimeService;
import org.sakaiproject.tool.cover.ToolManager;
import org.sakaiproject.user.api.User;
import org.sakaiproject.user.api.UserNotDefinedException;
import org.sakaiproject.user.cover.UserDirectoryService;
import org.sakaiproject.util.FileItem;
import org.sakaiproject.util.FormattedText;
import org.sakaiproject.util.ParameterParser;
import org.sakaiproject.util.ResourceLoader;
import org.sakaiproject.util.StringUtil;
import org.sakaiproject.util.Validator;
import org.sakaiproject.util.Xml;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.w3c.dom.Text;
/**
* <p>ResourceAction is a ContentHosting application</p>
*
* @author University of Michigan, CHEF Software Development Team
* @version $Revision$
*/
public class ResourcesAction
extends PagedResourceHelperAction // VelocityPortletPaneledAction
{
/** Resource bundle using current language locale */
private static ResourceLoader rb = new ResourceLoader("content");
private static final Log logger = LogFactory.getLog(ResourcesAction.class);
/** Name of state attribute containing a list of opened/expanded collections */
private static final String STATE_EXPANDED_COLLECTIONS = "resources.expanded_collections";
/** Name of state attribute for status of initialization. */
private static final String STATE_INITIALIZED = "resources.initialized";
/** The content hosting service in the State. */
private static final String STATE_CONTENT_SERVICE = "resources.content_service";
/** The content type image lookup service in the State. */
private static final String STATE_CONTENT_TYPE_IMAGE_SERVICE = "resources.content_type_image_service";
/** The resources, helper or dropbox mode. */
public static final String STATE_MODE_RESOURCES = "resources.resources_mode";
/** The resources, helper or dropbox mode. */
public static final String STATE_RESOURCES_HELPER_MODE = "resources.resources_helper_mode";
/** state attribute for the maximum size for file upload */
private static final String STATE_FILE_UPLOAD_MAX_SIZE = "resources.file_upload_max_size";
/** state attribute indicating whether users in current site should be denied option of making resources public */
private static final String STATE_PREVENT_PUBLIC_DISPLAY = "resources.prevent_public_display";
/** The name of a state attribute indicating whether the resources tool/helper is allowed to show all sites the user has access to */
public static final String STATE_SHOW_ALL_SITES = "resources.allow_user_to_see_all_sites";
/** The name of a state attribute indicating whether the wants to see other sites if that is enabled */
public static final String STATE_SHOW_OTHER_SITES = "resources.user_chooses_to_see_other_sites";
/** The user copyright string */
private static final String STATE_MY_COPYRIGHT = "resources.mycopyright";
/** copyright path -- MUST have same value as AccessServlet.COPYRIGHT_PATH */
public static final String COPYRIGHT_PATH = Entity.SEPARATOR + "copyright";
/** The collection id being browsed. */
private static final String STATE_COLLECTION_ID = "resources.collection_id";
/** The id of the "home" collection (can't go up from here.) */
private static final String STATE_HOME_COLLECTION_ID = "resources.collection_home";
/** The display name of the "home" collection (can't go up from here.) */
private static final String STATE_HOME_COLLECTION_DISPLAY_NAME = "resources.collection_home_display_name";
/** The inqualified input field */
private static final String STATE_UNQUALIFIED_INPUT_FIELD = "resources.unqualified_input_field";
/** The collection id path */
private static final String STATE_COLLECTION_PATH = "resources.collection_path";
/** The name of the state attribute containing BrowseItems for all content collections the user has access to */
private static final String STATE_COLLECTION_ROOTS = "resources.collection_rootie_tooties";
/** The sort by */
private static final String STATE_SORT_BY = "resources.sort_by";
/** The sort ascending or decending */
private static final String STATE_SORT_ASC = "resources.sort_asc";
/** The copy flag */
private static final String STATE_COPY_FLAG = "resources.copy_flag";
/** The cut flag */
private static final String STATE_CUT_FLAG = "resources.cut_flag";
/** The can-paste flag */
private static final String STATE_PASTE_ALLOWED_FLAG = "resources.can_paste_flag";
/** The move flag */
private static final String STATE_MOVE_FLAG = "resources.move_flag";
/** The select all flag */
private static final String STATE_SELECT_ALL_FLAG = "resources.select_all_flag";
/** The name of the state attribute indicating whether the hierarchical list is expanded */
private static final String STATE_EXPAND_ALL_FLAG = "resources.expand_all_flag";
/** The name of the state attribute indicating whether the hierarchical list needs to be expanded */
private static final String STATE_NEED_TO_EXPAND_ALL = "resources.need_to_expand_all";
/** The name of the state attribute containing a java.util.Set with the id's of selected items */
private static final String STATE_LIST_SELECTIONS = "resources.ignore_delete_selections";
/** The root of the navigation breadcrumbs for a folder, either the home or another site the user belongs to */
private static final String STATE_NAVIGATION_ROOT = "resources.navigation_root";
/************** the more context *****************************************/
/** The more id */
private static final String STATE_MORE_ID = "resources.more_id";
/** The more collection id */
private static final String STATE_MORE_COLLECTION_ID = "resources.more_collection_id";
/************** the edit context *****************************************/
/** The edit id */
public static final String STATE_EDIT_ID = "resources.edit_id";
public static final String STATE_STACK_EDIT_ID = "resources.stack_edit_id";
public static final String STATE_EDIT_COLLECTION_ID = "resources.stack_edit_collection_id";
public static final String STATE_STACK_EDIT_COLLECTION_ID = "resources.stack_edit_collection_id";
private static final String STATE_EDIT_ALERTS = "resources.edit_alerts";
private static final String STATE_STACK_EDIT_ITEM = "resources.stack_edit_item";
private static final String STATE_STACK_EDIT_INTENT = "resources.stack_edit_intent";
private static final String STATE_SHOW_FORM_ITEMS = "resources.show_form_items";
private static final String STATE_STACK_EDIT_ITEM_TITLE = "resources.stack_title";
/************** the create contexts *****************************************/
public static final String STATE_SUSPENDED_OPERATIONS_STACK = "resources.suspended_operations_stack";
public static final String STATE_SUSPENDED_OPERATIONS_STACK_DEPTH = "resources.suspended_operations_stack_depth";
public static final String STATE_CREATE_TYPE = "resources.create_type";
public static final String STATE_CREATE_COLLECTION_ID = "resources.create_collection_id";
public static final String STATE_CREATE_NUMBER = "resources.create_number";
public static final String STATE_STRUCTOBJ_TYPE = "resources.create_structured_object_type";
public static final String STATE_STRUCTOBJ_TYPE_READONLY = "resources.create_structured_object_type_readonly";
public static final String STATE_STACK_CREATE_TYPE = "resources.stack_create_type";
public static final String STATE_STACK_CREATE_COLLECTION_ID = "resources.stack_create_collection_id";
public static final String STATE_STACK_CREATE_NUMBER = "resources.stack_create_number";
public static final String STATE_STACK_STRUCTOBJ_TYPE = "resources.stack_create_structured_object_type";
public static final String STATE_STACK_STRUCTOBJ_TYPE_READONLY = "resources.stack_create_structured_object_type_readonly";
private static final String STATE_STACK_CREATE_ITEMS = "resources.stack_create_items";
private static final String STATE_STACK_CREATE_ACTUAL_COUNT = "resources.stack_create_actual_count";
private static final String STATE_STACK_STRUCTOBJ_ROOTNAME = "resources.stack_create_structured_object_root";
private static final String STATE_CREATE_ALERTS = "resources.create_alerts";
protected static final String STATE_CREATE_MESSAGE = "resources.create_message";
private static final String STATE_CREATE_MISSING_ITEM = "resources.create_missing_item";
private static final String STATE_STRUCTOBJ_HOMES = "resources.create_structured_object_home";
private static final String STATE_STACK_STRUCT_OBJ_SCHEMA = "resources.stack_create_structured_object_schema";
private static final String MIME_TYPE_DOCUMENT_PLAINTEXT = "text/plain";
private static final String MIME_TYPE_DOCUMENT_HTML = "text/html";
public static final String MIME_TYPE_STRUCTOBJ = "application/x-osp";
public static final String TYPE_FOLDER = "folder";
public static final String TYPE_UPLOAD = "file";
public static final String TYPE_URL = "Url";
public static final String TYPE_FORM = MIME_TYPE_STRUCTOBJ;
public static final String TYPE_HTML = MIME_TYPE_DOCUMENT_HTML;
public static final String TYPE_TEXT = MIME_TYPE_DOCUMENT_PLAINTEXT;
private static final int CREATE_MAX_ITEMS = 10;
private static final int INTEGER_WIDGET_LENGTH = 12;
private static final int DOUBLE_WIDGET_LENGTH = 18;
private static final Pattern INDEXED_FORM_FIELD_PATTERN = Pattern.compile("(.+)\\.(\\d+)");
/************** the metadata extension of edit/create contexts *****************************************/
private static final String STATE_METADATA_GROUPS = "resources.metadata.types";
private static final String INTENT_REVISE_FILE = "revise";
private static final String INTENT_REPLACE_FILE = "replace";
/** State attribute for where there is at least one attachment before invoking attachment tool */
public static final String STATE_HAS_ATTACHMENT_BEFORE = "resources.has_attachment_before";
/** The name of the state attribute containing a list of new items to be attached */
private static final String STATE_HELPER_NEW_ITEMS = "resources.helper_new_items";
/** The name of the state attribute indicating that the list of new items has changed */
private static final String STATE_HELPER_CHANGED = "resources.helper_changed";
/** The name of the optional state attribute indicating the id of the collection that should be treated as the "home" collection */
public static final String STATE_ATTACH_COLLECTION_ID = "resources.attach_collection_id";
/** The name of the state attribute containing the name of the tool that invoked Resources as attachment helper */
public static final String STATE_ATTACH_TOOL_NAME = "resources.attach_tool_name";
/** The name of the state attribute for "new-item" attachment indicating the type of item */
public static final String STATE_ATTACH_TEXT = "resources.attach_text";
/** The name of the state attribute for "new-item" attachment indicating the id of the item to edit */
public static final String STATE_ATTACH_ITEM_ID = "resources.attach_collection_id";
/** The name of the state attribute for "new-item" attachment indicating the id of the form-type if item-type
* is TYPE_FORM (ignored otherwise) */
public static final String STATE_ATTACH_FORM_ID = "resources.attach_form_id";
/** The name of the state attribute indicating which form field a resource should be attached to */
public static final String STATE_ATTACH_FORM_FIELD = "resources.attach_form_field";
/************** the helper context (file-picker) *****************************************/
/**
* State attribute for the Vector of References, one for each attachment.
* Using tools can pre-populate, and can read the results from here.
*/
public static final String STATE_ATTACHMENTS = "resources.state_attachments";
/**
* The name of the state attribute indicating that the file picker should return links to
* existing resources in an existing collection rather than copying it to the hidden attachments
* area. If this value is not set, all attachments are to copies in the hidden attachments area.
*/
public static final String STATE_ATTACH_LINKS = "resources.state_attach_links";
/**
* The name of the state attribute for the maximum number of items to attach. The attribute value will be an Integer,
* usually CARDINALITY_SINGLE or CARDINALITY_MULTIPLE.
*/
public static final String STATE_ATTACH_CARDINALITY = "resources.state_attach_cardinality";
/** A constant indicating maximum of one item can be attached. */
public static final Integer CARDINALITY_SINGLE = FilePickerHelper.CARDINALITY_SINGLE;
/** A constant indicating any the number of attachments is unlimited. */
public static final Integer CARDINALITY_MULTIPLE = FilePickerHelper.CARDINALITY_MULTIPLE;
/**
* The name of the state attribute for the title when a tool uses Resources as attachment helper (for create or attach but not for edit mode)
*/
public static final String STATE_ATTACH_TITLE = "resources.state_attach_title_text";
/**
* The name of the state attribute for the instructions when a tool uses Resources as attachment helper
* (for create or attach but not for edit mode)
*/
public static final String STATE_ATTACH_INSTRUCTION = "resources.state_attach_instruction_text";
/**
* State Attribute for the org.sakaiproject.content.api.ContentResourceFilter
* object that the current filter should honor. If this is set to null, then all files will
* be selectable and viewable
*/
public static final String STATE_ATTACH_FILTER = "resources.state_attach_filter";
/**
* @deprecated use STATE_ATTACH_TITLE and STATE_ATTACH_INSTRUCTION instead
*/
public static final String STATE_FROM_TEXT = "attachment.from_text";
/**
* the name of the state attribute indicating that the user canceled out of the helper. Is set only if the user canceled out of the helper.
*/
public static final String STATE_HELPER_CANCELED_BY_USER = "resources.state_attach_canceled_by_user";
/**
* The name of the state attribute indicating that dropboxes should be shown as places from which
* to select attachments. The value should be a List of user-id's. The file picker will attempt to show
* the dropbox for each user whose id is included in the list. If this
*/
public static final String STATE_ATTACH_SHOW_DROPBOXES = "resources.state_attach_show_dropboxes";
/**
* The name of the state attribute indicating that the current user's workspace Resources collection
* should be shown as places from which to select attachments. The value should be "true". The file picker will attempt to show
* the workspace if this attribute is set to "true".
*/
public static final String STATE_ATTACH_SHOW_WORKSPACE = "resources.state_attach_show_workspace";
/************** the delete context *****************************************/
/** The delete ids */
private static final String STATE_DELETE_IDS = "resources.delete_ids";
/** The not empty delete ids */
private static final String STATE_NOT_EMPTY_DELETE_IDS = "resource.not_empty_delete_ids";
/** The name of the state attribute containing a list of BrowseItem objects corresponding to resources selected for deletion */
private static final String STATE_DELETE_ITEMS = "resources.delete_items";
/** The name of the state attribute containing a list of BrowseItem objects corresponding to nonempty folders selected for deletion */
private static final String STATE_DELETE_ITEMS_NOT_EMPTY = "resources.delete_items_not_empty";
/** The name of the state attribute containing a list of BrowseItem objects selected for deletion that cannot be deleted */
private static final String STATE_DELETE_ITEMS_CANNOT_DELETE = "resources.delete_items_cannot_delete";
/************** the cut items context *****************************************/
/** The cut item ids */
private static final String STATE_CUT_IDS = "resources.revise_cut_ids";
/************** the copied items context *****************************************/
/** The copied item ids */
private static final String STATE_COPIED_IDS = "resources.revise_copied_ids";
/** The copied item id */
private static final String STATE_COPIED_ID = "resources.revise_copied_id";
/************** the moved items context *****************************************/
/** The copied item ids */
private static final String STATE_MOVED_IDS = "resources.revise_moved_ids";
/** Modes. */
private static final String MODE_LIST = "list";
private static final String MODE_EDIT = "edit";
private static final String MODE_DAV = "webdav";
private static final String MODE_CREATE = "create";
public static final String MODE_HELPER = "helper";
private static final String MODE_DELETE_CONFIRM = "deleteConfirm";
private static final String MODE_MORE = "more";
private static final String MODE_PROPERTIES = "properties";
/** modes for attachment helper */
public static final String MODE_ATTACHMENT_SELECT = "resources.attachment_select";
public static final String MODE_ATTACHMENT_CREATE = "resources.attachment_create";
public static final String MODE_ATTACHMENT_NEW_ITEM = "resources.attachment_new_item";
public static final String MODE_ATTACHMENT_EDIT_ITEM = "resources.attachment_edit_item";
public static final String MODE_ATTACHMENT_CONFIRM = "resources.attachment_confirm";
public static final String MODE_ATTACHMENT_SELECT_INIT = "resources.attachment_select_initialized";
public static final String MODE_ATTACHMENT_CREATE_INIT = "resources.attachment_create_initialized";
public static final String MODE_ATTACHMENT_NEW_ITEM_INIT = "resources.attachment_new_item_initialized";
public static final String MODE_ATTACHMENT_EDIT_ITEM_INIT = "resources.attachment_edit_item_initialized";
public static final String MODE_ATTACHMENT_CONFIRM_INIT = "resources.attachment_confirm_initialized";
public static final String MODE_ATTACHMENT_DONE = "resources.attachment_done";
/** vm files for each mode. */
private static final String TEMPLATE_LIST = "content/chef_resources_list";
private static final String TEMPLATE_EDIT = "content/chef_resources_edit";
private static final String TEMPLATE_CREATE = "content/chef_resources_create";
private static final String TEMPLATE_DAV = "content/chef_resources_webdav";
private static final String TEMPLATE_ITEMTYPE = "content/chef_resources_itemtype";
private static final String TEMPLATE_SELECT = "content/chef_resources_select";
private static final String TEMPLATE_ATTACH = "content/chef_resources_attach";
private static final String TEMPLATE_MORE = "content/chef_resources_more";
private static final String TEMPLATE_DELETE_CONFIRM = "content/chef_resources_deleteConfirm";
private static final String TEMPLATE_PROPERTIES = "content/chef_resources_properties";
// private static final String TEMPLATE_REPLACE = "_replace";
/** the site title */
private static final String STATE_SITE_TITLE = "site_title";
/** copyright related info */
private static final String COPYRIGHT_TYPES = "copyright_types";
private static final String COPYRIGHT_TYPE = "copyright_type";
private static final String DEFAULT_COPYRIGHT = "default_copyright";
private static final String COPYRIGHT_ALERT = "copyright_alert";
private static final String DEFAULT_COPYRIGHT_ALERT = "default_copyright_alert";
private static final String COPYRIGHT_FAIRUSE_URL = "copyright_fairuse_url";
private static final String NEW_COPYRIGHT_INPUT = "new_copyright_input";
private static final String COPYRIGHT_SELF_COPYRIGHT = rb.getString("cpright2");
private static final String COPYRIGHT_NEW_COPYRIGHT = rb.getString("cpright3");
private static final String COPYRIGHT_ALERT_URL = ServerConfigurationService.getAccessUrl() + COPYRIGHT_PATH;
/** state attribute indicating whether we're using the Creative Commons dialog instead of the "old" copyright dialog */
protected static final String STATE_USING_CREATIVE_COMMONS = "resources.usingCreativeCommons";
private static final int MAXIMUM_ATTEMPTS_FOR_UNIQUENESS = 100;
/** The default value for whether to show all sites in file-picker (used if global value can't be read from server config service) */
public static final boolean SHOW_ALL_SITES_IN_FILE_PICKER = false;
/** The default value for whether to show all sites in resources tool (used if global value can't be read from server config service) */
private static final boolean SHOW_ALL_SITES_IN_RESOURCES = false;
/** The default value for whether to show all sites in dropbox (used if global value can't be read from server config service) */
private static final boolean SHOW_ALL_SITES_IN_DROPBOX = false;
/** The number of members for a collection at which this tool should refuse to expand the collection */
protected static final int EXPANDABLE_FOLDER_SIZE_LIMIT = 256;
protected static final String STATE_SHOW_REMOVE_ACTION = "resources.show_remove_action";
protected static final String STATE_SHOW_MOVE_ACTION = "resources.show_move_action";
protected static final String STATE_SHOW_COPY_ACTION = "resources.show_copy_action";
protected static final String STATE_HIGHLIGHTED_ITEMS = "resources.highlighted_items";
/** The default number of site collections per page. */
protected static final int DEFAULT_PAGE_SIZE = 50;
protected static final String PARAM_PAGESIZE = "collections_per_page";
protected static final String STATE_TOP_MESSAGE_INDEX = "resources.top_message_index";
protected static final String STATE_REMOVED_ATTACHMENTS = "resources.removed_attachments";
/********* Global constants *********/
/** The null/empty string */
private static final String NULL_STRING = "";
/** The string used when pasting the same resource to the same folder */
private static final String DUPLICATE_STRING = rb.getString("copyof") + " ";
/** The string used when pasting shirtcut of the same resource to the same folder */
private static final String SHORTCUT_STRING = rb.getString("shortcut");
/** The copyright character (Note: could be "\u00a9" if we supported UNICODE for specials -ggolden */
private static final String COPYRIGHT_SYMBOL = rb.getString("cpright1");
/** The String of new copyright */
private static final String NEW_COPYRIGHT = "newcopyright";
/** The resource not exist string */
private static final String RESOURCE_NOT_EXIST_STRING = rb.getString("notexist1");
/** The title invalid string */
private static final String RESOURCE_INVALID_TITLE_STRING = rb.getString("titlecannot");
/** The copy, cut, paste not operate on collection string */
private static final String RESOURCE_INVALID_OPERATION_ON_COLLECTION_STRING = rb.getString("notsupported");
/** The maximum number of suspended operations that can be on the stack. */
private static final int MAXIMUM_SUSPENDED_OPERATIONS_STACK_DEPTH = 10;
/** portlet configuration parameter values**/
public static final String RESOURCES_MODE_RESOURCES = "resources";
public static final String RESOURCES_MODE_DROPBOX = "dropbox";
public static final String RESOURCES_MODE_HELPER = "helper";
/** The from state name */
private static final String STATE_FROM = "resources.from";
private static final String STATE_ENCODING = "resources.encoding";
private static final String DELIM = "@";
/**
* Build the context for normal display
*/
public String buildMainPanelContext ( VelocityPortlet portlet,
Context context,
RunData data,
SessionState state)
{
context.put("tlang",rb);
// find the ContentTypeImage service
context.put ("contentTypeImageService", state.getAttribute (STATE_CONTENT_TYPE_IMAGE_SERVICE));
context.put("copyright_alert_url", COPYRIGHT_ALERT_URL);
String template = null;
// place if notification is enabled and current site is not of My Workspace type
boolean isUserSite = SiteService.isUserSite(ToolManager.getCurrentPlacement().getContext());
context.put("notification", new Boolean(!isUserSite && notificationEnabled(state)));
// get the mode
String mode = (String) state.getAttribute (STATE_MODE);
String helper_mode = (String) state.getAttribute(ResourcesAction.STATE_RESOURCES_HELPER_MODE);
if (!MODE_HELPER.equals(mode) && helper_mode != null)
{
// not in helper mode, but a helper context is needed
// if the mode is not done, defer to the helper context
if (!mode.equals(ResourcesAction.MODE_ATTACHMENT_DONE))
{
template = ResourcesAction.buildHelperContext(portlet, context, data, state);
// template = AttachmentAction.buildHelperContext(portlet, context, runData, sstate);
return template;
}
// clean up
state.removeAttribute(ResourcesAction.STATE_RESOURCES_HELPER_MODE);
state.removeAttribute(ResourcesAction.STATE_ATTACHMENTS);
}
if (mode.equals (MODE_LIST))
{
// build the context for add item
template = buildListContext (portlet, context, data, state);
}
else if (mode.equals (MODE_HELPER))
{
// build the context for add item
template = buildHelperContext (portlet, context, data, state);
}
else if (mode.equals (MODE_CREATE))
{
// build the context for add item
template = buildCreateContext (portlet, context, data, state);
}
else if (mode.equals (MODE_DELETE_CONFIRM))
{
// build the context for the basic step of delete confirm page
template = buildDeleteConfirmContext (portlet, context, data, state);
}
else if (mode.equals (MODE_MORE))
{
// build the context to display the property list
template = buildMoreContext (portlet, context, data, state);
}
else if (mode.equals (MODE_EDIT))
{
// build the context to display the property list
template = buildEditContext (portlet, context, data, state);
}
else if (mode.equals (MODE_OPTIONS))
{
template = buildOptionsPanelContext (portlet, context, data, state);
}
else if(mode.equals(MODE_DAV))
{
template = buildWebdavContext (portlet, context, data, state);
}
return template;
} // buildMainPanelContext
/**
* Build the context for the list view
*/
public String buildListContext ( VelocityPortlet portlet,
Context context,
RunData data,
SessionState state)
{
context.put("tlang",rb);
context.put("expandedCollections", state.getAttribute(STATE_EXPANDED_COLLECTIONS));
// find the ContentTypeImage service
context.put ("contentTypeImageService", state.getAttribute (STATE_CONTENT_TYPE_IMAGE_SERVICE));
context.put("TYPE_FOLDER", TYPE_FOLDER);
context.put("TYPE_UPLOAD", TYPE_UPLOAD);
Set selectedItems = (Set) state.getAttribute(STATE_LIST_SELECTIONS);
if(selectedItems == null)
{
selectedItems = new TreeSet();
state.setAttribute(STATE_LIST_SELECTIONS, selectedItems);
}
context.put("selectedItems", selectedItems);
// find the ContentHosting service
org.sakaiproject.content.api.ContentHostingService contentService = (org.sakaiproject.content.api.ContentHostingService) state.getAttribute (STATE_CONTENT_SERVICE);
context.put ("service", contentService);
boolean inMyWorkspace = SiteService.isUserSite(ToolManager.getCurrentPlacement().getContext());
context.put("inMyWorkspace", Boolean.toString(inMyWorkspace));
boolean atHome = false;
// %%STATE_MODE_RESOURCES%%
boolean dropboxMode = RESOURCES_MODE_DROPBOX.equalsIgnoreCase((String) state.getAttribute(STATE_MODE_RESOURCES));
if (dropboxMode)
{
// notshow the public option or notification when in dropbox mode
context.put("dropboxMode", Boolean.TRUE);
}
else
{
//context.put("dropboxMode", Boolean.FALSE);
}
// make sure the channedId is set
String collectionId = (String) state.getAttribute (STATE_COLLECTION_ID);
context.put ("collectionId", collectionId);
String navRoot = (String) state.getAttribute(STATE_NAVIGATION_ROOT);
String homeCollectionId = (String) state.getAttribute(STATE_HOME_COLLECTION_ID);
String siteTitle = (String) state.getAttribute (STATE_SITE_TITLE);
if (collectionId.equals(homeCollectionId))
{
atHome = true;
context.put ("collectionDisplayName", state.getAttribute (STATE_HOME_COLLECTION_DISPLAY_NAME));
}
else
{
// should be not PermissionException thrown at this time, when the user can successfully navigate to this collection
try
{
context.put("collectionDisplayName", contentService.getCollection(collectionId).getProperties().getProperty(ResourceProperties.PROP_DISPLAY_NAME));
}
catch (IdUnusedException e){}
catch (TypeException e) {}
catch (PermissionException e) {}
}
if(!inMyWorkspace && !dropboxMode && atHome && SiteService.allowUpdateSite(ToolManager.getCurrentPlacement().getContext()))
{
context.put("showPermissions", Boolean.TRUE.toString());
//buildListMenu(portlet, context, data, state);
}
context.put("atHome", Boolean.toString(atHome));
List cPath = getCollectionPath(state);
context.put ("collectionPath", cPath);
// set the sort values
String sortedBy = (String) state.getAttribute (STATE_SORT_BY);
String sortedAsc = (String) state.getAttribute (STATE_SORT_ASC);
context.put ("currentSortedBy", sortedBy);
context.put ("currentSortAsc", sortedAsc);
context.put("TRUE", Boolean.TRUE.toString());
boolean showRemoveAction = false;
boolean showMoveAction = false;
boolean showCopyAction = false;
Set highlightedItems = new TreeSet();
try
{
try
{
contentService.checkCollection (collectionId);
context.put ("collectionFlag", Boolean.TRUE.toString());
}
catch(IdUnusedException ex)
{
Log.error("chef", this + "IdUnusedException: " + collectionId);
try
{
ContentCollectionEdit coll = contentService.addCollection(collectionId);
contentService.commitCollection(coll);
}
catch(IdUsedException inner)
{
// how can this happen??
Log.error("chef", this + "IdUsedException: " + collectionId);
throw ex;
}
catch(IdInvalidException inner)
{
Log.error("chef", this + "IdInvalidException: " + collectionId);
// what now?
throw ex;
}
catch(InconsistentException inner)
{
Log.error("chef", this + "InconsistentException: " + collectionId);
// what now?
throw ex;
}
}
catch(TypeException ex)
{
Log.error("chef", this + "TypeException.");
throw ex;
}
catch(PermissionException ex)
{
Log.error("chef", this + "PermissionException.");
throw ex;
}
String copyFlag = (String) state.getAttribute (STATE_COPY_FLAG);
if (copyFlag.equals (Boolean.TRUE.toString()))
{
context.put ("copyFlag", copyFlag);
List copiedItems = (List) state.getAttribute(STATE_COPIED_IDS);
// context.put ("copiedItem", state.getAttribute (STATE_COPIED_ID));
highlightedItems.addAll(copiedItems);
// context.put("copiedItems", copiedItems);
}
String moveFlag = (String) state.getAttribute (STATE_MOVE_FLAG);
if (moveFlag.equals (Boolean.TRUE.toString()))
{
context.put ("moveFlag", moveFlag);
List movedItems = (List) state.getAttribute(STATE_MOVED_IDS);
highlightedItems.addAll(movedItems);
// context.put ("copiedItem", state.getAttribute (STATE_COPIED_ID));
// context.put("movedItems", movedItems);
}
HashMap expandedCollections = (HashMap) state.getAttribute(STATE_EXPANDED_COLLECTIONS);
ContentCollection coll = contentService.getCollection(collectionId);
expandedCollections.put(collectionId, coll);
state.removeAttribute(STATE_PASTE_ALLOWED_FLAG);
List all_roots = new Vector();
List this_site = new Vector();
List members = getBrowseItems(collectionId, expandedCollections, highlightedItems, sortedBy, sortedAsc, (BrowseItem) null, navRoot.equals(homeCollectionId), state);
if(members != null && members.size() > 0)
{
BrowseItem root = (BrowseItem) members.remove(0);
showRemoveAction = showRemoveAction || root.hasDeletableChildren();
showMoveAction = showMoveAction || root.hasDeletableChildren();
showCopyAction = showCopyAction || root.hasCopyableChildren();
if(atHome && dropboxMode)
{
root.setName(siteTitle + " " + rb.getString("gen.drop"));
}
else if(atHome)
{
root.setName(siteTitle + " " + rb.getString("gen.reso"));
}
context.put("site", root);
root.addMembers(members);
this_site.add(root);
all_roots.add(root);
}
context.put ("this_site", this_site);
boolean show_all_sites = false;
List other_sites = new Vector();
String allowed_to_see_other_sites = (String) state.getAttribute(STATE_SHOW_ALL_SITES);
String show_other_sites = (String) state.getAttribute(STATE_SHOW_OTHER_SITES);
context.put("show_other_sites", show_other_sites);
if(Boolean.TRUE.toString().equals(allowed_to_see_other_sites))
{
context.put("allowed_to_see_other_sites", Boolean.TRUE.toString());
show_all_sites = Boolean.TRUE.toString().equals(show_other_sites);
}
if(atHome && show_all_sites)
{
state.setAttribute(STATE_HIGHLIGHTED_ITEMS, highlightedItems);
// TODO: see call to prepPage below. That also calls readAllResources. Are both calls necessary?
other_sites.addAll(readAllResources(state));
all_roots.addAll(other_sites);
List messages = prepPage(state);
context.put("other_sites", messages);
if (state.getAttribute(STATE_NUM_MESSAGES) != null)
{
context.put("allMsgNumber", state.getAttribute(STATE_NUM_MESSAGES).toString());
context.put("allMsgNumberInt", state.getAttribute(STATE_NUM_MESSAGES));
}
context.put("pagesize", ((Integer) state.getAttribute(STATE_PAGESIZE)).toString());
// find the position of the message that is the top first on the page
if ((state.getAttribute(STATE_TOP_MESSAGE_INDEX) != null) && (state.getAttribute(STATE_PAGESIZE) != null))
{
int topMsgPos = ((Integer)state.getAttribute(STATE_TOP_MESSAGE_INDEX)).intValue() + 1;
context.put("topMsgPos", Integer.toString(topMsgPos));
int btmMsgPos = topMsgPos + ((Integer)state.getAttribute(STATE_PAGESIZE)).intValue() - 1;
if (state.getAttribute(STATE_NUM_MESSAGES) != null)
{
int allMsgNumber = ((Integer)state.getAttribute(STATE_NUM_MESSAGES)).intValue();
if (btmMsgPos > allMsgNumber)
btmMsgPos = allMsgNumber;
}
context.put("btmMsgPos", Integer.toString(btmMsgPos));
}
boolean goPPButton = state.getAttribute(STATE_PREV_PAGE_EXISTS) != null;
context.put("goPPButton", Boolean.toString(goPPButton));
boolean goNPButton = state.getAttribute(STATE_NEXT_PAGE_EXISTS) != null;
context.put("goNPButton", Boolean.toString(goNPButton));
/*
boolean goFPButton = state.getAttribute(STATE_FIRST_PAGE_EXISTS) != null;
context.put("goFPButton", Boolean.toString(goFPButton));
boolean goLPButton = state.getAttribute(STATE_LAST_PAGE_EXISTS) != null;
context.put("goLPButton", Boolean.toString(goLPButton));
*/
context.put("pagesize", state.getAttribute(STATE_PAGESIZE));
// context.put("pagesizes", PAGESIZES);
}
// context.put ("other_sites", other_sites);
state.setAttribute(STATE_COLLECTION_ROOTS, all_roots);
// context.put ("root", root);
if(state.getAttribute(STATE_PASTE_ALLOWED_FLAG) != null)
{
context.put("paste_place_showing", state.getAttribute(STATE_PASTE_ALLOWED_FLAG));
}
if(showRemoveAction)
{
context.put("showRemoveAction", Boolean.TRUE.toString());
}
if(showMoveAction)
{
context.put("showMoveAction", Boolean.TRUE.toString());
}
if(showCopyAction)
{
context.put("showCopyAction", Boolean.TRUE.toString());
}
}
catch (IdUnusedException e)
{
addAlert(state, rb.getString("cannotfind"));
context.put ("collectionFlag", Boolean.FALSE.toString());
}
catch(TypeException e)
{
Log.error("chef", this + "TypeException.");
context.put ("collectionFlag", Boolean.FALSE.toString());
}
catch(PermissionException e)
{
addAlert(state, rb.getString("notpermis1"));
context.put ("collectionFlag", Boolean.FALSE.toString());
}
context.put("homeCollection", (String) state.getAttribute (STATE_HOME_COLLECTION_ID));
context.put("siteTitle", state.getAttribute(STATE_SITE_TITLE));
context.put ("resourceProperties", contentService.newResourceProperties ());
try
{
// TODO: why 'site' here?
Site site = SiteService.getSite(ToolManager.getCurrentPlacement().getContext());
context.put("siteTitle", site.getTitle());
}
catch (IdUnusedException e)
{
// Log.error("chef", this + e.toString());
}
context.put("expandallflag", state.getAttribute(STATE_EXPAND_ALL_FLAG));
state.removeAttribute(STATE_NEED_TO_EXPAND_ALL);
// inform the observing courier that we just updated the page...
// if there are pending requests to do so they can be cleared
justDelivered(state);
// pick the "show" template based on the standard template name
// String template = (String) getContext(data).get("template");
return TEMPLATE_LIST;
} // buildListContext
/**
* Build the context for the helper view
*/
public static String buildHelperContext ( VelocityPortlet portlet,
Context context,
RunData data,
SessionState state)
{
if(state.getAttribute(STATE_INITIALIZED) == null)
{
initStateAttributes(state, portlet);
if(state.getAttribute(ResourcesAction.STATE_HELPER_CANCELED_BY_USER) != null)
{
state.removeAttribute(ResourcesAction.STATE_HELPER_CANCELED_BY_USER);
}
}
String mode = (String) state.getAttribute(STATE_MODE);
if(state.getAttribute(STATE_MODE_RESOURCES) == null && MODE_HELPER.equals(mode))
{
state.setAttribute(ResourcesAction.STATE_MODE_RESOURCES, ResourcesAction.MODE_HELPER);
}
Set selectedItems = (Set) state.getAttribute(STATE_LIST_SELECTIONS);
if(selectedItems == null)
{
selectedItems = new TreeSet();
state.setAttribute(STATE_LIST_SELECTIONS, selectedItems);
}
context.put("selectedItems", selectedItems);
String helper_mode = (String) state.getAttribute(STATE_RESOURCES_HELPER_MODE);
boolean need_to_push = false;
if(MODE_ATTACHMENT_SELECT.equals(helper_mode))
{
need_to_push = true;
helper_mode = MODE_ATTACHMENT_SELECT_INIT;
}
else if(MODE_ATTACHMENT_CREATE.equals(helper_mode))
{
need_to_push = true;
helper_mode = MODE_ATTACHMENT_CREATE_INIT;
}
else if(MODE_ATTACHMENT_NEW_ITEM.equals(helper_mode))
{
need_to_push = true;
helper_mode = MODE_ATTACHMENT_NEW_ITEM_INIT;
}
else if(MODE_ATTACHMENT_EDIT_ITEM.equals(helper_mode))
{
need_to_push = true;
helper_mode = MODE_ATTACHMENT_EDIT_ITEM_INIT;
}
Map current_stack_frame = null;
if(need_to_push)
{
current_stack_frame = pushOnStack(state);
current_stack_frame.put(STATE_STACK_EDIT_INTENT, INTENT_REVISE_FILE);
state.setAttribute(VelocityPortletPaneledAction.STATE_HELPER, ResourcesAction.class.getName());
state.setAttribute(STATE_RESOURCES_HELPER_MODE, helper_mode);
if(MODE_ATTACHMENT_EDIT_ITEM_INIT.equals(helper_mode))
{
String attachmentId = (String) state.getAttribute(STATE_EDIT_ID);
if(attachmentId != null)
{
current_stack_frame.put(STATE_STACK_EDIT_ID, attachmentId);
String collectionId = ContentHostingService.getContainingCollectionId(attachmentId);
current_stack_frame.put(STATE_STACK_EDIT_COLLECTION_ID, collectionId);
EditItem item = getEditItem(attachmentId, collectionId, data);
if (state.getAttribute(STATE_MESSAGE) == null)
{
// got resource and sucessfully populated item with values
state.setAttribute(STATE_EDIT_ALERTS, new HashSet());
current_stack_frame.put(STATE_STACK_EDIT_ITEM, item);
}
}
}
else
{
List attachments = (List) state.getAttribute(STATE_ATTACHMENTS);
if(attachments == null)
{
attachments = EntityManager.newReferenceList();
}
List attached = new Vector();
Iterator it = attachments.iterator();
while(it.hasNext())
{
try
{
Reference ref = (Reference) it.next();
String itemId = ref.getId();
ResourceProperties properties = ref.getProperties();
String displayName = properties.getProperty(ResourceProperties.PROP_DISPLAY_NAME);
String containerId = ref.getContainer();
String accessUrl = ContentHostingService.getUrl(itemId);
String contentType = properties.getProperty(ResourceProperties.PROP_CONTENT_TYPE);
AttachItem item = new AttachItem(itemId, displayName, containerId, accessUrl);
item.setContentType(contentType);
attached.add(item);
}
catch(Exception ignore) {}
}
current_stack_frame.put(STATE_HELPER_NEW_ITEMS, attached);
}
}
else
{
current_stack_frame = peekAtStack(state);
if(current_stack_frame.get(STATE_STACK_EDIT_INTENT) == null)
{
current_stack_frame.put(STATE_STACK_EDIT_INTENT, INTENT_REVISE_FILE);
}
}
if(helper_mode == null)
{
helper_mode = (String) current_stack_frame.get(STATE_RESOURCES_HELPER_MODE);
}
else
{
current_stack_frame.put(STATE_RESOURCES_HELPER_MODE, helper_mode);
}
String helper_title = (String) current_stack_frame.get(STATE_ATTACH_TITLE);
if(helper_title == null)
{
helper_title = (String) state.getAttribute(STATE_ATTACH_TITLE);
if(helper_title != null)
{
current_stack_frame.put(STATE_ATTACH_TITLE, helper_title);
}
}
if(helper_title != null)
{
context.put("helper_title", helper_title);
}
String helper_instruction = (String) current_stack_frame.get(STATE_ATTACH_INSTRUCTION);
if(helper_instruction == null)
{
helper_instruction = (String) state.getAttribute(STATE_ATTACH_INSTRUCTION);
if(helper_instruction != null)
{
current_stack_frame.put(STATE_ATTACH_INSTRUCTION, helper_instruction);
}
}
if(helper_instruction != null)
{
context.put("helper_instruction", helper_instruction);
}
String title = (String) current_stack_frame.get(STATE_STACK_EDIT_ITEM_TITLE);
if(title == null)
{
title = (String) state.getAttribute(STATE_ATTACH_TEXT);
if(title != null)
{
current_stack_frame.put(STATE_STACK_EDIT_ITEM_TITLE, title);
}
}
if(title != null && title.trim().length() > 0)
{
context.put("helper_subtitle", title);
}
String template = null;
if(MODE_ATTACHMENT_SELECT_INIT.equals(helper_mode))
{
template = buildSelectAttachmentContext(portlet, context, data, state);
}
else if(MODE_ATTACHMENT_CREATE_INIT.equals(helper_mode))
{
template = buildCreateContext(portlet, context, data, state);
}
else if(MODE_ATTACHMENT_NEW_ITEM_INIT.equals(helper_mode))
{
template = buildItemTypeContext(portlet, context, data, state);
}
else if(MODE_ATTACHMENT_EDIT_ITEM_INIT.equals(helper_mode))
{
template = buildEditContext(portlet, context, data, state);
}
return template;
}
public static String buildItemTypeContext(VelocityPortlet portlet, Context context, RunData data, SessionState state)
{
context.put("tlang",rb);
initStateAttributes(state, portlet);
Map current_stack_frame = peekAtStack(state);
String mode = (String) state.getAttribute(STATE_MODE);
if(mode == null || mode.trim().length() == 0)
{
mode = MODE_HELPER;
state.setAttribute(STATE_MODE, mode);
}
String helper_mode = null;
if(MODE_HELPER.equals(mode))
{
helper_mode = (String) state.getAttribute(STATE_RESOURCES_HELPER_MODE);
if(helper_mode == null || helper_mode.trim().length() == 0)
{
helper_mode = MODE_ATTACHMENT_NEW_ITEM;
state.setAttribute(STATE_RESOURCES_HELPER_MODE, helper_mode);
}
current_stack_frame.put(STATE_RESOURCES_HELPER_MODE, helper_mode);
if(MODE_ATTACHMENT_NEW_ITEM_INIT.equals(helper_mode))
{
context.put("attaching_this_item", Boolean.TRUE.toString());
}
state.setAttribute(VelocityPortletPaneledAction.STATE_HELPER, ResourcesAction.class.getName());
}
String msg = (String) state.getAttribute(STATE_CREATE_MESSAGE);
if (msg != null)
{
context.put("itemAlertMessage", msg);
state.removeAttribute(STATE_CREATE_MESSAGE);
}
context.put("max_upload_size", state.getAttribute(STATE_FILE_UPLOAD_MAX_SIZE));
String collectionId = (String) current_stack_frame.get(STATE_STACK_CREATE_COLLECTION_ID);
if(collectionId == null || collectionId.trim().length() == 0)
{
collectionId = (String) state.getAttribute(STATE_CREATE_COLLECTION_ID);
if(collectionId == null || collectionId.trim().length() == 0)
{
collectionId = ContentHostingService.getSiteCollection(ToolManager.getCurrentPlacement().getContext());
}
current_stack_frame.put(STATE_STACK_CREATE_COLLECTION_ID, collectionId);
}
context.put("collectionId", collectionId);
String itemType = (String) current_stack_frame.get(STATE_STACK_CREATE_TYPE);
if(itemType == null || "".equals(itemType))
{
itemType = (String) state.getAttribute(STATE_CREATE_TYPE);
if(itemType == null || "".equals(itemType))
{
itemType = TYPE_UPLOAD;
}
current_stack_frame.put(STATE_STACK_CREATE_TYPE, itemType);
}
context.put("itemType", itemType);
Integer numberOfItems = (Integer) current_stack_frame.get(STATE_STACK_CREATE_NUMBER);
if(numberOfItems == null)
{
numberOfItems = (Integer) state.getAttribute(STATE_CREATE_NUMBER);
current_stack_frame.put(STATE_STACK_CREATE_NUMBER, numberOfItems);
}
if(numberOfItems == null)
{
numberOfItems = new Integer(1);
current_stack_frame.put(STATE_STACK_CREATE_NUMBER, numberOfItems);
}
context.put("numberOfItems", numberOfItems);
context.put("max_number", new Integer(1));
Collection groups = ContentHostingService.getGroupsWithReadAccess(collectionId);
// TODO: does this method filter groups for this subcollection??
if(! groups.isEmpty())
{
context.put("siteHasGroups", Boolean.TRUE.toString());
}
List new_items = (List) current_stack_frame.get(STATE_STACK_CREATE_ITEMS);
if(new_items == null)
{
String defaultCopyrightStatus = (String) state.getAttribute(DEFAULT_COPYRIGHT);
if(defaultCopyrightStatus == null || defaultCopyrightStatus.trim().equals(""))
{
defaultCopyrightStatus = ServerConfigurationService.getString("default.copyright");
state.setAttribute(DEFAULT_COPYRIGHT, defaultCopyrightStatus);
}
Site site;
try {
site = SiteService.getSite(ToolManager.getCurrentPlacement().getContext());
} catch (IdUnusedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
String encoding = data.getRequest().getCharacterEncoding();
List inherited_access_groups = new Vector();
AccessMode inherited_access = AccessMode.INHERITED;
try
{
ContentCollection parent = ContentHostingService.getCollection(collectionId);
inherited_access = parent.getInheritedAccess();
inherited_access_groups.addAll(parent.getInheritedGroups());
}
catch (IdUnusedException e)
{
}
catch (TypeException e)
{
}
catch (PermissionException e)
{
}
new_items = new Vector();
List theGroupsInThisSite = new Vector();
for(int i = 0; i < CREATE_MAX_ITEMS; i++)
{
EditItem item = new EditItem(itemType);
if(encoding != null)
{
item.setEncoding(encoding);
}
item.setCopyrightStatus(defaultCopyrightStatus);
new_items.add(item);
theGroupsInThisSite.add(new Vector(groups));
if(inherited_access_groups != null)
{
item.setInheritedGroups(inherited_access_groups);
}
if(inherited_access == null || inherited_access.equals(AccessMode.SITE))
{
item.setInheritedAccess(AccessMode.INHERITED.toString());
}
else
{
item.setInheritedAccess(inherited_access.toString());
}
}
context.put("theGroupsInThisSite", theGroupsInThisSite);
}
context.put("new_items", new_items);
current_stack_frame.put(STATE_STACK_CREATE_ITEMS, new_items);
String show_form_items = (String) current_stack_frame.get(STATE_SHOW_FORM_ITEMS);
if(show_form_items == null)
{
show_form_items = (String) state.getAttribute(STATE_SHOW_FORM_ITEMS);
if(show_form_items != null)
{
current_stack_frame.put(STATE_SHOW_FORM_ITEMS,show_form_items);
}
}
if(show_form_items != null)
{
context.put("show_form_items", show_form_items);
}
context.put("TYPE_FOLDER", TYPE_FOLDER);
context.put("TYPE_UPLOAD", TYPE_UPLOAD);
context.put("TYPE_HTML", TYPE_HTML);
context.put("TYPE_TEXT", TYPE_TEXT);
context.put("TYPE_URL", TYPE_URL);
context.put("TYPE_FORM", TYPE_FORM);
// copyright
copyrightChoicesIntoContext(state, context);
// put schema for metadata into context
metadataGroupsIntoContext(state, context);
if(TYPE_FORM.equals(itemType))
{
List listOfHomes = (List) current_stack_frame.get(STATE_STRUCTOBJ_HOMES);
if(listOfHomes == null)
{
setupStructuredObjects(state);
listOfHomes = (List) current_stack_frame.get(STATE_STRUCTOBJ_HOMES);
}
context.put("homes", listOfHomes);
String formtype = (String) current_stack_frame.get(STATE_STACK_STRUCTOBJ_TYPE);
if(formtype == null)
{
formtype = (String) state.getAttribute(STATE_STRUCTOBJ_TYPE);
if(formtype == null)
{
formtype = "";
}
current_stack_frame.put(STATE_STACK_STRUCTOBJ_TYPE, formtype);
}
context.put("formtype", formtype);
String formtype_readonly = (String) current_stack_frame.get(STATE_STACK_STRUCTOBJ_TYPE_READONLY);
if(formtype_readonly == null)
{
formtype_readonly = (String) state.getAttribute(STATE_STRUCTOBJ_TYPE_READONLY);
if(formtype_readonly == null)
{
formtype_readonly = Boolean.FALSE.toString();
}
current_stack_frame.put(STATE_STACK_STRUCTOBJ_TYPE_READONLY, formtype_readonly);
}
if(formtype_readonly != null && formtype_readonly.equals(Boolean.TRUE.toString()))
{
context.put("formtype_readonly", formtype_readonly);
}
String rootname = (String) current_stack_frame.get(STATE_STACK_STRUCTOBJ_ROOTNAME);
context.put("rootname", rootname);
context.put("STRING", ResourcesMetadata.WIDGET_STRING);
context.put("TEXTAREA", ResourcesMetadata.WIDGET_TEXTAREA);
context.put("BOOLEAN", ResourcesMetadata.WIDGET_BOOLEAN);
context.put("INTEGER", ResourcesMetadata.WIDGET_INTEGER);
context.put("DOUBLE", ResourcesMetadata.WIDGET_DOUBLE);
context.put("DATE", ResourcesMetadata.WIDGET_DATE);
context.put("TIME", ResourcesMetadata.WIDGET_TIME);
context.put("DATETIME", ResourcesMetadata.WIDGET_DATETIME);
context.put("ANYURI", ResourcesMetadata.WIDGET_ANYURI);
context.put("ENUM", ResourcesMetadata.WIDGET_ENUM);
context.put("NESTED", ResourcesMetadata.WIDGET_NESTED);
context.put("WYSIWYG", ResourcesMetadata.WIDGET_WYSIWYG);
context.put("today", TimeService.newTime());
context.put("DOT", ResourcesMetadata.DOT);
}
return TEMPLATE_ITEMTYPE;
}
/**
* Access the top item on the suspended-operations stack
* @param state The current session state, including the STATE_SUSPENDED_OPERATIONS_STACK attribute.
* @return The top item on the stack, or null if the stack is empty.
*/
private static Map peekAtStack(SessionState state)
{
Map current_stack_frame = null;
Stack operations_stack = (Stack) state.getAttribute(STATE_SUSPENDED_OPERATIONS_STACK);
if(operations_stack == null)
{
operations_stack = new Stack();
state.setAttribute(STATE_SUSPENDED_OPERATIONS_STACK, operations_stack);
}
if(! operations_stack.isEmpty())
{
current_stack_frame = (Map) operations_stack.peek();
}
return current_stack_frame;
}
/**
* Returns true if the suspended operations stack contains no elements.
* @param state The current session state, including the STATE_SUSPENDED_OPERATIONS_STACK attribute.
* @return true if the suspended operations stack contains no elements
*/
private static boolean isStackEmpty(SessionState state)
{
Stack operations_stack = (Stack) state.getAttribute(STATE_SUSPENDED_OPERATIONS_STACK);
if(operations_stack == null)
{
operations_stack = new Stack();
state.setAttribute(STATE_SUSPENDED_OPERATIONS_STACK, operations_stack);
}
return operations_stack.isEmpty();
}
/**
* Push an item of the suspended-operations stack.
* @param state The current session state, including the STATE_SUSPENDED_OPERATIONS_STACK attribute.
* @return The new item that has just been added to the stack, or null if depth limit is exceeded.
*/
private static Map pushOnStack(SessionState state)
{
Map current_stack_frame = null;
Stack operations_stack = (Stack) state.getAttribute(STATE_SUSPENDED_OPERATIONS_STACK);
if(operations_stack == null)
{
operations_stack = new Stack();
state.setAttribute(STATE_SUSPENDED_OPERATIONS_STACK, operations_stack);
}
if(operations_stack.size() < MAXIMUM_SUSPENDED_OPERATIONS_STACK_DEPTH)
{
current_stack_frame = (Map) operations_stack.push(new Hashtable());
}
Object helper_mode = state.getAttribute(STATE_RESOURCES_HELPER_MODE);
if(helper_mode != null)
{
current_stack_frame.put(STATE_RESOURCES_HELPER_MODE, helper_mode);
}
return current_stack_frame;
}
/**
* Remove and return the top item from the suspended-operations stack.
* @param state The current session state, including the STATE_SUSPENDED_OPERATIONS_STACK attribute.
* @return The item that has just been removed from the stack, or null if the stack was empty.
*/
private static Map popFromStack(SessionState state)
{
Map current_stack_frame = null;
Stack operations_stack = (Stack) state.getAttribute(STATE_SUSPENDED_OPERATIONS_STACK);
if(operations_stack == null)
{
operations_stack = new Stack();
state.setAttribute(STATE_SUSPENDED_OPERATIONS_STACK, operations_stack);
}
if(! operations_stack.isEmpty())
{
current_stack_frame = (Map) operations_stack.pop();
if(operations_stack.isEmpty())
{
String canceled = (String) current_stack_frame.get(STATE_HELPER_CANCELED_BY_USER);
if(canceled != null)
{
state.setAttribute(STATE_HELPER_CANCELED_BY_USER, canceled);
}
}
}
return current_stack_frame;
}
private static void resetCurrentMode(SessionState state)
{
String mode = (String) state.getAttribute(STATE_MODE);
if(isStackEmpty(state))
{
if(MODE_HELPER.equals(mode))
{
cleanupState(state);
state.setAttribute(STATE_RESOURCES_HELPER_MODE, MODE_ATTACHMENT_DONE);
}
else
{
state.setAttribute(STATE_MODE, MODE_LIST);
state.removeAttribute(STATE_RESOURCES_HELPER_MODE);
}
return;
}
Map current_stack_frame = peekAtStack(state);
String helper_mode = (String) current_stack_frame.get(STATE_RESOURCES_HELPER_MODE);
if(helper_mode != null)
{
state.setAttribute(STATE_RESOURCES_HELPER_MODE, helper_mode);
}
}
/**
* Build the context for selecting attachments
*/
public static String buildSelectAttachmentContext ( VelocityPortlet portlet,
Context context,
RunData data,
SessionState state)
{
context.put("tlang",rb);
initStateAttributes(state, portlet);
Map current_stack_frame = peekAtStack(state);
if(current_stack_frame == null)
{
current_stack_frame = pushOnStack(state);
}
state.setAttribute(VelocityPortletPaneledAction.STATE_HELPER, ResourcesAction.class.getName());
Set highlightedItems = new TreeSet();
List new_items = (List) current_stack_frame.get(STATE_HELPER_NEW_ITEMS);
if(new_items == null)
{
new_items = (List) state.getAttribute(STATE_HELPER_NEW_ITEMS);
if(new_items == null)
{
new_items = new Vector();
}
current_stack_frame.put(STATE_HELPER_NEW_ITEMS, new_items);
}
context.put("attached", new_items);
context.put("last", new Integer(new_items.size() - 1));
Integer max_cardinality = (Integer) current_stack_frame.get(STATE_ATTACH_CARDINALITY);
if(max_cardinality == null)
{
max_cardinality = (Integer) state.getAttribute(STATE_ATTACH_CARDINALITY);
if(max_cardinality == null)
{
max_cardinality = CARDINALITY_MULTIPLE;
}
current_stack_frame.put(STATE_ATTACH_CARDINALITY, max_cardinality);
}
context.put("max_cardinality", max_cardinality);
if(new_items.size() >= max_cardinality.intValue())
{
context.put("disable_attach_links", Boolean.TRUE.toString());
}
if(state.getAttribute(STATE_HELPER_CHANGED) != null)
{
context.put("list_has_changed", "true");
}
String form_field = (String) current_stack_frame.get(ResourcesAction.STATE_ATTACH_FORM_FIELD);
if(form_field == null)
{
form_field = (String) state.getAttribute(ResourcesAction.STATE_ATTACH_FORM_FIELD);
if(form_field != null)
{
current_stack_frame.put(ResourcesAction.STATE_ATTACH_FORM_FIELD, form_field);
state.removeAttribute(ResourcesAction.STATE_ATTACH_FORM_FIELD);
}
}
// find the ContentTypeImage service
context.put ("contentTypeImageService", state.getAttribute (STATE_CONTENT_TYPE_IMAGE_SERVICE));
context.put("TYPE_FOLDER", TYPE_FOLDER);
context.put("TYPE_UPLOAD", TYPE_UPLOAD);
// find the ContentHosting service
org.sakaiproject.content.api.ContentHostingService contentService = (org.sakaiproject.content.api.ContentHostingService) state.getAttribute (STATE_CONTENT_SERVICE);
// context.put ("service", contentService);
boolean inMyWorkspace = SiteService.isUserSite(ToolManager.getCurrentPlacement().getContext());
// context.put("inMyWorkspace", Boolean.toString(inMyWorkspace));
boolean atHome = false;
// %%STATE_MODE_RESOURCES%%
boolean dropboxMode = RESOURCES_MODE_DROPBOX.equalsIgnoreCase((String) state.getAttribute(STATE_MODE_RESOURCES));
// make sure the channedId is set
String collectionId = (String) state.getAttribute(STATE_ATTACH_COLLECTION_ID);
if(collectionId == null)
{
collectionId = (String) state.getAttribute (STATE_COLLECTION_ID);
}
context.put ("collectionId", collectionId);
String navRoot = (String) state.getAttribute(STATE_NAVIGATION_ROOT);
String homeCollectionId = (String) state.getAttribute(STATE_HOME_COLLECTION_ID);
String siteTitle = (String) state.getAttribute (STATE_SITE_TITLE);
if (collectionId.equals(homeCollectionId))
{
atHome = true;
//context.put ("collectionDisplayName", state.getAttribute (STATE_HOME_COLLECTION_DISPLAY_NAME));
}
else
{
/*
// should be not PermissionException thrown at this time, when the user can successfully navigate to this collection
try
{
context.put("collectionDisplayName", contentService.getCollection(collectionId).getProperties().getProperty(ResourceProperties.PROP_DISPLAY_NAME));
}
catch (IdUnusedException e){}
catch (TypeException e) {}
catch (PermissionException e) {}
*/
}
List cPath = getCollectionPath(state);
context.put ("collectionPath", cPath);
// set the sort values
String sortedBy = (String) state.getAttribute (STATE_SORT_BY);
String sortedAsc = (String) state.getAttribute (STATE_SORT_ASC);
context.put ("currentSortedBy", sortedBy);
context.put ("currentSortAsc", sortedAsc);
context.put("TRUE", Boolean.TRUE.toString());
// String current_user_id = UserDirectoryService.getCurrentUser().getId();
try
{
try
{
contentService.checkCollection (collectionId);
context.put ("collectionFlag", Boolean.TRUE.toString());
}
catch(IdUnusedException ex)
{
logger.error("ResourcesAction.buildSelectAttachment (static) : IdUnusedException: " + collectionId);
try
{
ContentCollectionEdit coll = contentService.addCollection(collectionId);
contentService.commitCollection(coll);
}
catch(IdUsedException inner)
{
// how can this happen??
logger.error("ResourcesAction.buildSelectAttachment (static) : IdUsedException: " + collectionId);
throw ex;
}
catch(IdInvalidException inner)
{
logger.error("ResourcesAction.buildSelectAttachment (static) : IdInvalidException: " + collectionId);
// what now?
throw ex;
}
catch(InconsistentException inner)
{
logger.error("ResourcesAction.buildSelectAttachment (static) : InconsistentException: " + collectionId);
// what now?
throw ex;
}
}
catch(TypeException ex)
{
logger.error("ResourcesAction.buildSelectAttachment (static) : TypeException.");
throw ex;
}
catch(PermissionException ex)
{
logger.error("ResourcesAction.buildSelectAttachment (static) : PermissionException.");
throw ex;
}
HashMap expandedCollections = (HashMap) state.getAttribute(STATE_EXPANDED_COLLECTIONS);
ContentCollection coll = contentService.getCollection(collectionId);
expandedCollections.put(collectionId, coll);
state.removeAttribute(STATE_PASTE_ALLOWED_FLAG);
List this_site = new Vector();
User[] submitters = (User[]) state.getAttribute(STATE_ATTACH_SHOW_DROPBOXES);
if(submitters != null)
{
String dropboxId = ContentHostingService.getDropboxCollection();
if(dropboxId == null)
{
ContentHostingService.createDropboxCollection();
dropboxId = ContentHostingService.getDropboxCollection();
}
if(dropboxId == null)
{
// do nothing
}
else if(ContentHostingService.isDropboxMaintainer())
{
for(int i = 0; i < submitters.length; i++)
{
User submitter = submitters[i];
String dbId = dropboxId + StringUtil.trimToZero(submitter.getId()) + "/";
try
{
ContentCollection db = ContentHostingService.getCollection(dbId);
expandedCollections.put(dbId, db);
List dbox = getBrowseItems(dbId, expandedCollections, highlightedItems, sortedBy, sortedAsc, (BrowseItem) null, false, state);
if(dbox != null && dbox.size() > 0)
{
BrowseItem root = (BrowseItem) dbox.remove(0);
// context.put("site", root);
root.setName(submitter.getDisplayName() + " " + rb.getString("gen.drop"));
root.addMembers(dbox);
this_site.add(root);
}
}
catch(IdUnusedException e)
{
// ignore a user's dropbox if it's not defined
}
}
}
else
{
try
{
ContentCollection db = ContentHostingService.getCollection(dropboxId);
expandedCollections.put(dropboxId, db);
List dbox = getBrowseItems(dropboxId, expandedCollections, highlightedItems, sortedBy, sortedAsc, (BrowseItem) null, false, state);
if(dbox != null && dbox.size() > 0)
{
BrowseItem root = (BrowseItem) dbox.remove(0);
// context.put("site", root);
root.setName(ContentHostingService.getDropboxDisplayName());
root.addMembers(dbox);
this_site.add(root);
}
}
catch(IdUnusedException e)
{
// if an id is unused, ignore it
}
}
}
List members = getBrowseItems(collectionId, expandedCollections, highlightedItems, sortedBy, sortedAsc, (BrowseItem) null, navRoot.equals(homeCollectionId), state);
if(members != null && members.size() > 0)
{
BrowseItem root = (BrowseItem) members.remove(0);
if(atHome && dropboxMode)
{
root.setName(siteTitle + " " + rb.getString("gen.drop"));
}
else if(atHome)
{
root.setName(siteTitle + " " + rb.getString("gen.reso"));
}
context.put("site", root);
root.addMembers(members);
this_site.add(root);
}
context.put ("this_site", this_site);
List other_sites = new Vector();
boolean show_all_sites = false;
String allowed_to_see_other_sites = (String) state.getAttribute(STATE_SHOW_ALL_SITES);
String show_other_sites = (String) state.getAttribute(STATE_SHOW_OTHER_SITES);
context.put("show_other_sites", show_other_sites);
if(Boolean.TRUE.toString().equals(allowed_to_see_other_sites))
{
context.put("allowed_to_see_other_sites", Boolean.TRUE.toString());
show_all_sites = Boolean.TRUE.toString().equals(show_other_sites);
}
if(show_all_sites)
{
state.setAttribute(STATE_HIGHLIGHTED_ITEMS, highlightedItems);
other_sites.addAll(readAllResources(state));
List messages = prepPage(state);
context.put("other_sites", messages);
if (state.getAttribute(STATE_NUM_MESSAGES) != null)
{
context.put("allMsgNumber", state.getAttribute(STATE_NUM_MESSAGES).toString());
context.put("allMsgNumberInt", state.getAttribute(STATE_NUM_MESSAGES));
}
context.put("pagesize", ((Integer) state.getAttribute(STATE_PAGESIZE)).toString());
// find the position of the message that is the top first on the page
if ((state.getAttribute(STATE_TOP_MESSAGE_INDEX) != null) && (state.getAttribute(STATE_PAGESIZE) != null))
{
int topMsgPos = ((Integer)state.getAttribute(STATE_TOP_MESSAGE_INDEX)).intValue() + 1;
context.put("topMsgPos", Integer.toString(topMsgPos));
int btmMsgPos = topMsgPos + ((Integer)state.getAttribute(STATE_PAGESIZE)).intValue() - 1;
if (state.getAttribute(STATE_NUM_MESSAGES) != null)
{
int allMsgNumber = ((Integer)state.getAttribute(STATE_NUM_MESSAGES)).intValue();
if (btmMsgPos > allMsgNumber)
btmMsgPos = allMsgNumber;
}
context.put("btmMsgPos", Integer.toString(btmMsgPos));
}
boolean goPPButton = state.getAttribute(STATE_PREV_PAGE_EXISTS) != null;
context.put("goPPButton", Boolean.toString(goPPButton));
boolean goNPButton = state.getAttribute(STATE_NEXT_PAGE_EXISTS) != null;
context.put("goNPButton", Boolean.toString(goNPButton));
/*
boolean goFPButton = state.getAttribute(STATE_FIRST_PAGE_EXISTS) != null;
context.put("goFPButton", Boolean.toString(goFPButton));
boolean goLPButton = state.getAttribute(STATE_LAST_PAGE_EXISTS) != null;
context.put("goLPButton", Boolean.toString(goLPButton));
*/
context.put("pagesize", state.getAttribute(STATE_PAGESIZE));
// context.put("pagesizes", PAGESIZES);
// List other_sites = new Vector();
/*
* NOTE: This does not (and should not) get all sites for admin.
* Getting all sites for admin is too big a request and
* would result in too big a display to render in html.
*/
/*
Map othersites = ContentHostingService.getCollectionMap();
Iterator siteIt = othersites.keySet().iterator();
while(siteIt.hasNext())
{
String displayName = (String) siteIt.next();
String collId = (String) othersites.get(displayName);
if(! collectionId.equals(collId))
{
members = getBrowseItems(collId, expandedCollections, highlightedItems, sortedBy, sortedAsc, (BrowseItem) null, false, state);
if(members != null && members.size() > 0)
{
BrowseItem root = (BrowseItem) members.remove(0);
root.addMembers(members);
root.setName(displayName);
other_sites.add(root);
}
}
}
context.put ("other_sites", other_sites);
*/
}
// context.put ("root", root);
context.put("expandedCollections", expandedCollections);
state.setAttribute(STATE_EXPANDED_COLLECTIONS, expandedCollections);
}
catch (IdUnusedException e)
{
addAlert(state, rb.getString("cannotfind"));
context.put ("collectionFlag", Boolean.FALSE.toString());
}
catch(TypeException e)
{
// Log.error("chef", this + "TypeException.");
context.put ("collectionFlag", Boolean.FALSE.toString());
}
catch(PermissionException e)
{
addAlert(state, rb.getString("notpermis1"));
context.put ("collectionFlag", Boolean.FALSE.toString());
}
context.put("homeCollection", (String) state.getAttribute (STATE_HOME_COLLECTION_ID));
context.put("siteTitle", state.getAttribute(STATE_SITE_TITLE));
context.put ("resourceProperties", contentService.newResourceProperties ());
try
{
// TODO: why 'site' here?
Site site = SiteService.getSite(ToolManager.getCurrentPlacement().getContext());
context.put("siteTitle", site.getTitle());
}
catch (IdUnusedException e)
{
// Log.error("chef", this + e.toString());
}
context.put("expandallflag", state.getAttribute(STATE_EXPAND_ALL_FLAG));
state.removeAttribute(STATE_NEED_TO_EXPAND_ALL);
// inform the observing courier that we just updated the page...
// if there are pending requests to do so they can be cleared
// justDelivered(state);
// pick the template based on whether client wants links or copies
String template = TEMPLATE_SELECT;
Object attach_links = current_stack_frame.get(STATE_ATTACH_LINKS);
if(attach_links == null)
{
attach_links = state.getAttribute(STATE_ATTACH_LINKS);
if(attach_links != null)
{
current_stack_frame.put(STATE_ATTACH_LINKS, attach_links);
}
}
if(attach_links == null)
{
// user wants copies in hidden attachments area
template = TEMPLATE_ATTACH;
}
return template;
} // buildSelectAttachmentContext
/**
* Expand all the collection resources and put in EXPANDED_COLLECTIONS attribute.
*/
public void doList ( RunData data)
{
// get the state object
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
state.setAttribute (STATE_MODE, MODE_LIST);
} // doList
/**
* Build the context for add display
*/
public String buildWebdavContext ( VelocityPortlet portlet,
Context context,
RunData data,
SessionState state)
{
context.put("tlang",rb);
// find the ContentTypeImage service
context.put ("contentTypeImageService", state.getAttribute (STATE_CONTENT_TYPE_IMAGE_SERVICE));
boolean inMyWorkspace = SiteService.isUserSite(ToolManager.getCurrentPlacement().getContext());
context.put("inMyWorkspace", Boolean.toString(inMyWorkspace));
context.put("server_url", ServerConfigurationService.getServerUrl());
context.put("site_id", ToolManager.getCurrentPlacement().getContext());
context.put("site_title", state.getAttribute(STATE_SITE_TITLE));
context.put("user_id", UserDirectoryService.getCurrentUser().getId());
context.put ("dav_group", "/dav/group/");
context.put ("dav_user", "/dav/user/");
String webdav_instructions = ServerConfigurationService.getString("webdav.instructions.url");
context.put("webdav_instructions" ,webdav_instructions);
// TODO: get browser id from somewhere.
//Session session = SessionManager.getCurrentSession();
//String browserId = session.;
String browserID = UsageSessionService.getSession().getBrowserId();
if(browserID.equals(UsageSession.WIN_IE))
{
context.put("isWinIEBrowser", Boolean.TRUE.toString());
}
return TEMPLATE_DAV;
} // buildWebdavContext
/**
* Build the context for delete confirmation page
*/
public String buildDeleteConfirmContext ( VelocityPortlet portlet,
Context context,
RunData data,
SessionState state)
{
context.put("tlang",rb);
// find the ContentTypeImage service
context.put ("contentTypeImageService", state.getAttribute (STATE_CONTENT_TYPE_IMAGE_SERVICE));
context.put ("collectionId", state.getAttribute (STATE_COLLECTION_ID) );
//%%%% FIXME
context.put ("collectionPath", state.getAttribute (STATE_COLLECTION_PATH));
List deleteItems = (List) state.getAttribute(STATE_DELETE_ITEMS);
List nonEmptyFolders = (List) state.getAttribute(STATE_DELETE_ITEMS_NOT_EMPTY);
context.put ("deleteItems", deleteItems);
Iterator it = nonEmptyFolders.iterator();
while(it.hasNext())
{
BrowseItem folder = (BrowseItem) it.next();
addAlert(state, rb.getString("folder2") + " " + folder.getName() + " " + rb.getString("contain2") + " ");
}
// find the ContentTypeImage service
context.put ("contentTypeImageService", state.getAttribute (STATE_CONTENT_TYPE_IMAGE_SERVICE));
context.put ("service", state.getAttribute (STATE_CONTENT_SERVICE));
// %%STATE_MODE_RESOURCES%%
//not show the public option when in dropbox mode
if (RESOURCES_MODE_RESOURCES.equalsIgnoreCase((String) state.getAttribute(STATE_MODE_RESOURCES)))
{
context.put("dropboxMode", Boolean.FALSE);
}
else if (RESOURCES_MODE_DROPBOX.equalsIgnoreCase((String) state.getAttribute(STATE_MODE_RESOURCES)))
{
// not show the public option or notification when in dropbox mode
context.put("dropboxMode", Boolean.TRUE);
}
context.put("homeCollection", (String) state.getAttribute (STATE_HOME_COLLECTION_ID));
context.put("siteTitle", state.getAttribute(STATE_SITE_TITLE));
context.put ("resourceProperties", ContentHostingService.newResourceProperties ());
// String template = (String) getContext(data).get("template");
return TEMPLATE_DELETE_CONFIRM;
} // buildDeleteConfirmContext
/**
* Build the context to show the list of resource properties
*/
public static String buildMoreContext ( VelocityPortlet portlet,
Context context,
RunData data,
SessionState state)
{
context.put("tlang",rb);
// find the ContentTypeImage service
context.put ("contentTypeImageService", state.getAttribute (STATE_CONTENT_TYPE_IMAGE_SERVICE));
// find the ContentHosting service
org.sakaiproject.content.api.ContentHostingService service = (org.sakaiproject.content.api.ContentHostingService) state.getAttribute (STATE_CONTENT_SERVICE);
context.put ("service", service);
Map current_stack_frame = peekAtStack(state);
String id = (String) current_stack_frame.get(STATE_MORE_ID);
context.put ("id", id);
String collectionId = (String) current_stack_frame.get(STATE_MORE_COLLECTION_ID);
context.put ("collectionId", collectionId);
String homeCollectionId = (String) (String) state.getAttribute (STATE_HOME_COLLECTION_ID);
context.put("homeCollectionId", homeCollectionId);
List cPath = getCollectionPath(state);
context.put ("collectionPath", cPath);
// for the resources of type URL or plain text, show the content also
try
{
ResourceProperties properties = service.getProperties (id);
context.put ("properties", properties);
String isCollection = properties.getProperty (ResourceProperties.PROP_IS_COLLECTION);
if ((isCollection != null) && isCollection.equals (Boolean.FALSE.toString()))
{
String copyrightAlert = properties.getProperty(properties.getNamePropCopyrightAlert());
context.put("hasCopyrightAlert", copyrightAlert);
String type = properties.getProperty (ResourceProperties.PROP_CONTENT_TYPE);
if (type.equalsIgnoreCase (MIME_TYPE_DOCUMENT_PLAINTEXT) || type.equalsIgnoreCase (MIME_TYPE_DOCUMENT_HTML) || type.equalsIgnoreCase (ResourceProperties.TYPE_URL))
{
ContentResource moreResource = service.getResource (id);
// read the body
String body = "";
byte[] content = null;
try
{
content = moreResource.getContent();
if (content != null)
{
body = new String(content);
}
}
catch(ServerOverloadException e)
{
// this represents server's file system is temporarily unavailable
// report problem to user? log problem?
}
context.put ("content", body);
} // if
} // if
else
{
// setup for quota - ADMIN only, collection only
if (SecurityService.isSuperUser())
{
try
{
// Getting the quota as a long validates the property
long quota = properties.getLongProperty(ResourceProperties.PROP_COLLECTION_BODY_QUOTA);
context.put("hasQuota", Boolean.TRUE);
context.put("quota", properties.getProperty(ResourceProperties.PROP_COLLECTION_BODY_QUOTA));
}
catch (Exception any) {}
}
}
}
catch (IdUnusedException e)
{
addAlert(state,RESOURCE_NOT_EXIST_STRING);
context.put("notExistFlag", new Boolean(true));
}
catch (TypeException e)
{
addAlert(state, rb.getString("typeex") + " ");
}
catch (PermissionException e)
{
addAlert(state," " + rb.getString("notpermis2") + " " + id + ". ");
} // try-catch
if (state.getAttribute(STATE_MESSAGE) == null)
{
context.put("notExistFlag", new Boolean(false));
}
if (RESOURCES_MODE_DROPBOX.equalsIgnoreCase((String) state.getAttribute(STATE_MODE_RESOURCES)))
{
// notshow the public option or notification when in dropbox mode
context.put("dropboxMode", Boolean.TRUE);
}
else
{
context.put("dropboxMode", Boolean.FALSE);
Boolean preventPublicDisplay = (Boolean) state.getAttribute(STATE_PREVENT_PUBLIC_DISPLAY);
if(preventPublicDisplay == null)
{
preventPublicDisplay = Boolean.FALSE;
state.setAttribute(STATE_PREVENT_PUBLIC_DISPLAY, preventPublicDisplay);
}
context.put("preventPublicDisplay", preventPublicDisplay);
if(preventPublicDisplay.equals(Boolean.FALSE))
{
// find out about pubview
boolean pubview = ContentHostingService.isInheritingPubView(id);
if (!pubview) pubview = ContentHostingService.isPubView(id);
context.put("pubview", new Boolean(pubview));
}
}
context.put("siteTitle", state.getAttribute(STATE_SITE_TITLE));
if (state.getAttribute(COPYRIGHT_TYPES) != null)
{
List copyrightTypes = (List) state.getAttribute(COPYRIGHT_TYPES);
context.put("copyrightTypes", copyrightTypes);
}
metadataGroupsIntoContext(state, context);
// String template = (String) getContext(data).get("template");
return TEMPLATE_MORE;
} // buildMoreContext
/**
* Build the context to edit the editable list of resource properties
*/
public static String buildEditContext (VelocityPortlet portlet,
Context context,
RunData data,
SessionState state)
{
context.put("tlang",rb);
// find the ContentTypeImage service
Map current_stack_frame = peekAtStack(state);
context.put ("contentTypeImageService", state.getAttribute (STATE_CONTENT_TYPE_IMAGE_SERVICE));
context.put ("from", state.getAttribute (STATE_FROM));
context.put ("mycopyright", (String) state.getAttribute (STATE_MY_COPYRIGHT));
context.put("SITE_ACCESS", AccessMode.SITE.toString());
context.put("GROUP_ACCESS", AccessMode.GROUPED.toString());
context.put("INHERITED_ACCESS", AccessMode.INHERITED.toString());
String collectionId = (String) current_stack_frame.get(STATE_STACK_EDIT_COLLECTION_ID);
context.put ("collectionId", collectionId);
String id = (String) current_stack_frame.get(STATE_STACK_EDIT_ID);
if(id == null)
{
id = (String) state.getAttribute(STATE_EDIT_ID);
if(id == null)
{
id = "";
}
current_stack_frame.put(STATE_STACK_EDIT_ID, id);
}
context.put ("id", id);
String homeCollectionId = (String) state.getAttribute (STATE_HOME_COLLECTION_ID);
if(homeCollectionId == null)
{
homeCollectionId = ContentHostingService.getSiteCollection(ToolManager.getCurrentPlacement().getContext());
state.setAttribute(STATE_HOME_COLLECTION_ID, homeCollectionId);
}
context.put("homeCollectionId", homeCollectionId);
List collectionPath = getCollectionPath(state);
context.put ("collectionPath", collectionPath);
if(homeCollectionId.equals(id))
{
context.put("atHome", Boolean.TRUE.toString());
}
String intent = (String) current_stack_frame.get(STATE_STACK_EDIT_INTENT);
if(intent == null)
{
intent = INTENT_REVISE_FILE;
current_stack_frame.put(STATE_STACK_EDIT_INTENT, intent);
}
context.put("intent", intent);
context.put("REVISE", INTENT_REVISE_FILE);
context.put("REPLACE", INTENT_REPLACE_FILE);
Collection groups = ContentHostingService.getGroupsWithReadAccess(collectionId);
// TODO: does this method filter groups for this subcollection??
if(! groups.isEmpty())
{
context.put("siteHasGroups", Boolean.TRUE.toString());
context.put("theGroupsInThisSite", groups);
}
String show_form_items = (String) state.getAttribute(STATE_SHOW_FORM_ITEMS);
if(show_form_items == null)
{
show_form_items = (String) state.getAttribute(STATE_SHOW_FORM_ITEMS);
if(show_form_items != null)
{
current_stack_frame.put(STATE_SHOW_FORM_ITEMS,show_form_items);
}
}
if(show_form_items != null)
{
context.put("show_form_items", show_form_items);
}
// put the item into context
EditItem item = (EditItem) current_stack_frame.get(STATE_STACK_EDIT_ITEM);
if(item == null)
{
item = getEditItem(id, collectionId, data);
if(item == null)
{
// what??
}
if (state.getAttribute(STATE_MESSAGE) == null)
{
// got resource and sucessfully populated item with values
state.setAttribute(STATE_EDIT_ALERTS, new HashSet());
current_stack_frame.put(STATE_STACK_EDIT_ITEM, item);
}
}
context.put("item", item);
if(item.isStructuredArtifact())
{
context.put("formtype", item.getFormtype());
current_stack_frame.put(STATE_STACK_STRUCTOBJ_TYPE, item.getFormtype());
List listOfHomes = (List) current_stack_frame.get(STATE_STRUCTOBJ_HOMES);
if(listOfHomes == null)
{
ResourcesAction.setupStructuredObjects(state);
listOfHomes = (List) current_stack_frame.get(STATE_STRUCTOBJ_HOMES);
}
context.put("homes", listOfHomes);
String formtype_readonly = (String) current_stack_frame.get(STATE_STACK_STRUCTOBJ_TYPE_READONLY);
if(formtype_readonly == null)
{
formtype_readonly = (String) state.getAttribute(STATE_STRUCTOBJ_TYPE_READONLY);
if(formtype_readonly == null)
{
formtype_readonly = Boolean.FALSE.toString();
}
current_stack_frame.put(STATE_STACK_STRUCTOBJ_TYPE_READONLY, formtype_readonly);
}
if(formtype_readonly != null && formtype_readonly.equals(Boolean.TRUE.toString()))
{
context.put("formtype_readonly", formtype_readonly);
}
String rootname = (String) current_stack_frame.get(STATE_STACK_STRUCTOBJ_ROOTNAME);
context.put("rootname", rootname);
context.put("STRING", ResourcesMetadata.WIDGET_STRING);
context.put("TEXTAREA", ResourcesMetadata.WIDGET_TEXTAREA);
context.put("BOOLEAN", ResourcesMetadata.WIDGET_BOOLEAN);
context.put("INTEGER", ResourcesMetadata.WIDGET_INTEGER);
context.put("DOUBLE", ResourcesMetadata.WIDGET_DOUBLE);
context.put("DATE", ResourcesMetadata.WIDGET_DATE);
context.put("TIME", ResourcesMetadata.WIDGET_TIME);
context.put("DATETIME", ResourcesMetadata.WIDGET_DATETIME);
context.put("ANYURI", ResourcesMetadata.WIDGET_ANYURI);
context.put("ENUM", ResourcesMetadata.WIDGET_ENUM);
context.put("NESTED", ResourcesMetadata.WIDGET_NESTED);
context.put("WYSIWYG", ResourcesMetadata.WIDGET_WYSIWYG);
context.put("today", TimeService.newTime());
context.put("TRUE", Boolean.TRUE.toString());
}
// copyright
copyrightChoicesIntoContext(state, context);
// put schema for metadata into context
metadataGroupsIntoContext(state, context);
// %%STATE_MODE_RESOURCES%%
if (RESOURCES_MODE_RESOURCES.equalsIgnoreCase((String) state.getAttribute(STATE_MODE_RESOURCES)))
{
context.put("dropboxMode", Boolean.FALSE);
}
else if (RESOURCES_MODE_DROPBOX.equalsIgnoreCase((String) state.getAttribute(STATE_MODE_RESOURCES)))
{
// notshow the public option or notification when in dropbox mode
context.put("dropboxMode", Boolean.TRUE);
}
context.put("siteTitle", state.getAttribute(STATE_SITE_TITLE));
// String template = (String) getContext(data).get("template");
return TEMPLATE_EDIT;
} // buildEditContext
/**
* Navigate in the resource hireachy
*/
public static void doNavigate ( RunData data )
{
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
if (state.getAttribute (STATE_SELECT_ALL_FLAG)!=null && state.getAttribute (STATE_SELECT_ALL_FLAG).equals (Boolean.TRUE.toString()))
{
state.setAttribute (STATE_SELECT_ALL_FLAG, Boolean.FALSE.toString());
}
if (state.getAttribute (STATE_EXPAND_ALL_FLAG)!=null && state.getAttribute (STATE_EXPAND_ALL_FLAG).equals (Boolean.TRUE.toString()))
{
state.setAttribute (STATE_EXPAND_ALL_FLAG, Boolean.FALSE.toString());
}
// save the current selections
Set selectedSet = new TreeSet();
String[] selectedItems = data.getParameters ().getStrings ("selectedMembers");
if(selectedItems != null)
{
selectedSet.addAll(Arrays.asList(selectedItems));
}
state.setAttribute(STATE_LIST_SELECTIONS, selectedSet);
String collectionId = data.getParameters().getString ("collectionId");
String navRoot = data.getParameters().getString("navRoot");
state.setAttribute(STATE_NAVIGATION_ROOT, navRoot);
// the exception message
try
{
ContentHostingService.checkCollection(collectionId);
}
catch(PermissionException e)
{
addAlert(state, " " + rb.getString("notpermis3") + " " );
}
catch (IdUnusedException e)
{
addAlert(state, " " + rb.getString("notexist2") + " ");
}
catch (TypeException e)
{
addAlert(state," " + rb.getString("notexist2") + " ");
}
if (state.getAttribute(STATE_MESSAGE) == null)
{
String oldCollectionId = (String) state.getAttribute(STATE_COLLECTION_ID);
// update this folder id in the set to be event-observed
removeObservingPattern(oldCollectionId, state);
addObservingPattern(collectionId, state);
state.setAttribute(STATE_COLLECTION_ID, collectionId);
state.setAttribute(STATE_EXPANDED_COLLECTIONS, new HashMap());
}
} // doNavigate
/**
* Show information about WebDAV
*/
public void doShow_webdav ( RunData data )
{
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
state.setAttribute(STATE_LIST_SELECTIONS, new TreeSet());
state.setAttribute (STATE_MODE, MODE_DAV);
// cancel copy if there is one in progress
if(! Boolean.FALSE.toString().equals(state.getAttribute (STATE_COPY_FLAG)))
{
initCopyContext(state);
}
// cancel move if there is one in progress
if(! Boolean.FALSE.toString().equals(state.getAttribute (STATE_MOVE_FLAG)))
{
initMoveContext(state);
}
} // doShow_webdav
/**
* initiate creation of one or more resource items (folders, file uploads, html docs, text docs, or urls)
* default type is folder
*/
public static void doCreate(RunData data)
{
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
ParameterParser params = data.getParameters ();
// cancel copy if there is one in progress
if(! Boolean.FALSE.toString().equals(state.getAttribute (STATE_COPY_FLAG)))
{
initCopyContext(state);
}
// cancel move if there is one in progress
if(! Boolean.FALSE.toString().equals(state.getAttribute (STATE_MOVE_FLAG)))
{
initMoveContext(state);
}
state.setAttribute(STATE_LIST_SELECTIONS, new TreeSet());
String itemType = params.getString("itemType");
if(itemType == null || "".equals(itemType))
{
itemType = TYPE_UPLOAD;
}
String stackOp = params.getString("suspended-operations-stack");
Map current_stack_frame = null;
if(stackOp != null && stackOp.equals("peek"))
{
current_stack_frame = peekAtStack(state);
}
else
{
current_stack_frame = pushOnStack(state);
}
String encoding = data.getRequest().getCharacterEncoding();
String defaultCopyrightStatus = (String) state.getAttribute(DEFAULT_COPYRIGHT);
if(defaultCopyrightStatus == null || defaultCopyrightStatus.trim().equals(""))
{
defaultCopyrightStatus = ServerConfigurationService.getString("default.copyright");
state.setAttribute(DEFAULT_COPYRIGHT, defaultCopyrightStatus);
}
List new_items = new Vector();
for(int i = 0; i < CREATE_MAX_ITEMS; i++)
{
EditItem item = new EditItem(itemType);
if(encoding != null)
{
item.setEncoding(encoding);
}
item.setCopyrightStatus(defaultCopyrightStatus);
new_items.add(item);
}
current_stack_frame.put(STATE_STACK_CREATE_ITEMS, new_items);
current_stack_frame.put(STATE_STACK_CREATE_TYPE, itemType);
String collectionId = params.getString ("collectionId");
current_stack_frame.put(STATE_STACK_CREATE_COLLECTION_ID, collectionId);
current_stack_frame.put(STATE_STACK_CREATE_NUMBER, new Integer(1));
state.setAttribute(STATE_CREATE_ALERTS, new HashSet());
current_stack_frame.put(STATE_CREATE_MISSING_ITEM, new HashSet());
current_stack_frame.remove(STATE_STACK_STRUCTOBJ_TYPE);
current_stack_frame.put(STATE_RESOURCES_HELPER_MODE, MODE_ATTACHMENT_CREATE_INIT);
state.setAttribute(STATE_RESOURCES_HELPER_MODE, MODE_ATTACHMENT_CREATE_INIT);
} // doCreate
public static void addCreateContextAlert(SessionState state, String message)
{
String soFar = (String) state.getAttribute(STATE_CREATE_MESSAGE);
if (soFar != null)
{
soFar = soFar + " " + message;
}
else
{
soFar = message;
}
state.setAttribute(STATE_CREATE_MESSAGE, soFar);
} // addItemTypeContextAlert
/**
* initiate creation of one or more resource items (file uploads, html docs, text docs, or urls -- not folders)
* default type is file upload
*/
/**
* @param data
*/
public static void doCreateitem(RunData data)
{
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
ParameterParser params = data.getParameters ();
state.setAttribute(STATE_LIST_SELECTIONS, new TreeSet());
Map current_stack_frame = peekAtStack(state);
boolean pop = false;
String itemType = params.getString("itemType");
String flow = params.getString("flow");
Set alerts = (Set) state.getAttribute(STATE_CREATE_ALERTS);
if(alerts == null)
{
alerts = new HashSet();
state.setAttribute(STATE_CREATE_ALERTS, alerts);
}
Set missing = new HashSet();
if(flow == null || flow.equals("cancel"))
{
pop = true;
}
else if(flow.equals("updateNumber"))
{
captureMultipleValues(state, params, false);
int number = params.getInt("numberOfItems");
Integer numberOfItems = new Integer(number);
current_stack_frame.put(ResourcesAction.STATE_STACK_CREATE_NUMBER, numberOfItems);
// clear display of error messages
state.setAttribute(STATE_CREATE_ALERTS, new HashSet());
List items = (List) current_stack_frame.get(STATE_STACK_CREATE_ITEMS);
if(items == null)
{
String defaultCopyrightStatus = (String) state.getAttribute(DEFAULT_COPYRIGHT);
if(defaultCopyrightStatus == null || defaultCopyrightStatus.trim().equals(""))
{
defaultCopyrightStatus = ServerConfigurationService.getString("default.copyright");
state.setAttribute(DEFAULT_COPYRIGHT, defaultCopyrightStatus);
}
String encoding = data.getRequest().getCharacterEncoding();
items = new Vector();
for(int i = 0; i < CREATE_MAX_ITEMS; i++)
{
EditItem item = new EditItem(itemType);
if(encoding != null)
{
item.setEncoding(encoding);
}
item.setCopyrightStatus(defaultCopyrightStatus);
items.add(item);
}
}
current_stack_frame.put(STATE_STACK_CREATE_ITEMS, items);
Iterator it = items.iterator();
while(it.hasNext())
{
EditItem item = (EditItem) it.next();
item.clearMissing();
}
state.removeAttribute(STATE_MESSAGE);
}
else if(flow.equals("create") && TYPE_FOLDER.equals(itemType))
{
// Get the items
captureMultipleValues(state, params, true);
alerts = (Set) state.getAttribute(STATE_CREATE_ALERTS);
if(alerts.isEmpty())
{
// Save the items
createFolders(state);
alerts = (Set) state.getAttribute(STATE_CREATE_ALERTS);
if(alerts.isEmpty())
{
pop = true;
}
}
}
else if(flow.equals("create") && TYPE_UPLOAD.equals(itemType))
{
captureMultipleValues(state, params, true);
alerts = (Set) state.getAttribute(STATE_CREATE_ALERTS);
if(alerts.isEmpty())
{
createFiles(state);
alerts = (Set) state.getAttribute(STATE_CREATE_ALERTS);
if(alerts.isEmpty())
{
pop = true;
}
}
}
else if(flow.equals("create") && MIME_TYPE_DOCUMENT_HTML.equals(itemType))
{
captureMultipleValues(state, params, true);
alerts = (Set) state.getAttribute(STATE_CREATE_ALERTS);
if(alerts.isEmpty())
{
createFiles(state);
alerts = (Set) state.getAttribute(STATE_CREATE_ALERTS);
if(alerts.isEmpty())
{
pop = true;
}
}
}
else if(flow.equals("create") && MIME_TYPE_DOCUMENT_PLAINTEXT.equals(itemType))
{
captureMultipleValues(state, params, true);
alerts = (Set) state.getAttribute(STATE_CREATE_ALERTS);
if(alerts.isEmpty())
{
createFiles(state);
alerts = (Set) state.getAttribute(STATE_CREATE_ALERTS);
if(alerts.isEmpty())
{
pop =true;
}
}
}
else if(flow.equals("create") && TYPE_URL.equals(itemType))
{
captureMultipleValues(state, params, true);
alerts = (Set) state.getAttribute(STATE_CREATE_ALERTS);
if(alerts.isEmpty())
{
createUrls(state);
alerts = (Set) state.getAttribute(STATE_CREATE_ALERTS);
if(alerts.isEmpty())
{
pop = true;
}
}
}
else if(flow.equals("create") && TYPE_FORM.equals(itemType))
{
captureMultipleValues(state, params, true);
alerts = (Set) state.getAttribute(STATE_CREATE_ALERTS);
if(alerts == null)
{
alerts = new HashSet();
state.setAttribute(STATE_CREATE_ALERTS, alerts);
}
if(alerts.isEmpty())
{
createStructuredArtifacts(state);
alerts = (Set) state.getAttribute(STATE_CREATE_ALERTS);
if(alerts.isEmpty())
{
pop = true;
}
}
}
else if(flow.equals("create"))
{
captureMultipleValues(state, params, true);
alerts = (Set) state.getAttribute(STATE_CREATE_ALERTS);
if(alerts == null)
{
alerts = new HashSet();
state.setAttribute(STATE_CREATE_ALERTS, alerts);
}
alerts.add("Invalid item type");
state.setAttribute(STATE_CREATE_ALERTS, alerts);
}
else if(flow.equals("updateDocType"))
{
// captureMultipleValues(state, params, false);
String formtype = params.getString("formtype");
if(formtype == null || formtype.equals(""))
{
alerts.add("Must select a form type");
missing.add("formtype");
}
current_stack_frame.put(STATE_STACK_STRUCTOBJ_TYPE, formtype);
setupStructuredObjects(state);
}
else if(flow.equals("addInstance"))
{
captureMultipleValues(state, params, false);
String field = params.getString("field");
List new_items = (List) current_stack_frame.get(STATE_STACK_CREATE_ITEMS);
if(new_items == null)
{
String defaultCopyrightStatus = (String) state.getAttribute(DEFAULT_COPYRIGHT);
if(defaultCopyrightStatus == null || defaultCopyrightStatus.trim().equals(""))
{
defaultCopyrightStatus = ServerConfigurationService.getString("default.copyright");
state.setAttribute(DEFAULT_COPYRIGHT, defaultCopyrightStatus);
}
String encoding = data.getRequest().getCharacterEncoding();
new_items = new Vector();
for(int i = 0; i < CREATE_MAX_ITEMS; i++)
{
EditItem item = new EditItem(itemType);
if(encoding != null)
{
item.setEncoding(encoding);
}
item.setCopyrightStatus(defaultCopyrightStatus);
new_items.add(item);
}
current_stack_frame.put(STATE_STACK_CREATE_ITEMS, new_items);
}
EditItem item = (EditItem) new_items.get(0);
addInstance(field, item.getProperties());
ResourcesMetadata form = item.getForm();
List flatList = form.getFlatList();
item.setProperties(flatList);
}
else if(flow.equals("linkResource") && TYPE_FORM.equals(itemType))
{
captureMultipleValues(state, params, false);
createLink(data, state);
}
else if(flow.equals("showOptional"))
{
captureMultipleValues(state, params, false);
int twiggleNumber = params.getInt("twiggleNumber", 0);
String metadataGroup = params.getString("metadataGroup");
List new_items = (List) current_stack_frame.get(STATE_STACK_CREATE_ITEMS);
if(new_items == null)
{
String defaultCopyrightStatus = (String) state.getAttribute(DEFAULT_COPYRIGHT);
if(defaultCopyrightStatus == null || defaultCopyrightStatus.trim().equals(""))
{
defaultCopyrightStatus = ServerConfigurationService.getString("default.copyright");
state.setAttribute(DEFAULT_COPYRIGHT, defaultCopyrightStatus);
}
String encoding = data.getRequest().getCharacterEncoding();
new_items = new Vector();
for(int i = 0; i < CREATE_MAX_ITEMS; i++)
{
EditItem item = new EditItem(itemType);
if(encoding != null)
{
item.setEncoding(encoding);
}
item.setCopyrightStatus(defaultCopyrightStatus);
new_items.add(item);
}
current_stack_frame.put(STATE_STACK_CREATE_ITEMS, new_items);
}
if(new_items != null && new_items.size() > twiggleNumber)
{
EditItem item = (EditItem) new_items.get(twiggleNumber);
if(item != null)
{
item.showMetadataGroup(metadataGroup);
}
}
// clear display of error messages
state.setAttribute(STATE_CREATE_ALERTS, new HashSet());
Iterator it = new_items.iterator();
while(it.hasNext())
{
EditItem item = (EditItem) it.next();
item.clearMissing();
}
}
else if(flow.equals("hideOptional"))
{
captureMultipleValues(state, params, false);
int twiggleNumber = params.getInt("twiggleNumber", 0);
String metadataGroup = params.getString("metadataGroup");
List new_items = (List) current_stack_frame.get(STATE_STACK_CREATE_ITEMS);
if(new_items == null)
{
String defaultCopyrightStatus = (String) state.getAttribute(DEFAULT_COPYRIGHT);
if(defaultCopyrightStatus == null || defaultCopyrightStatus.trim().equals(""))
{
defaultCopyrightStatus = ServerConfigurationService.getString("default.copyright");
state.setAttribute(DEFAULT_COPYRIGHT, defaultCopyrightStatus);
}
String encoding = data.getRequest().getCharacterEncoding();
new_items = new Vector();
for(int i = 0; i < CREATE_MAX_ITEMS; i++)
{
EditItem item = new EditItem(itemType);
if(encoding != null)
{
item.setEncoding(encoding);
}
item.setCopyrightStatus(defaultCopyrightStatus);
new_items.add(item);
}
current_stack_frame.put(STATE_STACK_CREATE_ITEMS, new_items);
}
if(new_items != null && new_items.size() > twiggleNumber)
{
EditItem item = (EditItem) new_items.get(twiggleNumber);
if(item != null)
{
item.hideMetadataGroup(metadataGroup);
}
}
// clear display of error messages
state.setAttribute(STATE_CREATE_ALERTS, new HashSet());
Iterator it = new_items.iterator();
while(it.hasNext())
{
EditItem item = (EditItem) it.next();
item.clearMissing();
}
}
alerts = (Set) state.getAttribute(STATE_CREATE_ALERTS);
if(alerts == null)
{
alerts = new HashSet();
state.setAttribute(STATE_CREATE_ALERTS, alerts);
}
Iterator alertIt = alerts.iterator();
while(alertIt.hasNext())
{
String alert = (String) alertIt.next();
addCreateContextAlert(state, alert);
//addAlert(state, alert);
}
alerts.clear();
current_stack_frame.put(STATE_CREATE_MISSING_ITEM, missing);
if(pop)
{
List new_items = (List) current_stack_frame.get(ResourcesAction.STATE_HELPER_NEW_ITEMS);
String helper_changed = (String) state.getAttribute(STATE_HELPER_CHANGED);
if(Boolean.TRUE.toString().equals(helper_changed))
{
// get list of attachments?
if(new_items != null)
{
List attachments = (List) state.getAttribute(STATE_ATTACHMENTS);
if(attachments == null)
{
attachments = EntityManager.newReferenceList();
state.setAttribute(STATE_ATTACHMENTS, attachments);
}
Iterator it = new_items.iterator();
while(it.hasNext())
{
AttachItem item = (AttachItem) it.next();
try
{
ContentResource resource = ContentHostingService.getResource(item.getId());
if (checkSelctItemFilter(resource, state))
{
attachments.add(resource.getReference());
}
else
{
it.remove();
addAlert(state, (String) rb.getFormattedMessage("filter", new Object[]{item.getDisplayName()}));
}
}
catch (PermissionException e)
{
addAlert(state, (String) rb.getFormattedMessage("filter", new Object[]{item.getDisplayName()}));
}
catch (IdUnusedException e)
{
addAlert(state, (String) rb.getFormattedMessage("filter", new Object[]{item.getDisplayName()}));
}
catch (TypeException e)
{
addAlert(state, (String) rb.getFormattedMessage("filter", new Object[]{item.getDisplayName()}));
}
Reference ref = EntityManager.newReference(ContentHostingService.getReference(item.getId()));
}
}
}
popFromStack(state);
resetCurrentMode(state);
if(!ResourcesAction.isStackEmpty(state) && new_items != null)
{
current_stack_frame = peekAtStack(state);
List old_items = (List) current_stack_frame.get(STATE_HELPER_NEW_ITEMS);
if(old_items == null)
{
old_items = new Vector();
current_stack_frame.put(STATE_HELPER_NEW_ITEMS, old_items);
}
old_items.addAll(new_items);
}
}
} // doCreateitem
private static void createLink(RunData data, SessionState state)
{
ParameterParser params = data.getParameters ();
Map current_stack_frame = peekAtStack(state);
String field = params.getString("field");
if(field == null)
{
}
else
{
current_stack_frame.put(ResourcesAction.STATE_ATTACH_FORM_FIELD, field);
}
//state.setAttribute(ResourcesAction.STATE_MODE, ResourcesAction.MODE_HELPER);
state.setAttribute(ResourcesAction.STATE_RESOURCES_HELPER_MODE, ResourcesAction.MODE_ATTACHMENT_SELECT);
state.setAttribute(ResourcesAction.STATE_ATTACH_CARDINALITY, ResourcesAction.CARDINALITY_SINGLE);
// put a copy of the attachments into the state
// state.setAttribute(ResourcesAction.STATE_ATTACHMENTS, EntityManager.newReferenceList());
// whether there is already an attachment
/*
if (attachments.size() > 0)
{
sstate.setAttribute(ResourcesAction.STATE_HAS_ATTACHMENT_BEFORE, Boolean.TRUE);
}
else
{
sstate.setAttribute(ResourcesAction.STATE_HAS_ATTACHMENT_BEFORE, Boolean.FALSE);
}
*/
// cancel copy if there is one in progress
if(! Boolean.FALSE.toString().equals(state.getAttribute (STATE_COPY_FLAG)))
{
initCopyContext(state);
}
// cancel move if there is one in progress
if(! Boolean.FALSE.toString().equals(state.getAttribute (STATE_MOVE_FLAG)))
{
initMoveContext(state);
}
}
/**
* Add a new StructuredArtifact to ContentHosting for each EditItem in the state attribute named STATE_STACK_CREATE_ITEMS.
* The number of items to be added is indicated by the state attribute named STATE_STACK_CREATE_NUMBER, and
* the items are added to the collection identified by the state attribute named STATE_STACK_CREATE_COLLECTION_ID.
* @param state
*/
private static void createStructuredArtifacts(SessionState state)
{
Map current_stack_frame = peekAtStack(state);
List new_items = (List) current_stack_frame.get(STATE_STACK_CREATE_ITEMS);
if(new_items == null)
{
String defaultCopyrightStatus = (String) state.getAttribute(DEFAULT_COPYRIGHT);
if(defaultCopyrightStatus == null || defaultCopyrightStatus.trim().equals(""))
{
defaultCopyrightStatus = ServerConfigurationService.getString("default.copyright");
state.setAttribute(DEFAULT_COPYRIGHT, defaultCopyrightStatus);
}
String itemType = (String) current_stack_frame.get(STATE_STACK_CREATE_TYPE);
if(itemType == null)
{
itemType = (String) state.getAttribute(STATE_CREATE_TYPE);
if(itemType == null)
{
itemType = ResourcesAction.TYPE_FORM;
}
current_stack_frame.put(STATE_STACK_CREATE_TYPE, itemType);
}
String encoding = (String) state.getAttribute(STATE_ENCODING);
new_items = new Vector();
for(int i = 0; i < CREATE_MAX_ITEMS; i++)
{
EditItem item = new EditItem(itemType);
if(encoding != null)
{
item.setEncoding(encoding);
}
item.setCopyrightStatus(defaultCopyrightStatus);
new_items.add(item);
}
current_stack_frame.put(STATE_STACK_CREATE_ITEMS, new_items);
}
String collectionId = (String) current_stack_frame.get(STATE_STACK_CREATE_COLLECTION_ID);
if(collectionId == null || collectionId.trim().length() == 0)
{
collectionId = (String) state.getAttribute(STATE_CREATE_COLLECTION_ID);
if(collectionId == null || collectionId.trim().length() == 0)
{
collectionId = ContentHostingService.getSiteCollection(ToolManager.getCurrentPlacement().getContext());
}
current_stack_frame.put(STATE_STACK_CREATE_COLLECTION_ID, collectionId);
}
Set alerts = (Set) state.getAttribute(STATE_CREATE_ALERTS);
if(alerts == null)
{
alerts = new HashSet();
state.setAttribute(STATE_CREATE_ALERTS, alerts);
}
Integer number = (Integer) current_stack_frame.get(STATE_STACK_CREATE_NUMBER);
if(number == null)
{
number = (Integer) state.getAttribute(STATE_CREATE_NUMBER);
if(number == null)
{
number = new Integer(1);
}
current_stack_frame.put(STATE_STACK_CREATE_NUMBER, number);
}
int numberOfItems = number.intValue();
SchemaBean rootSchema = (SchemaBean) current_stack_frame.get(STATE_STACK_STRUCT_OBJ_SCHEMA);
SchemaNode rootNode = rootSchema.getSchema();
outerloop: for(int i = 0; i < numberOfItems; i++)
{
EditItem item = (EditItem) new_items.get(i);
if(item.isBlank())
{
continue;
}
SaveArtifactAttempt attempt = new SaveArtifactAttempt(item, rootNode);
validateStructuredArtifact(attempt);
List errors = attempt.getErrors();
if(errors.isEmpty())
{
try
{
ResourcePropertiesEdit resourceProperties = ContentHostingService.newResourceProperties ();
resourceProperties.addProperty (ResourceProperties.PROP_DISPLAY_NAME, item.getName());
resourceProperties.addProperty (ResourceProperties.PROP_DESCRIPTION, item.getDescription());
resourceProperties.addProperty(ResourceProperties.PROP_CONTENT_ENCODING, "UTF-8");
resourceProperties.addProperty(ResourceProperties.PROP_STRUCTOBJ_TYPE, item.getFormtype());
resourceProperties.addProperty(ContentHostingService.PROP_ALTERNATE_REFERENCE, org.sakaiproject.metaobj.shared.mgt.MetaobjEntityManager.METAOBJ_ENTITY_PREFIX);
List metadataGroups = (List) state.getAttribute(STATE_METADATA_GROUPS);
saveMetadata(resourceProperties, metadataGroups, item);
String filename = Validator.escapeResourceName(item.getName()).trim();
String extension = ".xml";
int attemptNum = 0;
String attemptStr = "";
String newResourceId = collectionId + filename + attemptStr + extension;
if(newResourceId.length() > ContentHostingService.MAXIMUM_RESOURCE_ID_LENGTH)
{
alerts.add(rb.getString("toolong") + " " + newResourceId);
continue outerloop;
}
try
{
ContentResource resource = ContentHostingService.addResource (filename + extension,
collectionId,
MAXIMUM_ATTEMPTS_FOR_UNIQUENESS,
MIME_TYPE_STRUCTOBJ,
item.getContent(),
resourceProperties,
item.getNotification());
Boolean preventPublicDisplay = (Boolean) state.getAttribute(STATE_PREVENT_PUBLIC_DISPLAY);
if(preventPublicDisplay == null)
{
preventPublicDisplay = Boolean.FALSE;
state.setAttribute(STATE_PREVENT_PUBLIC_DISPLAY, preventPublicDisplay);
}
if(preventPublicDisplay.equals(Boolean.FALSE))
{
if (! RESOURCES_MODE_DROPBOX.equalsIgnoreCase((String) state.getAttribute(STATE_MODE_RESOURCES)))
{
if (!item.isPubviewset())
{
ContentHostingService.setPubView(resource.getId(), item.isPubview());
}
}
}
String mode = (String) state.getAttribute(STATE_MODE);
if(MODE_HELPER.equals(mode))
{
String helper_mode = (String) state.getAttribute(STATE_RESOURCES_HELPER_MODE);
if(helper_mode != null && MODE_ATTACHMENT_NEW_ITEM_INIT.equals(helper_mode))
{
// add to the attachments vector
List attachments = EntityManager.newReferenceList();
Reference ref = EntityManager.newReference(ContentHostingService.getReference(resource.getId()));
attachments.add(ref);
cleanupState(state);
state.setAttribute(STATE_ATTACHMENTS, attachments);
}
else
{
Object attach_links = current_stack_frame.get(STATE_ATTACH_LINKS);
if(attach_links == null)
{
attach_links = state.getAttribute(STATE_ATTACH_LINKS);
if(attach_links != null)
{
current_stack_frame.put(STATE_ATTACH_LINKS, attach_links);
}
}
if(attach_links == null)
{
attachItem(resource.getId(), state);
}
else
{
attachLink(resource.getId(), state);
}
}
}
}
catch(PermissionException e)
{
alerts.add(rb.getString("notpermis12"));
continue outerloop;
}
catch(IdInvalidException e)
{
alerts.add(rb.getString("title") + " " + e.getMessage ());
continue outerloop;
}
catch(IdLengthException e)
{
alerts.add(rb.getString("toolong") + " " + e.getMessage());
continue outerloop;
}
catch(IdUniquenessException e)
{
alerts.add("Could not add this item to this folder");
continue outerloop;
}
catch(InconsistentException e)
{
alerts.add(RESOURCE_INVALID_TITLE_STRING);
continue outerloop;
}
catch(OverQuotaException e)
{
alerts.add(rb.getString("overquota"));
continue outerloop;
}
catch(ServerOverloadException e)
{
alerts.add(rb.getString("failed"));
continue outerloop;
}
}
catch(RuntimeException e)
{
logger.error("ResourcesAction.createStructuredArtifacts ***** Unknown Exception ***** " + e.getMessage());
alerts.add(rb.getString("failed"));
}
HashMap currentMap = (HashMap) state.getAttribute(STATE_EXPANDED_COLLECTIONS);
if(currentMap == null)
{
// do nothing
}
else if(!currentMap.containsKey(collectionId))
{
try
{
currentMap.put (collectionId,ContentHostingService.getCollection (collectionId));
state.setAttribute(STATE_EXPANDED_COLLECTIONS, currentMap);
// add this folder id into the set to be event-observed
addObservingPattern(collectionId, state);
}
catch (IdUnusedException ignore)
{
}
catch (TypeException ignore)
{
}
catch (PermissionException ignore)
{
}
}
state.setAttribute(STATE_EXPANDED_COLLECTIONS, currentMap);
}
else
{
Iterator errorIt = errors.iterator();
while(errorIt.hasNext())
{
ValidationError error = (ValidationError) errorIt.next();
alerts.add(error.getDefaultMessage());
}
}
}
state.setAttribute(STATE_CREATE_ALERTS, alerts);
}
/**
* Convert from a hierarchical list of ResourcesMetadata objects to an org.w3.dom.Document,
* then to a string representation, then to a metaobj ElementBean. Validate the ElementBean
* against a SchemaBean. If it validates, save the string representation. Otherwise, on
* return, the parameter contains a non-empty list of ValidationError objects describing the
* problems.
* @param attempt A wrapper for the EditItem object which contains the hierarchical list of
* ResourcesMetadata objects for this form. Also contains an initially empty list of
* ValidationError objects that describes any of the problems found in validating the form.
*/
private static void validateStructuredArtifact(SaveArtifactAttempt attempt)
{
EditItem item = attempt.getItem();
ResourcesMetadata form = item.getForm();
Stack processStack = new Stack();
processStack.push(form);
Map parents = new Hashtable();
Document doc = Xml.createDocument();
int count = 0;
while(!processStack.isEmpty())
{
Object object = processStack.pop();
if(object instanceof ResourcesMetadata)
{
ResourcesMetadata element = (ResourcesMetadata) object;
Element node = doc.createElement(element.getLocalname());
if(element.isNested())
{
processStack.push(new ElementCarrier(node, element.getDottedname()));
List children = element.getNestedInstances();
//List children = element.getNested();
for(int k = children.size() - 1; k >= 0; k--)
{
ResourcesMetadata child = (ResourcesMetadata) children.get(k);
processStack.push(child);
parents.put(child.getDottedname(), node);
}
}
else
{
List values = element.getInstanceValues();
Iterator valueIt = values.iterator();
while(valueIt.hasNext())
{
Object value = valueIt.next();
if(value == null)
{
// do nothing
}
else if(value instanceof String)
{
node.appendChild(doc.createTextNode((String)value));
}
else if(value instanceof Time)
{
Time time = (Time) value;
TimeBreakdown breakdown = time.breakdownLocal();
int year = breakdown.getYear();
int month = breakdown.getMonth();
int day = breakdown.getDay();
String date = "" + year + (month < 10 ? "-0" : "-") + month + (day < 10 ? "-0" : "-") + day;
node.appendChild(doc.createTextNode(date));
}
else if(value instanceof Date)
{
Date date = (Date) value;
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
String formatted = df.format(date);
node.appendChild(doc.createTextNode(formatted));
}
else if(value instanceof Reference)
{
node.appendChild(doc.createTextNode(((Reference)value).getId()));
}
else
{
node.appendChild(doc.createTextNode(value.toString()));
}
}
Element parent = (Element) parents.get(element.getDottedname());
if(parent == null)
{
doc.appendChild(node);
count++;
}
else
{
parent.appendChild(node);
}
}
}
else if(object instanceof ElementCarrier)
{
ElementCarrier carrier = (ElementCarrier) object;
Element node = carrier.getElement();
Element parent = (Element) parents.get(carrier.getParent());
if(parent == null)
{
doc.appendChild(node);
count++;
}
else
{
parent.appendChild(node);
}
}
}
String content = Xml.writeDocumentToString(doc);
item.setContent(content);
StructuredArtifactValidationService validator = (StructuredArtifactValidationService) ComponentManager.get("org.sakaiproject.metaobj.shared.mgt.StructuredArtifactValidationService");
List errors = new ArrayList();
// convert the String representation to an ElementBean object. If that fails,
// add an error and return.
ElementBean bean = null;
SAXBuilder builder = new SAXBuilder();
StringReader reader = new StringReader(content);
try
{
org.jdom.Document jdoc = builder.build(reader);
bean = new ElementBean(jdoc.getRootElement(), attempt.getSchema(), true);
}
catch (JDOMException e)
{
// add message to list of errors
errors.add(new ValidationError("","",null,"JDOMException"));
}
catch (IOException e)
{
// add message to list of errors
errors.add(new ValidationError("","",null,"IOException"));
}
// call this.validate(bean, rootSchema, errors) and add results to errors list.
if(bean == null)
{
// add message to list of errors
errors.add(new ValidationError("","",null,"Bean is null"));
}
else
{
errors.addAll(validator.validate(bean));
}
attempt.setErrors(errors);
} // validateStructuredArtifact
/**
* Add a new folder to ContentHosting for each EditItem in the state attribute named STATE_STACK_CREATE_ITEMS.
* The number of items to be added is indicated by the state attribute named STATE_STACK_CREATE_NUMBER, and
* the items are added to the collection identified by the state attribute named STATE_STACK_CREATE_COLLECTION_ID.
* @param state
*/
protected static void createFolders(SessionState state)
{
Set alerts = (Set) state.getAttribute(STATE_CREATE_ALERTS);
if(alerts == null)
{
alerts = new HashSet();
state.setAttribute(STATE_CREATE_ALERTS, alerts);
}
Map current_stack_frame = peekAtStack(state);
List new_items = (List) current_stack_frame.get(STATE_STACK_CREATE_ITEMS);
if(new_items == null)
{
String defaultCopyrightStatus = (String) state.getAttribute(DEFAULT_COPYRIGHT);
if(defaultCopyrightStatus == null || defaultCopyrightStatus.trim().equals(""))
{
defaultCopyrightStatus = ServerConfigurationService.getString("default.copyright");
state.setAttribute(DEFAULT_COPYRIGHT, defaultCopyrightStatus);
}
new_items = new Vector();
for(int i = 0; i < CREATE_MAX_ITEMS; i++)
{
EditItem item = new EditItem(TYPE_FOLDER);
item.setCopyrightStatus(defaultCopyrightStatus);
new_items.add(item);
}
current_stack_frame.put(STATE_STACK_CREATE_ITEMS, new_items);
}
Integer number = (Integer) current_stack_frame.get(STATE_STACK_CREATE_NUMBER);
if(number == null)
{
number = (Integer) state.getAttribute(STATE_CREATE_NUMBER);
current_stack_frame.put(STATE_STACK_CREATE_NUMBER, number);
}
if(number == null)
{
number = new Integer(1);
current_stack_frame.put(STATE_STACK_CREATE_NUMBER, number);
}
String collectionId = (String) current_stack_frame.get(STATE_STACK_CREATE_COLLECTION_ID);
if(collectionId == null || collectionId.trim().length() == 0)
{
collectionId = (String) state.getAttribute(STATE_CREATE_COLLECTION_ID);
if(collectionId == null || collectionId.trim().length() == 0)
{
collectionId = ContentHostingService.getSiteCollection(ToolManager.getCurrentPlacement().getContext());
}
current_stack_frame.put(STATE_STACK_CREATE_COLLECTION_ID, collectionId);
}
int numberOfFolders = 1;
numberOfFolders = number.intValue();
outerloop: for(int i = 0; i < numberOfFolders; i++)
{
EditItem item = (EditItem) new_items.get(i);
if(item.isBlank())
{
continue;
}
String newCollectionId = collectionId + Validator.escapeResourceName(item.getName()) + Entity.SEPARATOR;
if(newCollectionId.length() > ContentHostingService.MAXIMUM_RESOURCE_ID_LENGTH)
{
alerts.add(rb.getString("toolong") + " " + newCollectionId);
continue outerloop;
}
ResourcePropertiesEdit resourceProperties = ContentHostingService.newResourceProperties ();
try
{
resourceProperties.addProperty (ResourceProperties.PROP_DISPLAY_NAME, item.getName());
resourceProperties.addProperty (ResourceProperties.PROP_DESCRIPTION, item.getDescription());
List metadataGroups = (List) state.getAttribute(STATE_METADATA_GROUPS);
saveMetadata(resourceProperties, metadataGroups, item);
ContentCollection collection = ContentHostingService.addCollection (newCollectionId, resourceProperties, item.getGroups());
Boolean preventPublicDisplay = (Boolean) state.getAttribute(STATE_PREVENT_PUBLIC_DISPLAY);
if(preventPublicDisplay == null)
{
preventPublicDisplay = Boolean.FALSE;
state.setAttribute(STATE_PREVENT_PUBLIC_DISPLAY, preventPublicDisplay);
}
if(preventPublicDisplay.equals(Boolean.FALSE))
{
if (! RESOURCES_MODE_DROPBOX.equalsIgnoreCase((String) state.getAttribute(STATE_MODE_RESOURCES)))
{
if (!item.isPubviewset())
{
ContentHostingService.setPubView(collection.getId(), item.isPubview());
}
}
}
}
catch (IdUsedException e)
{
alerts.add(rb.getString("resotitle") + " " + item.getName() + " " + rb.getString("used4"));
}
catch (IdInvalidException e)
{
alerts.add(rb.getString("title") + " " + e.getMessage ());
}
catch (PermissionException e)
{
alerts.add(rb.getString("notpermis5") + " " + item.getName());
}
catch (InconsistentException e)
{
alerts.add(RESOURCE_INVALID_TITLE_STRING);
} // try-catch
}
HashMap currentMap = (HashMap) state.getAttribute(STATE_EXPANDED_COLLECTIONS);
if(!currentMap.containsKey(collectionId))
{
try
{
currentMap.put (collectionId,ContentHostingService.getCollection (collectionId));
state.setAttribute(STATE_EXPANDED_COLLECTIONS, currentMap);
// add this folder id into the set to be event-observed
addObservingPattern(collectionId, state);
}
catch (IdUnusedException ignore)
{
}
catch (TypeException ignore)
{
}
catch (PermissionException ignore)
{
}
}
state.setAttribute(STATE_EXPANDED_COLLECTIONS, currentMap);
state.setAttribute(STATE_CREATE_ALERTS, alerts);
} // createFolders
/**
* Add a new file to ContentHosting for each EditItem in the state attribute named STATE_STACK_CREATE_ITEMS.
* The number of items to be added is indicated by the state attribute named STATE_STACK_CREATE_NUMBER, and
* the items are added to the collection identified by the state attribute named STATE_STACK_CREATE_COLLECTION_ID.
* @param state
*/
protected static void createFiles(SessionState state)
{
Set alerts = (Set) state.getAttribute(STATE_CREATE_ALERTS);
if(alerts == null)
{
alerts = new HashSet();
state.setAttribute(STATE_CREATE_ALERTS, alerts);
}
Map current_stack_frame = peekAtStack(state);
List new_items = (List) current_stack_frame.get(STATE_STACK_CREATE_ITEMS);
if(new_items == null)
{
String defaultCopyrightStatus = (String) state.getAttribute(DEFAULT_COPYRIGHT);
if(defaultCopyrightStatus == null || defaultCopyrightStatus.trim().equals(""))
{
defaultCopyrightStatus = ServerConfigurationService.getString("default.copyright");
state.setAttribute(DEFAULT_COPYRIGHT, defaultCopyrightStatus);
}
new_items = new Vector();
for(int i = 0; i < CREATE_MAX_ITEMS; i++)
{
EditItem item = new EditItem(TYPE_UPLOAD);
item.setCopyrightStatus(defaultCopyrightStatus);
new_items.add(item);
}
current_stack_frame.put(STATE_STACK_CREATE_ITEMS, new_items);
}
Integer number = (Integer) current_stack_frame.get(STATE_STACK_CREATE_NUMBER);
if(number == null)
{
number = (Integer) state.getAttribute(STATE_CREATE_NUMBER);
current_stack_frame.put(STATE_STACK_CREATE_NUMBER, number);
}
if(number == null)
{
number = new Integer(1);
current_stack_frame.put(STATE_STACK_CREATE_NUMBER, number);
}
String collectionId = (String) current_stack_frame.get(STATE_STACK_CREATE_COLLECTION_ID);
if(collectionId == null || collectionId.trim().length() == 0)
{
collectionId = (String) state.getAttribute(STATE_CREATE_COLLECTION_ID);
if(collectionId == null || collectionId.trim().length() == 0)
{
collectionId = ContentHostingService.getSiteCollection(ToolManager.getCurrentPlacement().getContext());
}
current_stack_frame.put(STATE_STACK_CREATE_COLLECTION_ID, collectionId);
}
int numberOfItems = 1;
numberOfItems = number.intValue();
outerloop: for(int i = 0; i < numberOfItems; i++)
{
EditItem item = (EditItem) new_items.get(i);
if(item.isBlank())
{
continue;
}
ResourcePropertiesEdit resourceProperties = ContentHostingService.newResourceProperties ();
resourceProperties.addProperty (ResourceProperties.PROP_DISPLAY_NAME, item.getName());
resourceProperties.addProperty (ResourceProperties.PROP_DESCRIPTION, item.getDescription());
resourceProperties.addProperty (ResourceProperties.PROP_COPYRIGHT, item.getCopyrightInfo());
resourceProperties.addProperty(ResourceProperties.PROP_COPYRIGHT_CHOICE, item.getCopyrightStatus());
if (item.hasCopyrightAlert())
{
resourceProperties.addProperty (ResourceProperties.PROP_COPYRIGHT_ALERT, Boolean.toString(item.hasCopyrightAlert()));
}
else
{
resourceProperties.removeProperty (ResourceProperties.PROP_COPYRIGHT_ALERT);
}
BasicRightsAssignment rightsObj = item.getRights();
rightsObj.addResourceProperties(resourceProperties);
resourceProperties.addProperty(ResourceProperties.PROP_IS_COLLECTION, Boolean.FALSE.toString());
if(item.isHtml())
{
resourceProperties.addProperty(ResourceProperties.PROP_CONTENT_ENCODING, "UTF-8");
}
List metadataGroups = (List) state.getAttribute(STATE_METADATA_GROUPS);
saveMetadata(resourceProperties, metadataGroups, item);
String filename = Validator.escapeResourceName(item.getFilename().trim());
if("".equals(filename))
{
filename = Validator.escapeResourceName(item.getName().trim());
}
resourceProperties.addProperty(ResourceProperties.PROP_ORIGINAL_FILENAME, filename);
try
{
ContentResource resource = ContentHostingService.addResource (filename,
collectionId,
MAXIMUM_ATTEMPTS_FOR_UNIQUENESS,
item.getMimeType(),
item.getContent(),
resourceProperties, item.getNotification());
item.setAdded(true);
Boolean preventPublicDisplay = (Boolean) state.getAttribute(STATE_PREVENT_PUBLIC_DISPLAY);
if(preventPublicDisplay == null)
{
preventPublicDisplay = Boolean.FALSE;
state.setAttribute(STATE_PREVENT_PUBLIC_DISPLAY, preventPublicDisplay);
}
if(preventPublicDisplay.equals(Boolean.FALSE))
{
if (! RESOURCES_MODE_DROPBOX.equalsIgnoreCase((String) state.getAttribute(STATE_MODE_RESOURCES)))
{
if (!item.isPubviewset())
{
ContentHostingService.setPubView(resource.getId(), item.isPubview());
}
}
}
try
{
Collection groupRefs = new Vector();
Iterator it = item.getGroups().iterator();
while(it.hasNext())
{
Group group = (Group) it.next();
groupRefs.add(group.getReference());
}
// TODO: what if parent has groups and user tries to set no groups??
// Should tool prevent that without needing exception??
if(!groupRefs.isEmpty())
{
// TODO: must be atomic with constructor
ContentResourceEdit edit = ContentHostingService.editResource(resource.getId());
edit.setGroupAccess(groupRefs);
ContentHostingService.commitResource(edit);
}
}
catch (IdUnusedException e)
{
}
catch (TypeException e)
{
}
catch (InUseException e)
{
}
catch(InconsistentException e)
{
alerts.add(rb.getString("add.nogroups"));
}
String mode = (String) state.getAttribute(STATE_MODE);
if(MODE_HELPER.equals(mode))
{
String helper_mode = (String) state.getAttribute(STATE_RESOURCES_HELPER_MODE);
if(helper_mode != null && MODE_ATTACHMENT_NEW_ITEM_INIT.equals(helper_mode))
{
// add to the attachments vector
List attachments = EntityManager.newReferenceList();
Reference ref = EntityManager.newReference(ContentHostingService.getReference(resource.getId()));
attachments.add(ref);
cleanupState(state);
state.setAttribute(STATE_ATTACHMENTS, attachments);
}
else
{
Object attach_links = current_stack_frame.get(STATE_ATTACH_LINKS);
if(attach_links == null)
{
attach_links = state.getAttribute(STATE_ATTACH_LINKS);
if(attach_links != null)
{
current_stack_frame.put(STATE_ATTACH_LINKS, attach_links);
}
}
if(attach_links == null)
{
attachItem(resource.getId(), state);
}
else
{
attachLink(resource.getId(), state);
}
}
}
}
catch(PermissionException e)
{
alerts.add(rb.getString("notpermis12"));
continue outerloop;
}
catch(IdInvalidException e)
{
alerts.add(rb.getString("title") + " " + e.getMessage ());
continue outerloop;
}
catch(IdLengthException e)
{
alerts.add(rb.getString("toolong") + " " + e.getMessage());
continue outerloop;
}
catch(IdUniquenessException e)
{
alerts.add("Could not add this item to this folder");
continue outerloop;
}
catch(InconsistentException e)
{
alerts.add(RESOURCE_INVALID_TITLE_STRING);
continue outerloop;
}
catch(OverQuotaException e)
{
alerts.add(rb.getString("overquota"));
continue outerloop;
}
catch(ServerOverloadException e)
{
alerts.add(rb.getString("failed"));
continue outerloop;
}
catch(RuntimeException e)
{
logger.error("ResourcesAction.createFiles ***** Unknown Exception ***** " + e.getMessage());
alerts.add(rb.getString("failed"));
continue outerloop;
}
}
HashMap currentMap = (HashMap) state.getAttribute(STATE_EXPANDED_COLLECTIONS);
if(currentMap == null)
{
// do nothing
}
else
{
if(!currentMap.containsKey(collectionId))
{
try
{
currentMap.put (collectionId,ContentHostingService.getCollection (collectionId));
state.setAttribute(STATE_EXPANDED_COLLECTIONS, currentMap);
// add this folder id into the set to be event-observed
addObservingPattern(collectionId, state);
}
catch (IdUnusedException ignore)
{
}
catch (TypeException ignore)
{
}
catch (PermissionException ignore)
{
}
}
state.setAttribute(STATE_EXPANDED_COLLECTIONS, currentMap);
}
state.setAttribute(STATE_CREATE_ALERTS, alerts);
} // createFiles
/**
* Process user's request to add an instance of a particular field to a structured object.
* @param data
*/
public static void doInsertValue(RunData data)
{
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
ParameterParser params = data.getParameters ();
captureMultipleValues(state, params, false);
Map current_stack_frame = peekAtStack(state);
String field = params.getString("field");
EditItem item = null;
String mode = (String) state.getAttribute(STATE_MODE);
if (MODE_CREATE.equals(mode))
{
int index = params.getInt("index");
List new_items = (List) current_stack_frame.get(STATE_STACK_CREATE_ITEMS);
if(new_items != null)
{
item = (EditItem) new_items.get(index);
}
}
else if(MODE_EDIT.equals(mode))
{
item = (EditItem) current_stack_frame.get(STATE_STACK_EDIT_ITEM);
}
if(item != null)
{
addInstance(field, item.getProperties());
}
} // doInsertValue
/**
* Search a flat list of ResourcesMetadata properties for one whose localname matches "field".
* If found and the field can have additional instances, increment the count for that item.
* @param field
* @param properties
* @return true if the field is found, false otherwise.
*/
protected static boolean addInstance(String field, List properties)
{
Iterator propIt = properties.iterator();
boolean found = false;
while(!found && propIt.hasNext())
{
ResourcesMetadata property = (ResourcesMetadata) propIt.next();
if(field.equals(property.getDottedname()))
{
found = true;
property.incrementCount();
}
}
return found;
}
public static void doAttachitem(RunData data)
{
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
ParameterParser params = data.getParameters ();
state.setAttribute(STATE_LIST_SELECTIONS, new TreeSet());
String itemId = params.getString("itemId");
Map current_stack_frame = peekAtStack(state);
Object attach_links = current_stack_frame.get(STATE_ATTACH_LINKS);
if(attach_links == null)
{
attach_links = state.getAttribute(STATE_ATTACH_LINKS);
if(attach_links != null)
{
current_stack_frame.put(STATE_ATTACH_LINKS, attach_links);
}
}
if(attach_links == null)
{
attachItem(itemId, state);
}
else
{
attachLink(itemId, state);
}
state.setAttribute(STATE_RESOURCES_HELPER_MODE, MODE_ATTACHMENT_SELECT_INIT);
// popFromStack(state);
// resetCurrentMode(state);
}
public static void doAttachupload(RunData data)
{
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
ParameterParser params = data.getParameters ();
Map current_stack_frame = peekAtStack(state);
String max_file_size_mb = (String) state.getAttribute(STATE_FILE_UPLOAD_MAX_SIZE);
int max_bytes = 1096 * 1096;
try
{
max_bytes = Integer.parseInt(max_file_size_mb) * 1096 * 1096;
}
catch(Exception e)
{
// if unable to parse an integer from the value
// in the properties file, use 1 MB as a default
max_file_size_mb = "1";
max_bytes = 1096 * 1096;
}
FileItem fileitem = null;
try
{
fileitem = params.getFileItem("upload");
}
catch(Exception e)
{
}
if(fileitem == null)
{
// "The user submitted a file to upload but it was too big!"
addAlert(state, rb.getString("size") + " " + max_file_size_mb + "MB " + rb.getString("exceeded2"));
}
else if (fileitem.getFileName() == null || fileitem.getFileName().length() == 0)
{
addAlert(state, rb.getString("choosefile7"));
}
else if (fileitem.getFileName().length() > 0)
{
String filename = Validator.getFileName(fileitem.getFileName());
byte[] bytes = fileitem.get();
String contentType = fileitem.getContentType();
if(bytes.length >= max_bytes)
{
addAlert(state, rb.getString("size") + " " + max_file_size_mb + "MB " + rb.getString("exceeded2"));
}
else if(bytes.length > 0)
{
// we just want the file name part - strip off any drive and path stuff
String name = Validator.getFileName(filename);
String resourceId = Validator.escapeResourceName(name);
// make a set of properties to add for the new resource
ResourcePropertiesEdit props = ContentHostingService.newResourceProperties();
props.addProperty(ResourceProperties.PROP_DISPLAY_NAME, name);
props.addProperty(ResourceProperties.PROP_DESCRIPTION, filename);
// make an attachment resource for this URL
try
{
String siteId = ToolManager.getCurrentPlacement().getContext();
String toolName = (String) current_stack_frame.get(STATE_ATTACH_TOOL_NAME);
if(toolName == null)
{
toolName = (String) state.getAttribute(STATE_ATTACH_TOOL_NAME);
if(toolName == null)
{
toolName = ToolManager.getCurrentTool().getTitle();
}
current_stack_frame.put(STATE_ATTACH_TOOL_NAME, toolName);
}
ContentResource attachment = ContentHostingService.addAttachmentResource(resourceId, siteId, toolName, contentType, bytes, props);
List new_items = (List) current_stack_frame.get(STATE_HELPER_NEW_ITEMS);
if(new_items == null)
{
new_items = (List) state.getAttribute(STATE_HELPER_NEW_ITEMS);
if(new_items == null)
{
new_items = new Vector();
}
current_stack_frame.put(STATE_HELPER_NEW_ITEMS, new_items);
}
String containerId = ContentHostingService.getContainingCollectionId (attachment.getId());
String accessUrl = attachment.getUrl();
AttachItem item = new AttachItem(attachment.getId(), filename, containerId, accessUrl);
item.setContentType(contentType);
new_items.add(item);
//check -- jim
state.setAttribute(STATE_HELPER_CHANGED, Boolean.TRUE.toString());
current_stack_frame.put(STATE_HELPER_NEW_ITEMS, new_items);
}
catch (PermissionException e)
{
addAlert(state, rb.getString("notpermis4"));
}
catch(OverQuotaException e)
{
addAlert(state, rb.getString("overquota"));
}
catch(ServerOverloadException e)
{
addAlert(state, rb.getString("failed"));
}
catch(IdInvalidException ignore)
{
// other exceptions should be caught earlier
}
catch(InconsistentException ignore)
{
// other exceptions should be caught earlier
}
catch(IdUsedException ignore)
{
// other exceptions should be caught earlier
}
catch(RuntimeException e)
{
logger.error("ResourcesAction.doAttachupload ***** Unknown Exception ***** " + e.getMessage());
addAlert(state, rb.getString("failed"));
}
}
else
{
addAlert(state, rb.getString("choosefile7"));
}
}
state.setAttribute(STATE_RESOURCES_HELPER_MODE, MODE_ATTACHMENT_SELECT_INIT);
//popFromStack(state);
//resetCurrentMode(state);
} // doAttachupload
public static void doAttachurl(RunData data)
{
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
ParameterParser params = data.getParameters ();
Map current_stack_frame = peekAtStack(state);
String url = params.getCleanString("url");
ResourcePropertiesEdit resourceProperties = ContentHostingService.newResourceProperties ();
resourceProperties.addProperty (ResourceProperties.PROP_DISPLAY_NAME, url);
resourceProperties.addProperty (ResourceProperties.PROP_DESCRIPTION, url);
resourceProperties.addProperty(ResourceProperties.PROP_IS_COLLECTION, Boolean.FALSE.toString());
try
{
url = validateURL(url);
byte[] newUrl = url.getBytes();
String newResourceId = Validator.escapeResourceName(url);
String siteId = ToolManager.getCurrentPlacement().getContext();
String toolName = (String) current_stack_frame.get(STATE_ATTACH_TOOL_NAME);
if(toolName == null)
{
toolName = (String) state.getAttribute(STATE_ATTACH_TOOL_NAME);
if(toolName == null)
{
toolName = ToolManager.getCurrentTool().getTitle();
}
current_stack_frame.put(STATE_ATTACH_TOOL_NAME, toolName);
}
ContentResource attachment = ContentHostingService.addAttachmentResource(newResourceId, siteId, toolName, ResourceProperties.TYPE_URL, newUrl, resourceProperties);
List new_items = (List) current_stack_frame.get(STATE_HELPER_NEW_ITEMS);
if(new_items == null)
{
new_items = (List) state.getAttribute(STATE_HELPER_NEW_ITEMS);
if(new_items == null)
{
new_items = new Vector();
}
current_stack_frame.put(STATE_HELPER_NEW_ITEMS, new_items);
}
String containerId = ContentHostingService.getContainingCollectionId (attachment.getId());
String accessUrl = attachment.getUrl();
AttachItem item = new AttachItem(attachment.getId(), url, containerId, accessUrl);
item.setContentType(ResourceProperties.TYPE_URL);
new_items.add(item);
state.setAttribute(STATE_HELPER_CHANGED, Boolean.TRUE.toString());
current_stack_frame.put(STATE_HELPER_NEW_ITEMS, new_items);
}
catch(MalformedURLException e)
{
// invalid url
addAlert(state, rb.getString("validurl") + " \"" + url + "\" " + rb.getString("invalid"));
}
catch (PermissionException e)
{
addAlert(state, rb.getString("notpermis4"));
}
catch(OverQuotaException e)
{
addAlert(state, rb.getString("overquota"));
}
catch(ServerOverloadException e)
{
addAlert(state, rb.getString("failed"));
}
catch(IdInvalidException ignore)
{
// other exceptions should be caught earlier
}
catch(IdUsedException ignore)
{
// other exceptions should be caught earlier
}
catch(InconsistentException ignore)
{
// other exceptions should be caught earlier
}
catch(RuntimeException e)
{
logger.error("ResourcesAction.doAttachurl ***** Unknown Exception ***** " + e.getMessage());
addAlert(state, rb.getString("failed"));
}
state.setAttribute(STATE_RESOURCES_HELPER_MODE, MODE_ATTACHMENT_SELECT_INIT);
// popFromStack(state);
// resetCurrentMode(state);
}
public static void doRemoveitem(RunData data)
{
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
ParameterParser params = data.getParameters ();
Map current_stack_frame = peekAtStack(state);
state.setAttribute(STATE_LIST_SELECTIONS, new TreeSet());
String itemId = params.getString("itemId");
List new_items = (List) current_stack_frame.get(STATE_HELPER_NEW_ITEMS);
if(new_items == null)
{
new_items = (List) state.getAttribute(STATE_HELPER_NEW_ITEMS);
if(new_items == null)
{
new_items = new Vector();
}
current_stack_frame.put(STATE_HELPER_NEW_ITEMS, new_items);
}
AttachItem item = null;
boolean found = false;
Iterator it = new_items.iterator();
while(!found && it.hasNext())
{
item = (AttachItem) it.next();
if(item.getId().equals(itemId))
{
found = true;
}
}
if(found && item != null)
{
new_items.remove(item);
List removed = (List) state.getAttribute(STATE_REMOVED_ATTACHMENTS);
if(removed == null)
{
removed = new Vector();
state.setAttribute(STATE_REMOVED_ATTACHMENTS, removed);
}
removed.add(item);
state.setAttribute(STATE_HELPER_CHANGED, Boolean.TRUE.toString());
}
} // doRemoveitem
public static void doAddattachments(RunData data)
{
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
ParameterParser params = data.getParameters ();
// cancel copy if there is one in progress
if(! Boolean.FALSE.toString().equals(state.getAttribute (STATE_COPY_FLAG)))
{
initCopyContext(state);
}
// cancel move if there is one in progress
if(! Boolean.FALSE.toString().equals(state.getAttribute (STATE_MOVE_FLAG)))
{
initMoveContext(state);
}
state.setAttribute(STATE_LIST_SELECTIONS, new TreeSet());
Map current_stack_frame = peekAtStack(state);
List new_items = (List) current_stack_frame.get(STATE_HELPER_NEW_ITEMS);
if(new_items == null)
{
new_items = (List) state.getAttribute(STATE_HELPER_NEW_ITEMS);
if(new_items == null)
{
new_items = new Vector();
}
current_stack_frame.put(STATE_HELPER_NEW_ITEMS, new_items);
}
List removed = (List) current_stack_frame.get(STATE_REMOVED_ATTACHMENTS);
if(removed == null)
{
removed = (List) state.getAttribute(STATE_REMOVED_ATTACHMENTS);
if(removed == null)
{
removed = new Vector();
}
current_stack_frame.put(STATE_REMOVED_ATTACHMENTS, removed);
}
Iterator removeIt = removed.iterator();
while(removeIt.hasNext())
{
AttachItem item = (AttachItem) removeIt.next();
try
{
if(ContentHostingService.isAttachmentResource(item.getId()))
{
ContentResourceEdit edit = ContentHostingService.editResource(item.getId());
ContentHostingService.removeResource(edit);
ContentCollectionEdit coll = ContentHostingService.editCollection(item.getCollectionId());
ContentHostingService.removeCollection(coll);
}
}
catch(Exception ignore)
{
// log failure
}
}
state.removeAttribute(STATE_REMOVED_ATTACHMENTS);
// add to the attachments vector
List attachments = EntityManager.newReferenceList();
Iterator it = new_items.iterator();
while(it.hasNext())
{
AttachItem item = (AttachItem) it.next();
try
{
Reference ref = EntityManager.newReference(ContentHostingService.getReference(item.getId()));
attachments.add(ref);
}
catch(Exception e)
{
}
}
cleanupState(state);
state.setAttribute(STATE_ATTACHMENTS, attachments);
// end up in main mode
popFromStack(state);
resetCurrentMode(state);
current_stack_frame = peekAtStack(state);
String field = null;
// if there is at least one attachment
if (attachments.size() > 0)
{
//check -- jim
state.setAttribute(AttachmentAction.STATE_HAS_ATTACHMENT_BEFORE, Boolean.TRUE);
if(current_stack_frame == null)
{
}
else
{
field = (String) current_stack_frame.get(STATE_ATTACH_FORM_FIELD);
}
}
if(field != null)
{
int index = 0;
String fieldname = field;
Matcher matcher = INDEXED_FORM_FIELD_PATTERN.matcher(field.trim());
if(matcher.matches())
{
fieldname = matcher.group(0);
index = Integer.parseInt(matcher.group(1));
}
// we are trying to attach a link to a form field and there is at least one attachment
if(new_items == null)
{
new_items = (List) current_stack_frame.get(ResourcesAction.STATE_HELPER_NEW_ITEMS);
if(new_items == null)
{
new_items = (List) state.getAttribute(ResourcesAction.STATE_HELPER_NEW_ITEMS);
}
}
EditItem edit_item = null;
List edit_items = (List) current_stack_frame.get(ResourcesAction.STATE_STACK_CREATE_ITEMS);
if(edit_items == null)
{
edit_item = (EditItem) current_stack_frame.get(ResourcesAction.STATE_STACK_EDIT_ITEM);
}
else
{
edit_item = (EditItem) edit_items.get(0);
}
if(edit_item != null)
{
Reference ref = (Reference) attachments.get(0);
edit_item.setPropertyValue(fieldname, index, ref);
}
}
}
public static void attachItem(String itemId, SessionState state)
{
org.sakaiproject.content.api.ContentHostingService contentService = (org.sakaiproject.content.api.ContentHostingService) state.getAttribute (STATE_CONTENT_SERVICE);
Map current_stack_frame = peekAtStack(state);
List new_items = (List) current_stack_frame.get(STATE_HELPER_NEW_ITEMS);
if(new_items == null)
{
new_items = (List) state.getAttribute(STATE_HELPER_NEW_ITEMS);
if(new_items == null)
{
new_items = new Vector();
}
current_stack_frame.put(STATE_HELPER_NEW_ITEMS, new_items);
}
boolean found = false;
Iterator it = new_items.iterator();
while(!found && it.hasNext())
{
AttachItem item = (AttachItem) it.next();
if(item.getId().equals(itemId))
{
found = true;
}
}
if(!found)
{
try
{
ContentResource res = contentService.getResource(itemId);
ResourceProperties props = res.getProperties();
ResourcePropertiesEdit newprops = contentService.newResourceProperties();
newprops.set(props);
byte[] bytes = res.getContent();
String contentType = res.getContentType();
String filename = Validator.getFileName(itemId);
String resourceId = Validator.escapeResourceName(filename);
String siteId = ToolManager.getCurrentPlacement().getContext();
String toolName = (String) current_stack_frame.get(STATE_ATTACH_TOOL_NAME);
if(toolName == null)
{
toolName = (String) state.getAttribute(STATE_ATTACH_TOOL_NAME);
if(toolName == null)
{
toolName = ToolManager.getCurrentTool().getTitle();
}
current_stack_frame.put(STATE_ATTACH_TOOL_NAME, toolName);
}
ContentResource attachment = ContentHostingService.addAttachmentResource(resourceId, siteId, toolName, contentType, bytes, props);
String displayName = newprops.getPropertyFormatted(ResourceProperties.PROP_DISPLAY_NAME);
String containerId = contentService.getContainingCollectionId (attachment.getId());
String accessUrl = attachment.getUrl();
AttachItem item = new AttachItem(attachment.getId(), displayName, containerId, accessUrl);
item.setContentType(contentType);
new_items.add(item);
state.setAttribute(STATE_HELPER_CHANGED, Boolean.TRUE.toString());
}
catch (PermissionException e)
{
addAlert(state, rb.getString("notpermis4"));
}
catch(OverQuotaException e)
{
addAlert(state, rb.getString("overquota"));
}
catch(ServerOverloadException e)
{
addAlert(state, rb.getString("failed"));
}
catch(IdInvalidException ignore)
{
// other exceptions should be caught earlier
}
catch(TypeException ignore)
{
// other exceptions should be caught earlier
}
catch(IdUnusedException ignore)
{
// other exceptions should be caught earlier
}
catch(IdUsedException ignore)
{
// other exceptions should be caught earlier
}
catch(InconsistentException ignore)
{
// other exceptions should be caught earlier
}
catch(RuntimeException e)
{
logger.error("ResourcesAction.attachItem ***** Unknown Exception ***** " + e.getMessage());
addAlert(state, rb.getString("failed"));
}
}
current_stack_frame.put(STATE_HELPER_NEW_ITEMS, new_items);
}
public static void attachLink(String itemId, SessionState state)
{
org.sakaiproject.content.api.ContentHostingService contentService = (org.sakaiproject.content.api.ContentHostingService) state.getAttribute (STATE_CONTENT_SERVICE);
Map current_stack_frame = peekAtStack(state);
List new_items = (List) current_stack_frame.get(STATE_HELPER_NEW_ITEMS);
if(new_items == null)
{
new_items = (List) state.getAttribute(STATE_HELPER_NEW_ITEMS);
if(new_items == null)
{
new_items = new Vector();
}
current_stack_frame.put(STATE_HELPER_NEW_ITEMS, new_items);
}
Integer max_cardinality = (Integer) current_stack_frame.get(STATE_ATTACH_CARDINALITY);
if(max_cardinality == null)
{
max_cardinality = (Integer) state.getAttribute(STATE_ATTACH_CARDINALITY);
if(max_cardinality == null)
{
max_cardinality = CARDINALITY_MULTIPLE;
}
current_stack_frame.put(STATE_ATTACH_CARDINALITY, max_cardinality);
}
boolean found = false;
Iterator it = new_items.iterator();
while(!found && it.hasNext())
{
AttachItem item = (AttachItem) it.next();
if(item.getId().equals(itemId))
{
found = true;
}
}
if(!found)
{
try
{
ContentResource res = contentService.getResource(itemId);
ResourceProperties props = res.getProperties();
String contentType = res.getContentType();
String filename = Validator.getFileName(itemId);
String resourceId = Validator.escapeResourceName(filename);
String siteId = ToolManager.getCurrentPlacement().getContext();
String toolName = (String) current_stack_frame.get(STATE_ATTACH_TOOL_NAME);
if(toolName == null)
{
toolName = (String) state.getAttribute(STATE_ATTACH_TOOL_NAME);
if(toolName == null)
{
toolName = ToolManager.getCurrentTool().getTitle();
}
current_stack_frame.put(STATE_ATTACH_TOOL_NAME, toolName);
}
String displayName = props.getPropertyFormatted(ResourceProperties.PROP_DISPLAY_NAME);
String containerId = contentService.getContainingCollectionId (itemId);
String accessUrl = res.getUrl();
AttachItem item = new AttachItem(itemId, displayName, containerId, accessUrl);
item.setContentType(contentType);
new_items.add(item);
state.setAttribute(STATE_HELPER_CHANGED, Boolean.TRUE.toString());
}
catch (PermissionException e)
{
addAlert(state, rb.getString("notpermis4"));
}
catch(TypeException ignore)
{
// other exceptions should be caught earlier
}
catch(IdUnusedException ignore)
{
// other exceptions should be caught earlier
}
catch(RuntimeException e)
{
logger.error("ResourcesAction.attachItem ***** Unknown Exception ***** " + e.getMessage());
addAlert(state, rb.getString("failed"));
}
}
current_stack_frame.put(STATE_HELPER_NEW_ITEMS, new_items);
}
/**
* Add a new URL to ContentHosting for each EditItem in the state attribute named STATE_STACK_CREATE_ITEMS.
* The number of items to be added is indicated by the state attribute named STATE_STACK_CREATE_NUMBER, and
* the items are added to the collection identified by the state attribute named STATE_STACK_CREATE_COLLECTION_ID.
* @param state
*/
protected static void createUrls(SessionState state)
{
Set alerts = (Set) state.getAttribute(STATE_CREATE_ALERTS);
if(alerts == null)
{
alerts = new HashSet();
state.setAttribute(STATE_CREATE_ALERTS, alerts);
}
Map current_stack_frame = peekAtStack(state);
List new_items = (List) current_stack_frame.get(STATE_STACK_CREATE_ITEMS);
Integer number = (Integer) current_stack_frame.get(STATE_STACK_CREATE_NUMBER);
if(number == null)
{
number = (Integer) state.getAttribute(STATE_CREATE_NUMBER);
current_stack_frame.put(STATE_STACK_CREATE_NUMBER, number);
}
if(number == null)
{
number = new Integer(1);
current_stack_frame.put(STATE_STACK_CREATE_NUMBER, number);
}
String collectionId = (String) current_stack_frame.get(STATE_STACK_CREATE_COLLECTION_ID);
if(collectionId == null || collectionId.trim().length() == 0)
{
collectionId = (String) state.getAttribute(STATE_CREATE_COLLECTION_ID);
if(collectionId == null || collectionId.trim().length() == 0)
{
collectionId = ContentHostingService.getSiteCollection(ToolManager.getCurrentPlacement().getContext());
}
current_stack_frame.put(STATE_STACK_CREATE_COLLECTION_ID, collectionId);
}
int numberOfItems = 1;
numberOfItems = number.intValue();
outerloop: for(int i = 0; i < numberOfItems; i++)
{
EditItem item = (EditItem) new_items.get(i);
if(item.isBlank())
{
continue;
}
ResourcePropertiesEdit resourceProperties = ContentHostingService.newResourceProperties ();
resourceProperties.addProperty (ResourceProperties.PROP_DISPLAY_NAME, item.getName());
resourceProperties.addProperty (ResourceProperties.PROP_DESCRIPTION, item.getDescription());
resourceProperties.addProperty(ResourceProperties.PROP_IS_COLLECTION, Boolean.FALSE.toString());
List metadataGroups = (List) state.getAttribute(STATE_METADATA_GROUPS);
saveMetadata(resourceProperties, metadataGroups, item);
byte[] newUrl = item.getFilename().getBytes();
String name = Validator.escapeResourceName(item.getName());
try
{
ContentResource resource = ContentHostingService.addResource (name,
collectionId,
MAXIMUM_ATTEMPTS_FOR_UNIQUENESS,
item.getMimeType(),
newUrl,
resourceProperties, item.getNotification());
item.setAdded(true);
Boolean preventPublicDisplay = (Boolean) state.getAttribute(STATE_PREVENT_PUBLIC_DISPLAY);
if(preventPublicDisplay == null)
{
preventPublicDisplay = Boolean.FALSE;
state.setAttribute(STATE_PREVENT_PUBLIC_DISPLAY, preventPublicDisplay);
}
if(preventPublicDisplay.equals(Boolean.FALSE))
{
if (! RESOURCES_MODE_DROPBOX.equalsIgnoreCase((String) state.getAttribute(STATE_MODE_RESOURCES)))
{
if (!item.isPubviewset())
{
ContentHostingService.setPubView(resource.getId(), item.isPubview());
}
}
}
String mode = (String) state.getAttribute(STATE_MODE);
if(MODE_HELPER.equals(mode))
{
String helper_mode = (String) state.getAttribute(STATE_RESOURCES_HELPER_MODE);
if(helper_mode != null && MODE_ATTACHMENT_NEW_ITEM.equals(helper_mode))
{
// add to the attachments vector
List attachments = EntityManager.newReferenceList();
Reference ref = EntityManager.newReference(ContentHostingService.getReference(resource.getId()));
attachments.add(ref);
cleanupState(state);
state.setAttribute(STATE_ATTACHMENTS, attachments);
}
else
{
Object attach_links = current_stack_frame.get(STATE_ATTACH_LINKS);
if(attach_links == null)
{
attach_links = state.getAttribute(STATE_ATTACH_LINKS);
if(attach_links != null)
{
current_stack_frame.put(STATE_ATTACH_LINKS, attach_links);
}
}
if(attach_links == null)
{
attachItem(resource.getId(), state);
}
else
{
attachLink(resource.getId(), state);
}
}
}
}
catch(PermissionException e)
{
alerts.add(rb.getString("notpermis12"));
continue outerloop;
}
catch(IdInvalidException e)
{
alerts.add(rb.getString("title") + " " + e.getMessage ());
continue outerloop;
}
catch(IdLengthException e)
{
alerts.add(rb.getString("toolong") + " " + e.getMessage());
continue outerloop;
}
catch(IdUniquenessException e)
{
alerts.add("Could not add this item to this folder");
continue outerloop;
}
catch(InconsistentException e)
{
alerts.add(RESOURCE_INVALID_TITLE_STRING);
continue outerloop;
}
catch(OverQuotaException e)
{
alerts.add(rb.getString("overquota"));
continue outerloop;
}
catch(ServerOverloadException e)
{
alerts.add(rb.getString("failed"));
continue outerloop;
}
catch(RuntimeException e)
{
logger.error("ResourcesAction.createFiles ***** Unknown Exception ***** " + e.getMessage());
alerts.add(rb.getString("failed"));
continue outerloop;
}
}
HashMap currentMap = (HashMap) state.getAttribute(STATE_EXPANDED_COLLECTIONS);
if(!currentMap.containsKey(collectionId))
{
try
{
currentMap.put (collectionId,ContentHostingService.getCollection (collectionId));
state.setAttribute(STATE_EXPANDED_COLLECTIONS, currentMap);
// add this folder id into the set to be event-observed
addObservingPattern(collectionId, state);
}
catch (IdUnusedException ignore)
{
}
catch (TypeException ignore)
{
}
catch (PermissionException ignore)
{
}
}
state.setAttribute(STATE_EXPANDED_COLLECTIONS, currentMap);
state.setAttribute(STATE_CREATE_ALERTS, alerts);
} // createUrls
/**
* Build the context for creating folders and items
*/
public static String buildCreateContext (VelocityPortlet portlet,
Context context,
RunData data,
SessionState state)
{
context.put("tlang",rb);
// find the ContentTypeImage service
context.put ("contentTypeImageService", state.getAttribute (STATE_CONTENT_TYPE_IMAGE_SERVICE));
context.put("TYPE_FOLDER", TYPE_FOLDER);
context.put("TYPE_UPLOAD", TYPE_UPLOAD);
context.put("TYPE_HTML", TYPE_HTML);
context.put("TYPE_TEXT", TYPE_TEXT);
context.put("TYPE_URL", TYPE_URL);
context.put("TYPE_FORM", TYPE_FORM);
context.put("SITE_ACCESS", AccessMode.SITE.toString());
context.put("GROUP_ACCESS", AccessMode.GROUPED.toString());
context.put("INHERITED_ACCESS", AccessMode.INHERITED.toString());
context.put("max_upload_size", state.getAttribute(STATE_FILE_UPLOAD_MAX_SIZE));
Map current_stack_frame = peekAtStack(state);
String itemType = (String) current_stack_frame.get(STATE_STACK_CREATE_TYPE);
if(itemType == null || itemType.trim().equals(""))
{
itemType = (String) state.getAttribute(STATE_CREATE_TYPE);
if(itemType == null || itemType.trim().equals(""))
{
itemType = TYPE_UPLOAD;
}
current_stack_frame.put(STATE_STACK_CREATE_TYPE, itemType);
}
context.put("itemType", itemType);
String field = (String) current_stack_frame.get(STATE_ATTACH_FORM_FIELD);
if(field == null)
{
field = (String) state.getAttribute(STATE_ATTACH_FORM_FIELD);
if(field != null)
{
current_stack_frame.put(STATE_ATTACH_FORM_FIELD, field);
state.removeAttribute(STATE_ATTACH_FORM_FIELD);
}
}
String msg = (String) state.getAttribute(STATE_CREATE_MESSAGE);
if (msg != null)
{
context.put("createAlertMessage", msg);
state.removeAttribute(STATE_CREATE_MESSAGE);
}
List new_items = (List) current_stack_frame.get(STATE_STACK_CREATE_ITEMS);
if(new_items == null)
{
String defaultCopyrightStatus = (String) state.getAttribute(DEFAULT_COPYRIGHT);
if(defaultCopyrightStatus == null || defaultCopyrightStatus.trim().equals(""))
{
defaultCopyrightStatus = ServerConfigurationService.getString("default.copyright");
state.setAttribute(DEFAULT_COPYRIGHT, defaultCopyrightStatus);
}
String encoding = data.getRequest().getCharacterEncoding();
new_items = new Vector();
for(int i = 0; i < CREATE_MAX_ITEMS; i++)
{
EditItem item = new EditItem(itemType);
if(encoding != null)
{
item.setEncoding(encoding);
}
item.setCopyrightStatus(defaultCopyrightStatus);
new_items.add(item);
}
current_stack_frame.put(STATE_STACK_CREATE_ITEMS, new_items);
}
context.put("new_items", new_items);
String collectionId = (String) current_stack_frame.get(STATE_STACK_CREATE_COLLECTION_ID);
if(collectionId == null || collectionId.trim().length() == 0)
{
collectionId = (String) state.getAttribute(STATE_CREATE_COLLECTION_ID);
if(collectionId == null || collectionId.trim().length() == 0)
{
collectionId = ContentHostingService.getSiteCollection(ToolManager.getCurrentPlacement().getContext());
}
current_stack_frame.put(STATE_STACK_CREATE_COLLECTION_ID, collectionId);
}
context.put("collectionId", collectionId);
Integer number = (Integer) current_stack_frame.get(STATE_STACK_CREATE_NUMBER);
if(number == null)
{
number = (Integer) state.getAttribute(STATE_CREATE_NUMBER);
current_stack_frame.put(STATE_STACK_CREATE_NUMBER, number);
}
context.put("numberOfItems", number);
context.put("max_number", new Integer(CREATE_MAX_ITEMS));
String homeCollectionId = (String) state.getAttribute (STATE_HOME_COLLECTION_ID);
context.put("homeCollectionId", homeCollectionId);
List collectionPath = getCollectionPath(state);
context.put ("collectionPath", collectionPath);
if(homeCollectionId.equals(collectionId))
{
context.put("atHome", Boolean.TRUE.toString());
}
Collection groups = ContentHostingService.getGroupsWithReadAccess(collectionId);
if(! groups.isEmpty())
{
context.put("siteHasGroups", Boolean.TRUE.toString());
List theGroupsInThisSite = new Vector();
for(int i = 0; i < CREATE_MAX_ITEMS; i++)
{
theGroupsInThisSite.add(groups.iterator());
}
context.put("theGroupsInThisSite", theGroupsInThisSite);
}
String show_form_items = (String) state.getAttribute(STATE_SHOW_FORM_ITEMS);
if(show_form_items == null)
{
show_form_items = (String) state.getAttribute(STATE_SHOW_FORM_ITEMS);
if(show_form_items != null)
{
current_stack_frame.put(STATE_SHOW_FORM_ITEMS,show_form_items);
}
}
if(show_form_items != null)
{
context.put("show_form_items", show_form_items);
}
// copyright
copyrightChoicesIntoContext(state, context);
// put schema for metadata into context
metadataGroupsIntoContext(state, context);
// %%STATE_MODE_RESOURCES%%
if (RESOURCES_MODE_RESOURCES.equalsIgnoreCase((String) state.getAttribute(STATE_MODE_RESOURCES)))
{
context.put("dropboxMode", Boolean.FALSE);
}
else if (RESOURCES_MODE_DROPBOX.equalsIgnoreCase((String) state.getAttribute(STATE_MODE_RESOURCES)))
{
// notshow the public option or notification when in dropbox mode
context.put("dropboxMode", Boolean.TRUE);
}
context.put("siteTitle", state.getAttribute(STATE_SITE_TITLE));
/*
Collection groups = ContentHostingService.getGroupsWithReadAccess(collectionId);
if(! groups.isEmpty())
{
context.put("siteHasGroups", Boolean.TRUE.toString());
context.put("theGroupsInThisSite", groups);
}
*/
if(TYPE_FORM.equals(itemType))
{
List listOfHomes = (List) current_stack_frame.get(STATE_STRUCTOBJ_HOMES);
if(listOfHomes == null)
{
setupStructuredObjects(state);
listOfHomes = (List) current_stack_frame.get(STATE_STRUCTOBJ_HOMES);
}
context.put("homes", listOfHomes);
String formtype = (String) current_stack_frame.get(STATE_STACK_STRUCTOBJ_TYPE);
if(formtype == null)
{
formtype = (String) state.getAttribute(STATE_STRUCTOBJ_TYPE);
if(formtype == null)
{
formtype = "";
}
current_stack_frame.put(STATE_STACK_STRUCTOBJ_TYPE, formtype);
}
context.put("formtype", formtype);
String rootname = (String) current_stack_frame.get(STATE_STACK_STRUCTOBJ_ROOTNAME);
context.put("rootname", rootname);
context.put("STRING", ResourcesMetadata.WIDGET_STRING);
context.put("TEXTAREA", ResourcesMetadata.WIDGET_TEXTAREA);
context.put("BOOLEAN", ResourcesMetadata.WIDGET_BOOLEAN);
context.put("INTEGER", ResourcesMetadata.WIDGET_INTEGER);
context.put("DOUBLE", ResourcesMetadata.WIDGET_DOUBLE);
context.put("DATE", ResourcesMetadata.WIDGET_DATE);
context.put("TIME", ResourcesMetadata.WIDGET_TIME);
context.put("DATETIME", ResourcesMetadata.WIDGET_DATETIME);
context.put("ANYURI", ResourcesMetadata.WIDGET_ANYURI);
context.put("ENUM", ResourcesMetadata.WIDGET_ENUM);
context.put("NESTED", ResourcesMetadata.WIDGET_NESTED);
context.put("WYSIWYG", ResourcesMetadata.WIDGET_WYSIWYG);
context.put("today", TimeService.newTime());
context.put("DOT", ResourcesMetadata.DOT);
}
Set missing = (Set) current_stack_frame.remove(STATE_CREATE_MISSING_ITEM);
context.put("missing", missing);
// String template = (String) getContext(data).get("template");
return TEMPLATE_CREATE;
}
/**
* show the resource properties
*/
public static void doMore ( RunData data)
{
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
ParameterParser params = data.getParameters ();
Map current_stack_frame = pushOnStack(state);
// cancel copy if there is one in progress
if(! Boolean.FALSE.toString().equals(state.getAttribute (STATE_COPY_FLAG)))
{
initCopyContext(state);
}
// cancel move if there is one in progress
if(! Boolean.FALSE.toString().equals(state.getAttribute (STATE_MOVE_FLAG)))
{
initMoveContext(state);
}
state.setAttribute(STATE_LIST_SELECTIONS, new TreeSet());
// the hosted item ID
String id = NULL_STRING;
// the collection id
String collectionId = NULL_STRING;
try
{
id = params.getString ("id");
if (id!=null)
{
// set the collection/resource id for more context
current_stack_frame.put(STATE_MORE_ID, id);
}
else
{
// get collection/resource id from the state object
id =(String) current_stack_frame.get(STATE_MORE_ID);
}
collectionId = params.getString ("collectionId");
current_stack_frame.put(STATE_MORE_COLLECTION_ID, collectionId);
if (collectionId.equals ((String) state.getAttribute(STATE_HOME_COLLECTION_ID)))
{
try
{
// this is a test to see if the collection exists. If not, it is created.
ContentCollection collection = ContentHostingService.getCollection (collectionId);
}
catch (IdUnusedException e )
{
try
{
// default copyright
String mycopyright = (String) state.getAttribute (STATE_MY_COPYRIGHT);
ResourcePropertiesEdit resourceProperties = ContentHostingService.newResourceProperties ();
String homeCollectionId = (String) state.getAttribute (STATE_HOME_COLLECTION_ID);
resourceProperties.addProperty (ResourceProperties.PROP_DISPLAY_NAME, ContentHostingService.getProperties (homeCollectionId).getPropertyFormatted (ResourceProperties.PROP_DISPLAY_NAME));
ContentCollection collection = ContentHostingService.addCollection (homeCollectionId, resourceProperties);
}
catch (IdUsedException ee)
{
addAlert(state, rb.getString("idused"));
}
catch (IdUnusedException ee)
{
addAlert(state,RESOURCE_NOT_EXIST_STRING);
}
catch (IdInvalidException ee)
{
addAlert(state, rb.getString("title") + " " + ee.getMessage ());
}
catch (PermissionException ee)
{
addAlert(state, rb.getString("permisex"));
}
catch (InconsistentException ee)
{
addAlert(state, RESOURCE_INVALID_TITLE_STRING);
}
}
catch (TypeException e )
{
addAlert(state, rb.getString("typeex"));
}
catch (PermissionException e )
{
addAlert(state, rb.getString("permisex"));
}
}
}
catch (NullPointerException eE)
{
addAlert(state," " + rb.getString("nullex") + " " + id + ". ");
}
// is there no error?
if (state.getAttribute(STATE_MESSAGE) == null)
{
// go to the more state
state.setAttribute(STATE_MODE, MODE_MORE);
} // if-else
} // doMore
/**
* doDelete to delete the selected collection or resource items
*/
public void doDelete ( RunData data)
{
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
// cancel copy if there is one in progress
if(! Boolean.FALSE.toString().equals(state.getAttribute (STATE_COPY_FLAG)))
{
initCopyContext(state);
}
// cancel move if there is one in progress
if(! Boolean.FALSE.toString().equals(state.getAttribute (STATE_MOVE_FLAG)))
{
initMoveContext(state);
}
ParameterParser params = data.getParameters ();
List Items = (List) state.getAttribute(STATE_DELETE_ITEMS);
// Vector deleteIds = (Vector) state.getAttribute (STATE_DELETE_IDS);
// delete the lowest item in the hireachy first
Hashtable deleteItems = new Hashtable();
// String collectionId = (String) state.getAttribute (STATE_COLLECTION_ID);
int maxDepth = 0;
int depth = 0;
Iterator it = Items.iterator();
while(it.hasNext())
{
BrowseItem item = (BrowseItem) it.next();
depth = ContentHostingService.getDepth(item.getId(), item.getRoot());
if (depth > maxDepth)
{
maxDepth = depth;
}
List v = (List) deleteItems.get(new Integer(depth));
if(v == null)
{
v = new Vector();
}
v.add(item);
deleteItems.put(new Integer(depth), v);
}
boolean isCollection = false;
for (int j=maxDepth; j>0; j--)
{
List v = (List) deleteItems.get(new Integer(j));
if (v==null)
{
v = new Vector();
}
Iterator itemIt = v.iterator();
while(itemIt.hasNext())
{
BrowseItem item = (BrowseItem) itemIt.next();
try
{
if (item.isFolder())
{
ContentHostingService.removeCollection(item.getId());
}
else
{
ContentHostingService.removeResource(item.getId());
}
}
catch (PermissionException e)
{
addAlert(state, rb.getString("notpermis6") + " " + item.getName() + ". ");
}
catch (IdUnusedException e)
{
addAlert(state,RESOURCE_NOT_EXIST_STRING);
}
catch (TypeException e)
{
addAlert(state, rb.getString("deleteres") + " " + item.getName() + " " + rb.getString("wrongtype"));
}
catch (ServerOverloadException e)
{
addAlert(state, rb.getString("failed"));
}
catch (InUseException e)
{
addAlert(state, rb.getString("deleteres") + " " + item.getName() + " " + rb.getString("locked"));
}// try - catch
catch(RuntimeException e)
{
logger.error("ResourcesAction.doDelete ***** Unknown Exception ***** " + e.getMessage());
addAlert(state, rb.getString("failed"));
}
} // for
} // for
if (state.getAttribute(STATE_MESSAGE) == null)
{
// delete sucessful
state.setAttribute (STATE_MODE, MODE_LIST);
if (((String) state.getAttribute (STATE_SELECT_ALL_FLAG)).equals (Boolean.TRUE.toString()))
{
state.setAttribute (STATE_SELECT_ALL_FLAG, Boolean.FALSE.toString());
}
} // if-else
} // doDelete
/**
* doCancel to return to the previous state
*/
public static void doCancel ( RunData data)
{
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
state.setAttribute(STATE_LIST_SELECTIONS, new TreeSet());
if(!isStackEmpty(state))
{
Map current_stack_frame = peekAtStack(state);
current_stack_frame.put(STATE_HELPER_CANCELED_BY_USER, Boolean.TRUE.toString());
popFromStack(state);
}
resetCurrentMode(state);
} // doCancel
/**
* Paste the previously copied/cutted item(s)
*/
public void doHandlepaste ( RunData data)
{
ParameterParser params = data.getParameters ();
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
// get the cut items to be pasted
Vector pasteCutItems = (Vector) state.getAttribute (STATE_CUT_IDS);
// get the copied items to be pasted
Vector pasteCopiedItems = (Vector) state.getAttribute (STATE_COPIED_IDS);
String collectionId = params.getString ("collectionId");
String originalDisplayName = NULL_STRING;
// handle cut and paste
if (((String) state.getAttribute (STATE_CUT_FLAG)).equals (Boolean.TRUE.toString()))
{
for (int i = 0; i < pasteCutItems.size (); i++)
{
String currentPasteCutItem = (String) pasteCutItems.get (i);
try
{
ResourceProperties properties = ContentHostingService.getProperties (currentPasteCutItem);
originalDisplayName = properties.getPropertyFormatted (ResourceProperties.PROP_DISPLAY_NAME);
/*
if (Boolean.TRUE.toString().equals(properties.getProperty (ResourceProperties.PROP_IS_COLLECTION)))
{
String alert = (String) state.getAttribute(STATE_MESSAGE);
if (alert == null || ((alert != null) && (alert.indexOf(RESOURCE_INVALID_OPERATION_ON_COLLECTION_STRING) == -1)))
{
addAlert(state, RESOURCE_INVALID_OPERATION_ON_COLLECTION_STRING);
}
}
else
{
*/
// paste the resource
ContentResource resource = ContentHostingService.getResource (currentPasteCutItem);
ResourceProperties p = ContentHostingService.getProperties(currentPasteCutItem);
String id = collectionId + Validator.escapeResourceName(p.getProperty(ResourceProperties.PROP_DISPLAY_NAME));
// cut-paste to the same collection?
boolean cutPasteSameCollection = false;
String displayName = p.getProperty(ResourceProperties.PROP_DISPLAY_NAME);
// till paste successfully or it fails
ResourcePropertiesEdit resourceProperties = ContentHostingService.newResourceProperties ();
// add the properties of the pasted item
Iterator propertyNames = properties.getPropertyNames ();
while ( propertyNames.hasNext ())
{
String propertyName = (String) propertyNames.next ();
if (!properties.isLiveProperty (propertyName))
{
if (propertyName.equals (ResourceProperties.PROP_DISPLAY_NAME)&&(displayName.length ()>0))
{
resourceProperties.addProperty (propertyName, displayName);
}
else
{
resourceProperties.addProperty (propertyName, properties.getProperty (propertyName));
} // if-else
} // if
} // while
try
{
// paste the cutted resource to the new collection - no notification
ContentResource newResource = ContentHostingService.addResource (id, resource.getContentType (), resource.getContent (), resourceProperties, NotificationService.NOTI_NONE);
String uuid = ContentHostingService.getUuid(resource.getId());
ContentHostingService.setUuid(id, uuid);
}
catch (InconsistentException e)
{
addAlert(state,RESOURCE_INVALID_TITLE_STRING);
}
catch (OverQuotaException e)
{
addAlert(state, rb.getString("overquota"));
}
catch (IdInvalidException e)
{
addAlert(state, rb.getString("title") + " " + e.getMessage ());
}
catch(ServerOverloadException e)
{
// this represents temporary unavailability of server's filesystem
// for server configured to save resource body in filesystem
addAlert(state, rb.getString("failed"));
}
catch (IdUsedException e)
{
// cut and paste to the same collection; stop adding new resource
if (id.equals(currentPasteCutItem))
{
cutPasteSameCollection = true;
}
else
{
addAlert(state, rb.getString("notaddreso") + " " + id + rb.getString("used2"));
/*
// pasted to the same folder as before; add "Copy of "/ "copy (n) of" to the id
if (countNumber==1)
{
displayName = DUPLICATE_STRING + p.getProperty(ResourceProperties.PROP_DISPLAY_NAME);
id = collectionId + Validator.escapeResourceName(displayName);
}
else
{
displayName = "Copy (" + countNumber + ") of " + p.getProperty(ResourceProperties.PROP_DISPLAY_NAME);
id = collectionId + Validator.escapeResourceName(displayName);
}
countNumber++;
*/
}
} // try-catch
catch(RuntimeException e)
{
logger.error("ResourcesAction.doHandlepaste ***** Unknown Exception ***** " + e.getMessage());
addAlert(state, rb.getString("failed"));
}
if (!cutPasteSameCollection)
{
// remove the cutted resource
ContentHostingService.removeResource (currentPasteCutItem);
}
// } // if-else
}
catch (InUseException e)
{
addAlert(state, rb.getString("someone") + " " + originalDisplayName + ". ");
}
catch (PermissionException e)
{
addAlert(state, rb.getString("notpermis7") + " " + originalDisplayName + ". ");
}
catch (IdUnusedException e)
{
addAlert(state,RESOURCE_NOT_EXIST_STRING);
}
catch (TypeException e)
{
addAlert(state, rb.getString("pasteitem") + " " + originalDisplayName + " " + rb.getString("mismatch"));
} // try-catch
catch(RuntimeException e)
{
logger.error("ResourcesAction.doHandlepaste ***** Unknown Exception ***** " + e.getMessage());
addAlert(state, rb.getString("failed"));
}
} // for
} // cut
// handling copy and paste
if (Boolean.toString(true).equalsIgnoreCase((String) state.getAttribute (STATE_COPY_FLAG)))
{
for (int i = 0; i < pasteCopiedItems.size (); i++)
{
String currentPasteCopiedItem = (String) pasteCopiedItems.get (i);
try
{
ResourceProperties properties = ContentHostingService.getProperties (currentPasteCopiedItem);
originalDisplayName = properties.getPropertyFormatted (ResourceProperties.PROP_DISPLAY_NAME);
// copy, cut and paste not operated on collections
if (properties.getProperty (ResourceProperties.PROP_IS_COLLECTION).equals (Boolean.TRUE.toString()))
{
String alert = (String) state.getAttribute(STATE_MESSAGE);
if (alert == null || ((alert != null) && (alert.indexOf(RESOURCE_INVALID_OPERATION_ON_COLLECTION_STRING) == -1)))
{
addAlert(state, RESOURCE_INVALID_OPERATION_ON_COLLECTION_STRING);
}
}
else
{
// paste the resource
ContentResource resource = ContentHostingService.getResource (currentPasteCopiedItem);
ResourceProperties p = ContentHostingService.getProperties(currentPasteCopiedItem);
String displayName = DUPLICATE_STRING + p.getProperty(ResourceProperties.PROP_DISPLAY_NAME);
String id = collectionId + Validator.escapeResourceName(displayName);
ResourcePropertiesEdit resourceProperties = ContentHostingService.newResourceProperties ();
// add the properties of the pasted item
Iterator propertyNames = properties.getPropertyNames ();
while ( propertyNames.hasNext ())
{
String propertyName = (String) propertyNames.next ();
if (!properties.isLiveProperty (propertyName))
{
if (propertyName.equals (ResourceProperties.PROP_DISPLAY_NAME)&&(displayName.length ()>0))
{
resourceProperties.addProperty (propertyName, displayName);
}
else
{
resourceProperties.addProperty (propertyName, properties.getProperty (propertyName));
}
}
}
try
{
// paste the copied resource to the new collection
ContentResource newResource = ContentHostingService.addResource (id, resource.getContentType (), resource.getContent (), resourceProperties, NotificationService.NOTI_NONE);
}
catch (InconsistentException e)
{
addAlert(state,RESOURCE_INVALID_TITLE_STRING);
}
catch (IdInvalidException e)
{
addAlert(state,rb.getString("title") + " " + e.getMessage ());
}
catch (OverQuotaException e)
{
addAlert(state, rb.getString("overquota"));
}
catch (ServerOverloadException e)
{
addAlert(state, rb.getString("failed"));
}
catch (IdUsedException e)
{
addAlert(state, rb.getString("notaddreso") + " " + id + rb.getString("used2"));
/*
// copying
// pasted to the same folder as before; add "Copy of " to the id
if (countNumber > 1)
{
displayName = "Copy (" + countNumber + ") of " + p.getProperty(ResourceProperties.PROP_DISPLAY_NAME);
}
else if (countNumber == 1)
{
displayName = "Copy of " + p.getProperty(ResourceProperties.PROP_DISPLAY_NAME);
}
id = collectionId + Validator.escapeResourceName(displayName);
countNumber++;
*/
} // try-catch
catch(RuntimeException e)
{
logger.error("ResourcesAction.doHandlepaste ***** Unknown Exception ***** " + e.getMessage());
addAlert(state, rb.getString("failed"));
}
} // if-else
}
catch (PermissionException e)
{
addAlert(state, rb.getString("notpermis8") + " " + originalDisplayName + ". ");
}
catch (IdUnusedException e)
{
addAlert(state,RESOURCE_NOT_EXIST_STRING);
}
catch (TypeException e)
{
addAlert(state, rb.getString("pasteitem") + " " + originalDisplayName + " " + rb.getString("mismatch"));
} // try-catch
} // for
} // copy
if (state.getAttribute(STATE_MESSAGE) == null)
{
// delete sucessful
state.setAttribute (STATE_MODE, MODE_LIST);
// reset the cut flag
if (((String)state.getAttribute (STATE_CUT_FLAG)).equals (Boolean.TRUE.toString()))
{
state.setAttribute (STATE_CUT_FLAG, Boolean.FALSE.toString());
}
// reset the copy flag
if (Boolean.toString(true).equalsIgnoreCase((String)state.getAttribute (STATE_COPY_FLAG)))
{
state.setAttribute (STATE_COPY_FLAG, Boolean.FALSE.toString());
}
// try to expand the collection
HashMap expandedCollections = (HashMap) state.getAttribute(STATE_EXPANDED_COLLECTIONS);
if(! expandedCollections.containsKey(collectionId))
{
org.sakaiproject.content.api.ContentHostingService contentService = (org.sakaiproject.content.api.ContentHostingService) state.getAttribute (STATE_CONTENT_SERVICE);
try
{
ContentCollection coll = contentService.getCollection(collectionId);
expandedCollections.put(collectionId, coll);
}
catch(Exception ignore){}
}
}
} // doHandlepaste
/**
* Paste the shortcut(s) of previously copied item(s)
*/
public void doHandlepasteshortcut ( RunData data)
{
ParameterParser params = data.getParameters ();
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
// get the items to be pasted
Vector pasteItems = new Vector ();
if (((String) state.getAttribute (STATE_COPY_FLAG)).equals (Boolean.TRUE.toString()))
{
pasteItems = (Vector) ( (Vector) state.getAttribute (STATE_COPIED_IDS)).clone ();
}
if (((String) state.getAttribute (STATE_CUT_FLAG)).equals (Boolean.TRUE.toString()))
{
addAlert(state, rb.getString("choosecp"));
}
if (state.getAttribute(STATE_MESSAGE) == null)
{
String collectionId = params.getString ("collectionId");
String originalDisplayName = NULL_STRING;
for (int i = 0; i < pasteItems.size (); i++)
{
String currentPasteItem = (String) pasteItems.get (i);
try
{
ResourceProperties properties = ContentHostingService.getProperties (currentPasteItem);
originalDisplayName = properties.getPropertyFormatted (ResourceProperties.PROP_DISPLAY_NAME);
if (properties.getProperty (ResourceProperties.PROP_IS_COLLECTION).equals (Boolean.TRUE.toString()))
{
// paste the collection
}
else
{
// paste the resource
ContentResource resource = ContentHostingService.getResource (currentPasteItem);
ResourceProperties p = ContentHostingService.getProperties(currentPasteItem);
String displayName = SHORTCUT_STRING + p.getProperty(ResourceProperties.PROP_DISPLAY_NAME);
String id = collectionId + Validator.escapeResourceName(displayName);
//int countNumber = 2;
ResourcePropertiesEdit resourceProperties = ContentHostingService.newResourceProperties ();
// add the properties of the pasted item
Iterator propertyNames = properties.getPropertyNames ();
while ( propertyNames.hasNext ())
{
String propertyName = (String) propertyNames.next ();
if ((!properties.isLiveProperty (propertyName)) && (!propertyName.equals (ResourceProperties.PROP_DISPLAY_NAME)))
{
resourceProperties.addProperty (propertyName, properties.getProperty (propertyName));
}
}
// %%%%% should be _blank for items that can be displayed in browser, _self for others
// resourceProperties.addProperty (ResourceProperties.PROP_OPEN_NEWWINDOW, "_self");
resourceProperties.addProperty (ResourceProperties.PROP_DISPLAY_NAME, displayName);
try
{
ContentResource referedResource= ContentHostingService.getResource (currentPasteItem);
ContentResource newResource = ContentHostingService.addResource (id, ResourceProperties.TYPE_URL, referedResource.getUrl().getBytes (), resourceProperties, NotificationService.NOTI_NONE);
}
catch (InconsistentException e)
{
addAlert(state, RESOURCE_INVALID_TITLE_STRING);
}
catch (OverQuotaException e)
{
addAlert(state, rb.getString("overquota"));
}
catch (IdInvalidException e)
{
addAlert(state, rb.getString("title") + " " + e.getMessage ());
}
catch (ServerOverloadException e)
{
addAlert(state, rb.getString("failed"));
}
catch (IdUsedException e)
{
addAlert(state, rb.getString("notaddreso") + " " + id + rb.getString("used2"));
/*
// pasted shortcut to the same folder as before; add countNumber to the id
displayName = "Shortcut (" + countNumber + ") to " + p.getProperty(ResourceProperties.PROP_DISPLAY_NAME);
id = collectionId + Validator.escapeResourceName(displayName);
countNumber++;
*/
} // try-catch
catch(RuntimeException e)
{
logger.error("ResourcesAction.doHandlepasteshortcut ***** Unknown Exception ***** " + e.getMessage());
addAlert(state, rb.getString("failed"));
}
} // if-else
}
catch (PermissionException e)
{
addAlert(state, rb.getString("notpermis9") + " " + currentPasteItem.substring (currentPasteItem.lastIndexOf (Entity.SEPARATOR)+1) + ". ");
}
catch (IdUnusedException e)
{
addAlert(state,RESOURCE_NOT_EXIST_STRING);
}
catch (TypeException e)
{
addAlert(state, rb.getString("pasteitem") + " " + currentPasteItem.substring (currentPasteItem.lastIndexOf (Entity.SEPARATOR)+1) + " " + rb.getString("mismatch"));
} // try-catch
} // for
}
if (state.getAttribute(STATE_MESSAGE) == null)
{
if (((String) state.getAttribute (STATE_COPY_FLAG)).equals (Boolean.TRUE.toString()))
{
// reset the copy flag
state.setAttribute (STATE_COPY_FLAG, Boolean.FALSE.toString());
}
// paste shortcut sucessful
state.setAttribute (STATE_MODE, MODE_LIST);
}
} // doHandlepasteshortcut
/**
* Edit the editable collection/resource properties
*/
public static void doEdit ( RunData data )
{
ParameterParser params = data.getParameters ();
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
Map current_stack_frame = pushOnStack(state);
state.setAttribute(STATE_LIST_SELECTIONS, new TreeSet());
// cancel copy if there is one in progress
if(! Boolean.FALSE.toString().equals(state.getAttribute (STATE_COPY_FLAG)))
{
initCopyContext(state);
}
// cancel move if there is one in progress
if(! Boolean.FALSE.toString().equals(state.getAttribute (STATE_MOVE_FLAG)))
{
initMoveContext(state);
}
String id = NULL_STRING;
id = params.getString ("id");
if(id == null || id.length() == 0)
{
// there is no resource selected, show the alert message to the user
addAlert(state, rb.getString("choosefile2"));
return;
}
current_stack_frame.put(STATE_STACK_EDIT_ID, id);
String collectionId = (String) params.getString("collectionId");
if(collectionId == null)
{
collectionId = ContentHostingService.getSiteCollection(ToolManager.getCurrentPlacement().getContext());
state.setAttribute(STATE_HOME_COLLECTION_ID, collectionId);
}
current_stack_frame.put(STATE_STACK_EDIT_COLLECTION_ID, collectionId);
EditItem item = getEditItem(id, collectionId, data);
if (state.getAttribute(STATE_MESSAGE) == null)
{
// got resource and sucessfully populated item with values
// state.setAttribute (STATE_MODE, MODE_EDIT);
state.setAttribute(ResourcesAction.STATE_RESOURCES_HELPER_MODE, ResourcesAction.MODE_ATTACHMENT_EDIT_ITEM_INIT);
state.setAttribute(STATE_EDIT_ALERTS, new HashSet());
current_stack_frame.put(STATE_STACK_EDIT_ITEM, item);
}
else
{
popFromStack(state);
}
} // doEdit
public static EditItem getEditItem(String id, String collectionId, RunData data)
{
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
Stack operations_stack = (Stack) state.getAttribute(STATE_SUSPENDED_OPERATIONS_STACK);
Map current_stack_frame = peekAtStack(state);
EditItem item = null;
// populate an EditItem object with values from the resource and return the EditItem
try
{
ResourceProperties properties = ContentHostingService.getProperties(id);
boolean isCollection = false;
try
{
isCollection = properties.getBooleanProperty(ResourceProperties.PROP_IS_COLLECTION);
}
catch(Exception e)
{
// assume isCollection is false if property is not set
}
ContentEntity entity = null;
String itemType = "";
byte[] content = null;
if(isCollection)
{
itemType = "folder";
entity = ContentHostingService.getCollection(id);
}
else
{
entity = ContentHostingService.getResource(id);
itemType = ((ContentResource) entity).getContentType();
content = ((ContentResource) entity).getContent();
}
String itemName = properties.getProperty(ResourceProperties.PROP_DISPLAY_NAME);
item = new EditItem(id, itemName, itemType);
BasicRightsAssignment rightsObj = new BasicRightsAssignment(item.getItemNum(), properties);
item.setRights(rightsObj);
String encoding = data.getRequest().getCharacterEncoding();
if(encoding != null)
{
item.setEncoding(encoding);
}
String defaultCopyrightStatus = (String) state.getAttribute(DEFAULT_COPYRIGHT);
if(defaultCopyrightStatus == null || defaultCopyrightStatus.trim().equals(""))
{
defaultCopyrightStatus = ServerConfigurationService.getString("default.copyright");
state.setAttribute(DEFAULT_COPYRIGHT, defaultCopyrightStatus);
}
item.setCopyrightStatus(defaultCopyrightStatus);
if(content != null)
{
item.setContent(content);
}
String dummyId = collectionId.trim();
if(dummyId.endsWith(Entity.SEPARATOR))
{
dummyId += "dummy";
}
else
{
dummyId += Entity.SEPARATOR + "dummy";
}
String containerId = ContentHostingService.getContainingCollectionId (id);
item.setContainer(containerId);
boolean canRead = ContentHostingService.allowGetCollection(id);
boolean canAddFolder = ContentHostingService.allowAddCollection(id);
boolean canAddItem = ContentHostingService.allowAddResource(id);
boolean canDelete = ContentHostingService.allowRemoveResource(id);
boolean canRevise = ContentHostingService.allowUpdateResource(id);
item.setCanRead(canRead);
item.setCanRevise(canRevise);
item.setCanAddItem(canAddItem);
item.setCanAddFolder(canAddFolder);
item.setCanDelete(canDelete);
// item.setIsUrl(isUrl);
AccessMode access = ((GroupAwareEntity) entity).getAccess();
if(access == null)
{
item.setAccess(AccessMode.INHERITED.toString());
}
else
{
item.setAccess(access.toString());
}
AccessMode inherited_access = ((GroupAwareEntity) entity).getInheritedAccess();
if(inherited_access == null || inherited_access.equals(AccessMode.SITE))
{
item.setInheritedAccess(AccessMode.INHERITED.toString());
}
else
{
item.setInheritedAccess(inherited_access.toString());
}
List access_groups = new Vector(((GroupAwareEntity) entity).getGroups());
if(access_groups != null)
{
Site site = SiteService.getSite(ToolManager.getCurrentPlacement().getContext());
Iterator it = access_groups.iterator();
while(it.hasNext())
{
String groupRef = (String) it.next();
Group group = site.getGroup(groupRef);
item.addGroup(group.getId());
}
}
List inherited_access_groups = new Vector(((GroupAwareEntity) entity).getInheritedGroups());
if(inherited_access_groups != null)
{
Site site = SiteService.getSite(ToolManager.getCurrentPlacement().getContext());
Iterator it = inherited_access_groups.iterator();
while(it.hasNext())
{
String groupRef = (String) it.next();
Group group = site.getGroup(groupRef);
item.addGroup(group.getId());
}
}
if(item.isUrl())
{
String url = new String(content);
item.setFilename(url);
}
else if(item.isStructuredArtifact())
{
String formtype = properties.getProperty(ResourceProperties.PROP_STRUCTOBJ_TYPE);
current_stack_frame.put(STATE_STACK_STRUCTOBJ_TYPE, formtype);
current_stack_frame.put(STATE_STACK_EDIT_ITEM, item);
setupStructuredObjects(state);
Document doc = Xml.readDocumentFromString(new String(content));
Element root = doc.getDocumentElement();
importStructuredArtifact(root, item.getForm());
List flatList = item.getForm().getFlatList();
item.setProperties(flatList);
}
else if(item.isHtml() || item.isPlaintext() || item.isFileUpload())
{
String filename = properties.getProperty(ResourceProperties.PROP_ORIGINAL_FILENAME);
if(filename == null)
{
// this is a hack to deal with the fact that original filenames were not saved for some time.
if(containerId != null && item.getId().startsWith(containerId) && containerId.length() < item.getId().length())
{
filename = item.getId().substring(containerId.length());
}
}
if(filename == null)
{
item.setFilename(itemName);
}
else
{
item.setFilename(filename);
}
}
String description = properties.getProperty(ResourceProperties.PROP_DESCRIPTION);
item.setDescription(description);
try
{
Time creTime = properties.getTimeProperty(ResourceProperties.PROP_CREATION_DATE);
String createdTime = creTime.toStringLocalShortDate() + " " + creTime.toStringLocalShort();
item.setCreatedTime(createdTime);
}
catch(Exception e)
{
String createdTime = properties.getProperty(ResourceProperties.PROP_CREATION_DATE);
item.setCreatedTime(createdTime);
}
try
{
String createdBy = getUserProperty(properties, ResourceProperties.PROP_CREATOR).getDisplayName();
item.setCreatedBy(createdBy);
}
catch(Exception e)
{
String createdBy = properties.getProperty(ResourceProperties.PROP_CREATOR);
item.setCreatedBy(createdBy);
}
try
{
Time modTime = properties.getTimeProperty(ResourceProperties.PROP_MODIFIED_DATE);
String modifiedTime = modTime.toStringLocalShortDate() + " " + modTime.toStringLocalShort();
item.setModifiedTime(modifiedTime);
}
catch(Exception e)
{
String modifiedTime = properties.getProperty(ResourceProperties.PROP_MODIFIED_DATE);
item.setModifiedTime(modifiedTime);
}
try
{
String modifiedBy = getUserProperty(properties, ResourceProperties.PROP_MODIFIED_BY).getDisplayName();
item.setModifiedBy(modifiedBy);
}
catch(Exception e)
{
String modifiedBy = properties.getProperty(ResourceProperties.PROP_MODIFIED_BY);
item.setModifiedBy(modifiedBy);
}
String url = ContentHostingService.getUrl(id);
item.setUrl(url);
String size = "";
if(properties.getProperty(ResourceProperties.PROP_CONTENT_LENGTH) != null)
{
size = properties.getPropertyFormatted(ResourceProperties.PROP_CONTENT_LENGTH) + " (" + Validator.getFileSizeWithDividor(properties.getProperty(ResourceProperties.PROP_CONTENT_LENGTH)) +" bytes)";
}
item.setSize(size);
String copyrightStatus = properties.getProperty(properties.getNamePropCopyrightChoice());
if(copyrightStatus == null || copyrightStatus.trim().equals(""))
{
copyrightStatus = (String) state.getAttribute(DEFAULT_COPYRIGHT);
}
item.setCopyrightStatus(copyrightStatus);
String copyrightInfo = properties.getPropertyFormatted(properties.getNamePropCopyright());
item.setCopyrightInfo(copyrightInfo);
String copyrightAlert = properties.getProperty(properties.getNamePropCopyrightAlert());
if("true".equalsIgnoreCase(copyrightAlert))
{
item.setCopyrightAlert(true);
}
else
{
item.setCopyrightAlert(false);
}
boolean pubviewset = ContentHostingService.isInheritingPubView(containerId) || ContentHostingService.isPubView(containerId);
item.setPubviewset(pubviewset);
boolean pubview = pubviewset;
if (!pubview)
{
pubview = ContentHostingService.isPubView(id);
}
item.setPubview(pubview);
Map metadata = new Hashtable();
List groups = (List) state.getAttribute(STATE_METADATA_GROUPS);
if(groups != null && ! groups.isEmpty())
{
Iterator it = groups.iterator();
while(it.hasNext())
{
MetadataGroup group = (MetadataGroup) it.next();
Iterator propIt = group.iterator();
while(propIt.hasNext())
{
ResourcesMetadata prop = (ResourcesMetadata) propIt.next();
String name = prop.getFullname();
String widget = prop.getWidget();
if(widget.equals(ResourcesMetadata.WIDGET_DATE) || widget.equals(ResourcesMetadata.WIDGET_DATETIME) || widget.equals(ResourcesMetadata.WIDGET_TIME))
{
Time time = TimeService.newTime();
try
{
time = properties.getTimeProperty(name);
}
catch(Exception ignore)
{
// use "now" as default in that case
}
metadata.put(name, time);
}
else
{
String value = properties.getPropertyFormatted(name);
metadata.put(name, value);
}
}
}
item.setMetadata(metadata);
}
else
{
item.setMetadata(new Hashtable());
}
// for collections only
if(item.isFolder())
{
// setup for quota - ADMIN only, site-root collection only
if (SecurityService.isSuperUser())
{
Reference ref = EntityManager.newReference(entity.getReference());
String context = ref.getContext();
String siteCollectionId = ContentHostingService.getSiteCollection(context);
if(siteCollectionId.equals(entity.getId()))
{
item.setCanSetQuota(true);
try
{
long quota = properties.getLongProperty(ResourceProperties.PROP_COLLECTION_BODY_QUOTA);
item.setHasQuota(true);
item.setQuota(Long.toString(quota));
}
catch (Exception any)
{
}
}
}
}
}
catch (IdUnusedException e)
{
addAlert(state, RESOURCE_NOT_EXIST_STRING);
}
catch (PermissionException e)
{
addAlert(state, rb.getString("notpermis2") + " " + id + ". " );
}
catch(TypeException e)
{
addAlert(state," " + rb.getString("typeex") + " " + id);
}
catch(ServerOverloadException e)
{
// this represents temporary unavailability of server's filesystem
// for server configured to save resource body in filesystem
addAlert(state, rb.getString("failed"));
}
catch(RuntimeException e)
{
logger.error("ResourcesAction.doEdit ***** Unknown Exception ***** " + e.getMessage());
addAlert(state, rb.getString("failed"));
}
return item;
}
/**
* This method updates the session state with information needed to create or modify
* structured artifacts in the resources tool. Among other things, it obtains a list
* of "forms" available to the user and places that list in state indexed as
* "STATE_STRUCTOBJ_HOMES". If the current formtype is known (in state indexed as
* "STATE_STACK_STRUCTOBJ_TYPE"), the list of properties associated with that form type is
* generated. If we are in a "create" context, the properties are added to each of
* the items in the list of items indexed as "STATE_STACK_CREATE_ITEMS". If we are in an
* "edit" context, the properties are added to the current item being edited (a state
* attribute indexed as "STATE_STACK_EDIT_ITEM"). The metaobj SchemaBean associated with
* the current form and its root SchemaNode object are also placed in state for later
* reference.
*/
public static void setupStructuredObjects(SessionState state)
{
Map current_stack_frame = peekAtStack(state);
String formtype = (String) current_stack_frame.get(STATE_STACK_STRUCTOBJ_TYPE);
if(formtype == null)
{
formtype = (String) state.getAttribute(STATE_STRUCTOBJ_TYPE);
if(formtype == null)
{
formtype = "";
}
current_stack_frame.put(STATE_STACK_STRUCTOBJ_TYPE, formtype);
}
HomeFactory factory = (HomeFactory) ComponentManager.get("homeFactory");
Map homes = factory.getHomes(StructuredArtifactHomeInterface.class);
List listOfHomes = new Vector();
Iterator it = homes.keySet().iterator();
while(it.hasNext())
{
String key = (String) it.next();
try
{
Object obj = homes.get(key);
listOfHomes.add(obj);
}
catch(Exception ignore)
{}
}
current_stack_frame.put(STATE_STRUCTOBJ_HOMES, listOfHomes);
StructuredArtifactHomeInterface home = null;
SchemaBean rootSchema = null;
ResourcesMetadata elements = null;
if(formtype == null || formtype.equals(""))
{
formtype = "";
current_stack_frame.put(STATE_STACK_STRUCTOBJ_TYPE, formtype);
}
else if(listOfHomes.isEmpty())
{
// hmmm
}
else
{
try
{
home = (StructuredArtifactHomeInterface) factory.getHome(formtype);
}
catch(NullPointerException ignore)
{
home = null;
}
}
if(home != null)
{
rootSchema = new SchemaBean(home.getRootNode(), home.getSchema(), formtype, home.getType().getDescription());
List fields = rootSchema.getFields();
String docRoot = rootSchema.getFieldName();
elements = new ResourcesMetadata("", docRoot, "", "", ResourcesMetadata.WIDGET_NESTED, ResourcesMetadata.WIDGET_NESTED);
elements.setDottedparts(docRoot);
elements.setContainer(null);
elements = createHierarchicalList(elements, fields, 1);
String instruction = home.getInstruction();
current_stack_frame.put(STATE_STACK_STRUCTOBJ_ROOTNAME, docRoot);
current_stack_frame.put(STATE_STACK_STRUCT_OBJ_SCHEMA, rootSchema);
List new_items = (List) current_stack_frame.get(STATE_STACK_CREATE_ITEMS);
if(new_items != null)
{
Integer number = (Integer) current_stack_frame.get(STATE_STACK_CREATE_NUMBER);
if(number == null)
{
number = (Integer) state.getAttribute(STATE_CREATE_NUMBER);
current_stack_frame.put(STATE_STACK_CREATE_NUMBER, number);
}
if(number == null)
{
number = new Integer(1);
current_stack_frame.put(STATE_STACK_CREATE_NUMBER, number);
}
List flatList = elements.getFlatList();
for(int i = 0; i < number.intValue(); i++)
{
//%%%%% doing this wipes out data that's been stored previously
EditItem item = (EditItem) new_items.get(i);
item.setRootname(docRoot);
item.setFormtype(formtype);
item.setInstruction(instruction);
item.setProperties(flatList);
item.setForm(elements);
}
current_stack_frame.put(STATE_STACK_CREATE_ITEMS, new_items);
}
else if(current_stack_frame.get(STATE_STACK_EDIT_ITEM) != null)
{
EditItem item = (EditItem) current_stack_frame.get(STATE_STACK_EDIT_ITEM);
item.setRootname(docRoot);
item.setFormtype(formtype);
item.setInstruction(instruction);
item.setForm(elements);
}
}
} // setupStructuredArtifacts
/**
* This method navigates through a list of SchemaNode objects representing fields in a form,
* creates a ResourcesMetadata object for each field and adds those as nested fields within
* a root element. If a field contains nested fields, a recursive call adds nested fields
* in the corresponding ResourcesMetadata object.
* @param element The root element to which field descriptions are added.
* @param fields A list of metaobj SchemaNode objects.
* @param depth The depth of nesting, corresponding to the amount of indent that will be used
* when displaying the list.
* @return The update root element.
*/
private static ResourcesMetadata createHierarchicalList(ResourcesMetadata element, List fields, int depth)
{
List properties = new Vector();
for(Iterator fieldIt = fields.iterator(); fieldIt.hasNext(); )
{
SchemaBean field = (SchemaBean) fieldIt.next();
SchemaNode node = field.getSchema();
Map annotations = field.getAnnotations();
Pattern pattern = null;
String localname = field.getFieldName();
String description = field.getDescription();
String label = (String) annotations.get("label");
if(label == null || label.trim().equals(""))
{
label = description;
}
String richText = (String) annotations.get("isRichText");
boolean isRichText = richText != null && richText.equalsIgnoreCase(Boolean.TRUE.toString());
Class javaclass = node.getObjectType();
String typename = javaclass.getName();
String widget = ResourcesMetadata.WIDGET_STRING;
int length = 0;
List enumerals = null;
if(field.getFields().size() > 0)
{
widget = ResourcesMetadata.WIDGET_NESTED;
}
else if(node.hasEnumerations())
{
enumerals = node.getEnumeration();
typename = String.class.getName();
widget = ResourcesMetadata.WIDGET_ENUM;
}
else if(typename.equals(String.class.getName()))
{
length = node.getType().getMaxLength();
String baseType = node.getType().getBaseType();
if(isRichText)
{
widget = ResourcesMetadata.WIDGET_WYSIWYG;
}
else if(baseType.trim().equalsIgnoreCase(ResourcesMetadata.NAMESPACE_XSD_ABBREV + ResourcesMetadata.XSD_NORMALIZED_STRING))
{
widget = ResourcesMetadata.WIDGET_STRING;
if(length > 50)
{
length = 50;
}
}
else if(length > 100 || length < 1)
{
widget = ResourcesMetadata.WIDGET_TEXTAREA;
}
else if(length > 50)
{
length = 50;
}
pattern = node.getType().getPattern();
}
else if(typename.equals(Date.class.getName()))
{
widget = ResourcesMetadata.WIDGET_DATE;
}
else if(typename.equals(Boolean.class.getName()))
{
widget = ResourcesMetadata.WIDGET_BOOLEAN;
}
else if(typename.equals(URI.class.getName()))
{
widget = ResourcesMetadata.WIDGET_ANYURI;
}
else if(typename.equals(Number.class.getName()))
{
widget = ResourcesMetadata.WIDGET_INTEGER;
//length = node.getType().getTotalDigits();
length = INTEGER_WIDGET_LENGTH;
}
else if(typename.equals(Double.class.getName()))
{
widget = ResourcesMetadata.WIDGET_DOUBLE;
length = DOUBLE_WIDGET_LENGTH;
}
int minCard = node.getMinOccurs();
int maxCard = node.getMaxOccurs();
if(maxCard < 1)
{
maxCard = Integer.MAX_VALUE;
}
if(minCard < 0)
{
minCard = 0;
}
minCard = java.lang.Math.max(0,minCard);
maxCard = java.lang.Math.max(1,maxCard);
int currentCount = java.lang.Math.min(java.lang.Math.max(1,minCard),maxCard);
ResourcesMetadata prop = new ResourcesMetadata(element.getDottedname(), localname, label, description, typename, widget);
List parts = new Vector(element.getDottedparts());
parts.add(localname);
prop.setDottedparts(parts);
prop.setContainer(element);
if(ResourcesMetadata.WIDGET_NESTED.equals(widget))
{
prop = createHierarchicalList(prop, field.getFields(), depth + 1);
}
prop.setMinCardinality(minCard);
prop.setMaxCardinality(maxCard);
prop.setCurrentCount(currentCount);
prop.setDepth(depth);
if(enumerals != null)
{
prop.setEnumeration(enumerals);
}
if(length > 0)
{
prop.setLength(length);
}
if(pattern != null)
{
prop.setPattern(pattern);
}
properties.add(prop);
}
element.setNested(properties);
return element;
} // createHierarchicalList
/**
* This method captures property values from an org.w3c.dom.Document and inserts them
* into a hierarchical list of ResourcesMetadata objects which describes the structure
* of the form. The values are added by inserting nested instances into the properties.
*
* @param element An org.w3c.dom.Element containing values to be imported.
* @param properties A hierarchical list of ResourcesMetadata objects describing a form
*/
public static void importStructuredArtifact(Node node, ResourcesMetadata property)
{
if(property == null || node == null)
{
return;
}
String tagname = property.getLocalname();
String nodename = node.getLocalName();
if(! tagname.equals(nodename))
{
// return;
}
if(property.getNested().size() == 0)
{
boolean value_found = false;
Node child = node.getFirstChild();
while(! value_found && child != null)
{
if(child.getNodeType() == Node.TEXT_NODE)
{
Text value = (Text) child;
if(ResourcesMetadata.WIDGET_DATE.equals(property.getWidget()) || ResourcesMetadata.WIDGET_DATETIME.equals(property.getWidget()) || ResourcesMetadata.WIDGET_TIME.equals(property.getWidget()))
{
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
Time time = TimeService.newTime();
try
{
Date date = df.parse(value.getData());
time = TimeService.newTime(date.getTime());
}
catch(Exception ignore)
{
// use "now" as default in that case
}
property.setValue(0, time);
}
else if(ResourcesMetadata.WIDGET_ANYURI.equals(property.getWidget()))
{
Reference ref = EntityManager.newReference(ContentHostingService.getReference(value.getData()));
property.setValue(0, ref);
}
else
{
property.setValue(0, value.getData());
}
}
child = child.getNextSibling();
}
}
else if(node instanceof Element)
{
// a nested element
Iterator nestedIt = property.getNested().iterator();
while(nestedIt.hasNext())
{
ResourcesMetadata prop = (ResourcesMetadata) nestedIt.next();
NodeList nodes = ((Element) node).getElementsByTagName(prop.getLocalname());
if(nodes == null)
{
continue;
}
for(int i = 0; i < nodes.getLength(); i++)
{
Node n = nodes.item(i);
if(n != null)
{
ResourcesMetadata instance = prop.addInstance();
if(instance != null)
{
importStructuredArtifact(n, instance);
}
}
}
}
}
} // importStructuredArtifact
protected static String validateURL(String url) throws MalformedURLException
{
if (url.equals (NULL_STRING))
{
// ignore the empty url field
}
else if (url.indexOf ("://") == -1)
{
// if it's missing the transport, add http://
url = "http://" + url;
}
if(!url.equals(NULL_STRING))
{
// valid protocol?
try
{
// test to see if the input validates as a URL.
// Checks string for format only.
URL u = new URL(url);
}
catch (MalformedURLException e1)
{
try
{
Pattern pattern = Pattern.compile("\\s*([a-zA-Z0-9]+)://([^\\n]+)");
Matcher matcher = pattern.matcher(url);
if(matcher.matches())
{
// if URL has "unknown" protocol, check remaider with
// "http" protocol and accept input it that validates.
URL test = new URL("http://" + matcher.group(2));
}
else
{
throw e1;
}
}
catch (MalformedURLException e2)
{
throw e1;
}
}
}
return url;
}
/**
* Retrieve values for an item from edit context. Edit context contains just one item at a time of a known type
* (folder, file, text document, structured-artifact, etc). This method retrieves the data apppropriate to the
* type and updates the values of the EditItem stored as the STATE_STACK_EDIT_ITEM attribute in state.
* @param state
* @param params
* @param item
*/
protected static void captureValues(SessionState state, ParameterParser params)
{
Map current_stack_frame = peekAtStack(state);
EditItem item = (EditItem) current_stack_frame.get(STATE_STACK_EDIT_ITEM);
Set alerts = (Set) state.getAttribute(STATE_EDIT_ALERTS);
if(alerts == null)
{
alerts = new HashSet();
state.setAttribute(STATE_EDIT_ALERTS, alerts);
}
String flow = params.getString("flow");
boolean intentChanged = "intentChanged".equals(flow);
String check_fileName = params.getString("check_fileName");
boolean expectFile = "true".equals(check_fileName);
String intent = params.getString("intent");
String oldintent = (String) current_stack_frame.get(STATE_STACK_EDIT_INTENT);
boolean upload_file = expectFile && item.isFileUpload() || ((item.isHtml() || item.isPlaintext()) && !intentChanged && INTENT_REPLACE_FILE.equals(intent) && INTENT_REPLACE_FILE.equals(oldintent));
boolean revise_file = (item.isHtml() || item.isPlaintext()) && !intentChanged && INTENT_REVISE_FILE.equals(intent) && INTENT_REVISE_FILE.equals(oldintent);
String name = params.getString("name");
if(name == null || "".equals(name.trim()))
{
alerts.add(rb.getString("titlenotnull"));
// addAlert(state, rb.getString("titlenotnull"));
}
else
{
item.setName(name.trim());
}
String description = params.getString("description");
if(description == null)
{
item.setDescription("");
}
else
{
item.setDescription(description);
}
item.setContentHasChanged(false);
if(upload_file)
{
String max_file_size_mb = (String) state.getAttribute(STATE_FILE_UPLOAD_MAX_SIZE);
int max_bytes = 1096 * 1096;
try
{
max_bytes = Integer.parseInt(max_file_size_mb) * 1096 * 1096;
}
catch(Exception e)
{
// if unable to parse an integer from the value
// in the properties file, use 1 MB as a default
max_file_size_mb = "1";
max_bytes = 1096 * 1096;
}
/*
// params.getContentLength() returns m_req.getContentLength()
if(params.getContentLength() >= max_bytes)
{
alerts.add(rb.getString("size") + " " + max_file_size_mb + "MB " + rb.getString("exceeded2"));
}
else
*/
{
// check for file replacement
FileItem fileitem = params.getFileItem("fileName");
if(fileitem == null)
{
// "The user submitted a file to upload but it was too big!"
alerts.clear();
alerts.add(rb.getString("size") + " " + max_file_size_mb + "MB " + rb.getString("exceeded2"));
//item.setMissing("fileName");
}
else if (fileitem.getFileName() == null || fileitem.getFileName().length() == 0)
{
if(item.getContent() == null || item.getContent().length <= 0)
{
// "The user submitted the form, but didn't select a file to upload!"
alerts.add(rb.getString("choosefile") + ". ");
//item.setMissing("fileName");
}
}
else if (fileitem.getFileName().length() > 0)
{
String filename = Validator.getFileName(fileitem.getFileName());
byte[] bytes = fileitem.get();
String contenttype = fileitem.getContentType();
if(bytes.length >= max_bytes)
{
alerts.clear();
alerts.add(rb.getString("size") + " " + max_file_size_mb + "MB " + rb.getString("exceeded2"));
// item.setMissing("fileName");
}
else if(bytes.length > 0)
{
item.setContent(bytes);
item.setContentHasChanged(true);
item.setMimeType(contenttype);
item.setFilename(filename);
}
}
}
}
else if(revise_file)
{
// check for input from editor (textarea)
String content = params.getString("content");
if(content != null)
{
item.setContent(content);
item.setContentHasChanged(true);
}
}
else if(item.isUrl())
{
String url = params.getString("Url");
if(url == null || url.trim().equals(""))
{
item.setFilename("");
alerts.add(rb.getString("validurl"));
}
else
{
// valid protocol?
item.setFilename(url);
try
{
// test format of input
URL u = new URL(url);
}
catch (MalformedURLException e1)
{
try
{
// if URL did not validate, check whether the problem was an
// unrecognized protocol, and accept input if that's the case.
Pattern pattern = Pattern.compile("\\s*([a-zA-Z0-9]+)://([^\\n]+)");
Matcher matcher = pattern.matcher(url);
if(matcher.matches())
{
URL test = new URL("http://" + matcher.group(2));
}
else
{
url = "http://" + url;
URL test = new URL(url);
item.setFilename(url);
}
}
catch (MalformedURLException e2)
{
// invalid url
alerts.add(rb.getString("validurl"));
}
}
}
}
else if(item.isFolder())
{
if(item.canSetQuota())
{
// read the quota fields
String setQuota = params.getString("setQuota");
boolean hasQuota = params.getBoolean("hasQuota");
item.setHasQuota(hasQuota);
if(hasQuota)
{
int q = params.getInt("quota");
item.setQuota(Integer.toString(q));
}
}
}
else if(item.isStructuredArtifact())
{
String formtype = (String) current_stack_frame.get(STATE_STACK_STRUCTOBJ_TYPE);
if(formtype == null)
{
formtype = (String) state.getAttribute(STATE_STRUCTOBJ_TYPE);
if(formtype == null)
{
formtype = "";
}
current_stack_frame.put(STATE_STACK_STRUCTOBJ_TYPE, formtype);
}
String formtype_check = params.getString("formtype");
if(formtype_check == null || formtype_check.equals(""))
{
alerts.add(rb.getString("type"));
item.setMissing("formtype");
}
else if(formtype_check.equals(formtype))
{
item.setFormtype(formtype);
capturePropertyValues(params, item, item.getProperties());
}
}
if(! item.isFolder() && ! item.isStructuredArtifact() && ! item.isUrl())
{
String mime_category = params.getString("mime_category");
String mime_subtype = params.getString("mime_subtype");
if(mime_category != null && mime_subtype != null)
{
String mimetype = mime_category + "/" + mime_subtype;
if(! mimetype.equals(item.getMimeType()))
{
item.setMimeType(mimetype);
item.setContentTypeHasChanged(true);
}
}
}
if(item.isFileUpload() || item.isHtml() || item.isPlaintext())
{
BasicRightsAssignment rightsObj = item.getRights();
rightsObj.captureValues(params);
boolean usingCreativeCommons = state.getAttribute(STATE_USING_CREATIVE_COMMONS) != null && state.getAttribute(STATE_USING_CREATIVE_COMMONS).equals(Boolean.TRUE.toString());
if(usingCreativeCommons)
{
String ccOwnership = params.getString("ccOwnership");
if(ccOwnership != null)
{
item.setRightsownership(ccOwnership);
}
String ccTerms = params.getString("ccTerms");
if(ccTerms != null)
{
item.setLicense(ccTerms);
}
String ccCommercial = params.getString("ccCommercial");
if(ccCommercial != null)
{
item.setAllowCommercial(ccCommercial);
}
String ccModification = params.getString("ccModification");
if(ccCommercial != null)
{
item.setAllowModifications(ccModification);
}
String ccRightsYear = params.getString("ccRightsYear");
if(ccRightsYear != null)
{
item.setRightstyear(ccRightsYear);
}
String ccRightsOwner = params.getString("ccRightsOwner");
if(ccRightsOwner != null)
{
item.setRightsowner(ccRightsOwner);
}
/*
ccValues.ccOwner = new Array();
ccValues.myRights = new Array();
ccValues.otherRights = new Array();
ccValues.ccCommercial = new Array();
ccValues.ccModifications = new Array();
ccValues.ccRightsYear = new Array();
ccValues.ccRightsOwner = new Array();
*/
}
else
{
// check for copyright status
// check for copyright info
// check for copyright alert
String copyrightStatus = StringUtil.trimToNull(params.getString ("copyrightStatus"));
String copyrightInfo = StringUtil.trimToNull(params.getCleanString ("copyrightInfo"));
String copyrightAlert = StringUtil.trimToNull(params.getString("copyrightAlert"));
if (copyrightStatus != null)
{
if (state.getAttribute(COPYRIGHT_NEW_COPYRIGHT) != null && copyrightStatus.equals(state.getAttribute(COPYRIGHT_NEW_COPYRIGHT)))
{
if (copyrightInfo != null)
{
item.setCopyrightInfo( copyrightInfo );
}
else
{
alerts.add(rb.getString("specifycp2"));
// addAlert(state, rb.getString("specifycp2"));
}
}
else if (state.getAttribute(COPYRIGHT_SELF_COPYRIGHT) != null && copyrightStatus.equals (state.getAttribute(COPYRIGHT_SELF_COPYRIGHT)))
{
item.setCopyrightInfo((String) state.getAttribute (STATE_MY_COPYRIGHT));
}
item.setCopyrightStatus( copyrightStatus );
}
item.setCopyrightAlert(copyrightAlert != null);
}
}
String access_mode = params.getString("access_mode");
if(access_mode != null)
{
item.setAccess(access_mode);
if(AccessMode.GROUPED.toString().equals(access_mode))
{
String xxx = params.getString("access_groups");
String[] access_groups = params.getStrings("access_groups");
item.clearGroups();
for(int gr = 0; gr < access_groups.length; gr++)
{
item.addGroup(access_groups[gr]);
}
}
}
Boolean preventPublicDisplay = (Boolean) state.getAttribute(STATE_PREVENT_PUBLIC_DISPLAY);
if(preventPublicDisplay == null)
{
preventPublicDisplay = Boolean.FALSE;
state.setAttribute(STATE_PREVENT_PUBLIC_DISPLAY, preventPublicDisplay);
}
if(preventPublicDisplay.equals(Boolean.FALSE))
{
boolean pubviewset = item.isPubviewset();
boolean pubview = false;
if (! RESOURCES_MODE_DROPBOX.equalsIgnoreCase((String) state.getAttribute(STATE_MODE_RESOURCES)))
{
if (!pubviewset)
{
pubview = params.getBoolean("pubview");
item.setPubview(pubview);
}
}
}
int noti = NotificationService.NOTI_NONE;
// %%STATE_MODE_RESOURCES%%
if (RESOURCES_MODE_DROPBOX.equalsIgnoreCase((String) state.getAttribute(STATE_MODE_RESOURCES)))
{
// set noti to none if in dropbox mode
noti = NotificationService.NOTI_NONE;
}
else
{
// read the notification options
String notification = params.getString("notify");
if ("r".equals(notification))
{
noti = NotificationService.NOTI_REQUIRED;
}
else if ("o".equals(notification))
{
noti = NotificationService.NOTI_OPTIONAL;
}
}
item.setNotification(noti);
List metadataGroups = (List) state.getAttribute(STATE_METADATA_GROUPS);
if(metadataGroups != null && ! metadataGroups.isEmpty())
{
Iterator groupIt = metadataGroups.iterator();
while(groupIt.hasNext())
{
MetadataGroup group = (MetadataGroup) groupIt.next();
if(group.isShowing())
{
Iterator propIt = group.iterator();
while(propIt.hasNext())
{
ResourcesMetadata prop = (ResourcesMetadata) propIt.next();
String propname = prop.getFullname();
if(ResourcesMetadata.WIDGET_DATE.equals(prop.getWidget()) || ResourcesMetadata.WIDGET_DATETIME.equals(prop.getWidget()) || ResourcesMetadata.WIDGET_TIME.equals(prop.getWidget()))
{
int year = 0;
int month = 0;
int day = 0;
int hour = 0;
int minute = 0;
int second = 0;
int millisecond = 0;
String ampm = "";
if(prop.getWidget().equals(ResourcesMetadata.WIDGET_DATE) ||
prop.getWidget().equals(ResourcesMetadata.WIDGET_DATETIME))
{
year = params.getInt(propname + "_year", year);
month = params.getInt(propname + "_month", month);
day = params.getInt(propname + "_day", day);
}
if(prop.getWidget().equals(ResourcesMetadata.WIDGET_TIME) ||
prop.getWidget().equals(ResourcesMetadata.WIDGET_DATETIME))
{
hour = params.getInt(propname + "_hour", hour);
minute = params.getInt(propname + "_minute", minute);
second = params.getInt(propname + "_second", second);
millisecond = params.getInt(propname + "_millisecond", millisecond);
ampm = params.getString(propname + "_ampm").trim();
if("pm".equalsIgnoreCase("ampm"))
{
if(hour < 12)
{
hour += 12;
}
}
else if(hour == 12)
{
hour = 0;
}
}
if(hour > 23)
{
hour = hour % 24;
day++;
}
Time value = TimeService.newTimeLocal(year, month, day, hour, minute, second, millisecond);
item.setMetadataItem(propname,value);
}
else
{
String value = params.getString(propname);
if(value != null)
{
item.setMetadataItem(propname, value);
}
}
}
}
}
}
current_stack_frame.put(STATE_STACK_EDIT_ITEM, item);
state.setAttribute(STATE_EDIT_ALERTS, alerts);
} // captureValues
/**
* Retrieve from an html form all the values needed to create a new resource
* @param item The EditItem object in which the values are temporarily stored.
* @param index The index of the item (used as a suffix in the name of the form element)
* @param state
* @param params
* @param markMissing Indicates whether to mark required elements if they are missing.
* @return
*/
public static Set captureValues(EditItem item, int index, SessionState state, ParameterParser params, boolean markMissing)
{
Map current_stack_frame = peekAtStack(state);
Set item_alerts = new HashSet();
boolean blank_entry = true;
item.clearMissing();
String name = params.getString("name" + index);
if(name == null || name.trim().equals(""))
{
if(markMissing)
{
item_alerts.add(rb.getString("titlenotnull"));
item.setMissing("name");
}
item.setName("");
// addAlert(state, rb.getString("titlenotnull"));
}
else
{
item.setName(name);
blank_entry = false;
}
String description = params.getString("description" + index);
if(description == null || description.trim().equals(""))
{
item.setDescription("");
}
else
{
item.setDescription(description);
blank_entry = false;
}
item.setContentHasChanged(false);
if(item.isFileUpload())
{
String max_file_size_mb = (String) state.getAttribute(STATE_FILE_UPLOAD_MAX_SIZE);
int max_bytes = 1096 * 1096;
try
{
max_bytes = Integer.parseInt(max_file_size_mb) * 1096 * 1096;
}
catch(Exception e)
{
// if unable to parse an integer from the value
// in the properties file, use 1 MB as a default
max_file_size_mb = "1";
max_bytes = 1096 * 1096;
}
/*
// params.getContentLength() returns m_req.getContentLength()
if(params.getContentLength() >= max_bytes)
{
item_alerts.add(rb.getString("size") + " " + max_file_size_mb + "MB " + rb.getString("exceeded2"));
}
else
*/
{
// check for file replacement
FileItem fileitem = null;
try
{
fileitem = params.getFileItem("fileName" + index);
}
catch(Exception e)
{
// this is an error in Firefox, Mozilla and Netscape
// "The user didn't select a file to upload!"
if(item.getContent() == null || item.getContent().length <= 0)
{
item_alerts.add(rb.getString("choosefile") + " " + (index + 1) + ". ");
item.setMissing("fileName");
}
}
if(fileitem == null)
{
// "The user submitted a file to upload but it was too big!"
item_alerts.clear();
item_alerts.add(rb.getString("size") + " " + max_file_size_mb + "MB " + rb.getString("exceeded2"));
item.setMissing("fileName");
}
else if (fileitem.getFileName() == null || fileitem.getFileName().length() == 0)
{
if(item.getContent() == null || item.getContent().length <= 0)
{
// "The user submitted the form, but didn't select a file to upload!"
item_alerts.add(rb.getString("choosefile") + " " + (index + 1) + ". ");
item.setMissing("fileName");
}
}
else if (fileitem.getFileName().length() > 0)
{
String filename = Validator.getFileName(fileitem.getFileName());
byte[] bytes = fileitem.get();
String contenttype = fileitem.getContentType();
if(bytes.length >= max_bytes)
{
item_alerts.clear();
item_alerts.add(rb.getString("size") + " " + max_file_size_mb + "MB " + rb.getString("exceeded2"));
item.setMissing("fileName");
}
else if(bytes.length > 0)
{
item.setContent(bytes);
item.setContentHasChanged(true);
item.setMimeType(contenttype);
item.setFilename(filename);
blank_entry = false;
}
else
{
item_alerts.add(rb.getString("choosefile") + " " + (index + 1) + ". ");
item.setMissing("fileName");
}
}
}
}
else if(item.isPlaintext())
{
// check for input from editor (textarea)
String content = params.getString("content" + index);
if(content != null)
{
item.setContentHasChanged(true);
item.setContent(content);
blank_entry = false;
}
item.setMimeType(MIME_TYPE_DOCUMENT_PLAINTEXT);
}
else if(item.isHtml())
{
// check for input from editor (textarea)
String content = params.getCleanString("content" + index);
StringBuffer alertMsg = new StringBuffer();
content = FormattedText.processHtmlDocument(content, alertMsg);
if (alertMsg.length() > 0)
{
item_alerts.add(alertMsg.toString());
}
if(content != null && !content.equals(""))
{
item.setContent(content);
item.setContentHasChanged(true);
blank_entry = false;
}
item.setMimeType(MIME_TYPE_DOCUMENT_HTML);
}
else if(item.isUrl())
{
item.setMimeType(ResourceProperties.TYPE_URL);
String url = params.getString("Url" + index);
if(url == null || url.trim().equals(""))
{
item.setFilename("");
item_alerts.add(rb.getString("specifyurl"));
item.setMissing("Url");
}
else
{
item.setFilename(url);
blank_entry = false;
// is protocol supplied and, if so, is it recognized?
try
{
// check format of input
URL u = new URL(url);
}
catch (MalformedURLException e1)
{
try
{
// if URL did not validate, check whether the problem was an
// unrecognized protocol, and accept input if that's the case.
Pattern pattern = Pattern.compile("\\s*([a-zA-Z0-9]+)://([^\\n]+)");
Matcher matcher = pattern.matcher(url);
if(matcher.matches())
{
URL test = new URL("http://" + matcher.group(2));
}
else
{
url = "http://" + url;
URL test = new URL(url);
item.setFilename(url);
}
}
catch (MalformedURLException e2)
{
// invalid url
item_alerts.add(rb.getString("validurl"));
item.setMissing("Url");
}
}
}
}
else if(item.isStructuredArtifact())
{
String formtype = (String) current_stack_frame.get(STATE_STACK_STRUCTOBJ_TYPE);
if(formtype == null)
{
formtype = (String) state.getAttribute(STATE_STRUCTOBJ_TYPE);
if(formtype == null)
{
formtype = "";
}
current_stack_frame.put(STATE_STACK_STRUCTOBJ_TYPE, formtype);
}
String formtype_check = params.getString("formtype");
if(formtype_check == null || formtype_check.equals(""))
{
item_alerts.add("Must select a form type");
item.setMissing("formtype");
}
else if(formtype_check.equals(formtype))
{
item.setFormtype(formtype);
capturePropertyValues(params, item, item.getProperties());
// blank_entry = false;
}
item.setMimeType(MIME_TYPE_STRUCTOBJ);
}
if(item.isFileUpload() || item.isHtml() || item.isPlaintext())
{
BasicRightsAssignment rightsObj = item.getRights();
rightsObj.captureValues(params);
boolean usingCreativeCommons = state.getAttribute(STATE_USING_CREATIVE_COMMONS) != null && state.getAttribute(STATE_USING_CREATIVE_COMMONS).equals(Boolean.TRUE.toString());
if(usingCreativeCommons)
{
String ccOwnership = params.getString("ccOwnership" + index);
if(ccOwnership != null)
{
item.setRightsownership(ccOwnership);
}
String ccTerms = params.getString("ccTerms" + index);
if(ccTerms != null)
{
item.setLicense(ccTerms);
}
String ccCommercial = params.getString("ccCommercial" + index);
if(ccCommercial != null)
{
item.setAllowCommercial(ccCommercial);
}
String ccModification = params.getString("ccModification" + index);
if(ccCommercial != null)
{
item.setAllowModifications(ccModification);
}
String ccRightsYear = params.getString("ccRightsYear" + index);
if(ccRightsYear != null)
{
item.setRightstyear(ccRightsYear);
}
String ccRightsOwner = params.getString("ccRightsOwner" + index);
if(ccRightsOwner != null)
{
item.setRightsowner(ccRightsOwner);
}
/*
ccValues.ccOwner = new Array();
ccValues.myRights = new Array();
ccValues.otherRights = new Array();
ccValues.ccCommercial = new Array();
ccValues.ccModifications = new Array();
ccValues.ccRightsYear = new Array();
ccValues.ccRightsOwner = new Array();
*/
}
else
{
// check for copyright status
// check for copyright info
// check for copyright alert
String copyrightStatus = StringUtil.trimToNull(params.getString ("copyright" + index));
String copyrightInfo = StringUtil.trimToNull(params.getCleanString ("newcopyright" + index));
String copyrightAlert = StringUtil.trimToNull(params.getString("copyrightAlert" + index));
if (copyrightStatus != null)
{
if (state.getAttribute(COPYRIGHT_NEW_COPYRIGHT) != null && copyrightStatus.equals(state.getAttribute(COPYRIGHT_NEW_COPYRIGHT)))
{
if (copyrightInfo != null)
{
item.setCopyrightInfo( copyrightInfo );
}
else
{
item_alerts.add(rb.getString("specifycp2"));
// addAlert(state, rb.getString("specifycp2"));
}
}
else if (state.getAttribute(COPYRIGHT_SELF_COPYRIGHT) != null && copyrightStatus.equals (state.getAttribute(COPYRIGHT_SELF_COPYRIGHT)))
{
item.setCopyrightInfo((String) state.getAttribute (STATE_MY_COPYRIGHT));
}
item.setCopyrightStatus( copyrightStatus );
}
item.setCopyrightAlert(copyrightAlert != null);
}
}
Boolean preventPublicDisplay = (Boolean) state.getAttribute(STATE_PREVENT_PUBLIC_DISPLAY);
if(preventPublicDisplay == null)
{
preventPublicDisplay = Boolean.FALSE;
state.setAttribute(STATE_PREVENT_PUBLIC_DISPLAY, preventPublicDisplay);
}
if(preventPublicDisplay.equals(Boolean.FALSE))
{
boolean pubviewset = item.isPubviewset();
boolean pubview = false;
if (! RESOURCES_MODE_DROPBOX.equalsIgnoreCase((String) state.getAttribute(STATE_MODE_RESOURCES)))
{
if (!pubviewset)
{
pubview = params.getBoolean("pubview");
item.setPubview(pubview);
}
}
}
String access_mode = params.getString("access_mode" + index);
if(access_mode != null)
{
item.setAccess(access_mode);
if(AccessMode.GROUPED.toString().equals(access_mode))
{
String[] access_groups = params.getStrings("access_groups" + index);
for(int gr = 0; gr < access_groups.length; gr++)
{
item.addGroup(access_groups[gr]);
}
}
}
int noti = NotificationService.NOTI_NONE;
// %%STATE_MODE_RESOURCES%%
if (RESOURCES_MODE_DROPBOX.equalsIgnoreCase((String) state.getAttribute(STATE_MODE_RESOURCES)))
{
// set noti to none if in dropbox mode
noti = NotificationService.NOTI_NONE;
}
else
{
// read the notification options
String notification = params.getString("notify" + index);
if ("r".equals(notification))
{
noti = NotificationService.NOTI_REQUIRED;
}
else if ("o".equals(notification))
{
noti = NotificationService.NOTI_OPTIONAL;
}
}
item.setNotification(noti);
List metadataGroups = (List) state.getAttribute(STATE_METADATA_GROUPS);
if(metadataGroups != null && ! metadataGroups.isEmpty())
{
Iterator groupIt = metadataGroups.iterator();
while(groupIt.hasNext())
{
MetadataGroup group = (MetadataGroup) groupIt.next();
if(item.isGroupShowing(group.getName()))
{
Iterator propIt = group.iterator();
while(propIt.hasNext())
{
ResourcesMetadata prop = (ResourcesMetadata) propIt.next();
String propname = prop.getFullname();
if(ResourcesMetadata.WIDGET_DATE.equals(prop.getWidget()) || ResourcesMetadata.WIDGET_DATETIME.equals(prop.getWidget()) || ResourcesMetadata.WIDGET_TIME.equals(prop.getWidget()))
{
int year = 0;
int month = 0;
int day = 0;
int hour = 0;
int minute = 0;
int second = 0;
int millisecond = 0;
String ampm = "";
if(prop.getWidget().equals(ResourcesMetadata.WIDGET_DATE) ||
prop.getWidget().equals(ResourcesMetadata.WIDGET_DATETIME))
{
year = params.getInt(propname + "_" + index + "_year", year);
month = params.getInt(propname + "_" + index + "_month", month);
day = params.getInt(propname + "_" + index + "_day", day);
}
if(prop.getWidget().equals(ResourcesMetadata.WIDGET_TIME) ||
prop.getWidget().equals(ResourcesMetadata.WIDGET_DATETIME))
{
hour = params.getInt(propname + "_" + index + "_hour", hour);
minute = params.getInt(propname + "_" + index + "_minute", minute);
second = params.getInt(propname + "_" + index + "_second", second);
millisecond = params.getInt(propname + "_" + index + "_millisecond", millisecond);
ampm = params.getString(propname + "_" + index + "_ampm").trim();
if("pm".equalsIgnoreCase(ampm))
{
if(hour < 12)
{
hour += 12;
}
}
else if(hour == 12)
{
hour = 0;
}
}
if(hour > 23)
{
hour = hour % 24;
day++;
}
Time value = TimeService.newTimeLocal(year, month, day, hour, minute, second, millisecond);
item.setMetadataItem(propname,value);
}
else
{
String value = params.getString(propname + "_" + index);
if(value != null)
{
item.setMetadataItem(propname, value);
}
}
}
}
}
}
item.markAsBlank(blank_entry);
return item_alerts;
}
/**
* Retrieve values for one or more items from create context. Create context contains up to ten items at a time
* all of the same type (folder, file, text document, structured-artifact, etc). This method retrieves the data
* apppropriate to the type and updates the values of the EditItem objects stored as the STATE_STACK_CREATE_ITEMS
* attribute in state. If the third parameter is "true", missing/incorrect user inputs will generate error messages
* and attach flags to the input elements.
* @param state
* @param params
* @param markMissing Should this method generate error messages and add flags for missing/incorrect user inputs?
*/
protected static void captureMultipleValues(SessionState state, ParameterParser params, boolean markMissing)
{
Map current_stack_frame = peekAtStack(state);
Integer number = (Integer) current_stack_frame.get(STATE_STACK_CREATE_NUMBER);
if(number == null)
{
number = (Integer) state.getAttribute(STATE_CREATE_NUMBER);
current_stack_frame.put(STATE_STACK_CREATE_NUMBER, number);
}
if(number == null)
{
number = new Integer(1);
current_stack_frame.put(STATE_STACK_CREATE_NUMBER, number);
}
List new_items = (List) current_stack_frame.get(STATE_STACK_CREATE_ITEMS);
if(new_items == null)
{
String defaultCopyrightStatus = (String) state.getAttribute(DEFAULT_COPYRIGHT);
if(defaultCopyrightStatus == null || defaultCopyrightStatus.trim().equals(""))
{
defaultCopyrightStatus = ServerConfigurationService.getString("default.copyright");
state.setAttribute(DEFAULT_COPYRIGHT, defaultCopyrightStatus);
}
String itemType = (String) current_stack_frame.get(STATE_STACK_CREATE_TYPE);
if(itemType == null || itemType.trim().equals(""))
{
itemType = (String) state.getAttribute(STATE_CREATE_TYPE);
if(itemType == null || itemType.trim().equals(""))
{
itemType = TYPE_UPLOAD;
}
current_stack_frame.put(STATE_STACK_CREATE_TYPE, itemType);
}
new_items = new Vector();
for(int i = 0; i < CREATE_MAX_ITEMS; i++)
{
EditItem item = new EditItem(itemType);
item.setCopyrightStatus(defaultCopyrightStatus);
new_items.add(item);
}
current_stack_frame.put(STATE_STACK_CREATE_ITEMS, new_items);
}
Set alerts = (Set) state.getAttribute(STATE_CREATE_ALERTS);
if(alerts == null)
{
alerts = new HashSet();
state.setAttribute(STATE_CREATE_ALERTS, alerts);
}
int actualCount = 0;
Set first_item_alerts = null;
String max_file_size_mb = (String) state.getAttribute(STATE_FILE_UPLOAD_MAX_SIZE);
int max_bytes = 1096 * 1096;
try
{
max_bytes = Integer.parseInt(max_file_size_mb) * 1096 * 1096;
}
catch(Exception e)
{
// if unable to parse an integer from the value
// in the properties file, use 1 MB as a default
max_file_size_mb = "1";
max_bytes = 1096 * 1096;
}
/*
// params.getContentLength() returns m_req.getContentLength()
if(params.getContentLength() > max_bytes)
{
alerts.add(rb.getString("size") + " " + max_file_size_mb + "MB " + rb.getString("exceeded2"));
state.setAttribute(STATE_CREATE_ALERTS, alerts);
return;
}
*/
for(int i = 0; i < number.intValue(); i++)
{
EditItem item = (EditItem) new_items.get(i);
Set item_alerts = captureValues(item, i, state, params, markMissing);
if(i == 0)
{
first_item_alerts = item_alerts;
}
else if(item.isBlank())
{
item.clearMissing();
}
if(! item.isBlank())
{
alerts.addAll(item_alerts);
actualCount ++;
}
}
if(actualCount > 0)
{
EditItem item = (EditItem) new_items.get(0);
if(item.isBlank())
{
item.clearMissing();
}
}
else if(markMissing)
{
alerts.addAll(first_item_alerts);
}
state.setAttribute(STATE_CREATE_ALERTS, alerts);
current_stack_frame.put(STATE_STACK_CREATE_ACTUAL_COUNT, Integer.toString(actualCount));
} // captureMultipleValues
protected static void capturePropertyValues(ParameterParser params, EditItem item, List properties)
{
// use the item's properties if they're not supplied
if(properties == null)
{
properties = item.getProperties();
}
// if max cardinality > 1, value is a list (Iterate over members of list)
// else value is an object, not a list
// if type is nested, object is a Map (iterate over name-value pairs for the properties of the nested object)
// else object is type to store value, usually a string or a date/time
Iterator it = properties.iterator();
while(it.hasNext())
{
ResourcesMetadata prop = (ResourcesMetadata) it.next();
String propname = prop.getDottedname();
if(ResourcesMetadata.WIDGET_NESTED.equals(prop.getWidget()))
{
// do nothing
}
else if(ResourcesMetadata.WIDGET_BOOLEAN.equals(prop.getWidget()))
{
String value = params.getString(propname);
if(value == null || Boolean.FALSE.toString().equals(value))
{
prop.setValue(0, Boolean.FALSE.toString());
}
else
{
prop.setValue(0, Boolean.TRUE.toString());
}
}
else if(ResourcesMetadata.WIDGET_DATE.equals(prop.getWidget()) || ResourcesMetadata.WIDGET_DATETIME.equals(prop.getWidget()) || ResourcesMetadata.WIDGET_TIME.equals(prop.getWidget()))
{
int year = 0;
int month = 0;
int day = 0;
int hour = 0;
int minute = 0;
int second = 0;
int millisecond = 0;
String ampm = "";
if(prop.getWidget().equals(ResourcesMetadata.WIDGET_DATE) ||
prop.getWidget().equals(ResourcesMetadata.WIDGET_DATETIME))
{
year = params.getInt(propname + "_year", year);
month = params.getInt(propname + "_month", month);
day = params.getInt(propname + "_day", day);
}
if(prop.getWidget().equals(ResourcesMetadata.WIDGET_TIME) ||
prop.getWidget().equals(ResourcesMetadata.WIDGET_DATETIME))
{
hour = params.getInt(propname + "_hour", hour);
minute = params.getInt(propname + "_minute", minute);
second = params.getInt(propname + "_second", second);
millisecond = params.getInt(propname + "_millisecond", millisecond);
ampm = params.getString(propname + "_ampm");
if("pm".equalsIgnoreCase(ampm))
{
if(hour < 12)
{
hour += 12;
}
}
else if(hour == 12)
{
hour = 0;
}
}
if(hour > 23)
{
hour = hour % 24;
day++;
}
Time value = TimeService.newTimeLocal(year, month, day, hour, minute, second, millisecond);
prop.setValue(0, value);
}
else if(ResourcesMetadata.WIDGET_ANYURI.equals(prop.getWidget()))
{
String value = params.getString(propname);
if(value != null && ! value.trim().equals(""))
{
Reference ref = EntityManager.newReference(ContentHostingService.getReference(value));
prop.setValue(0, ref);
}
}
else
{
String value = params.getString(propname);
if(value != null)
{
prop.setValue(0, value);
}
}
}
} // capturePropertyValues
/**
* Modify the properties
*/
public static void doSavechanges ( RunData data)
{
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
ParameterParser params = data.getParameters ();
String flow = params.getString("flow").trim();
if(flow == null || "cancel".equals(flow))
{
doCancel(data);
return;
}
// get values from form and update STATE_STACK_EDIT_ITEM attribute in state
captureValues(state, params);
Map current_stack_frame = peekAtStack(state);
EditItem item = (EditItem) current_stack_frame.get(STATE_STACK_EDIT_ITEM);
if(flow.equals("showMetadata"))
{
doShow_metadata(data);
return;
}
else if(flow.equals("hideMetadata"))
{
doHide_metadata(data);
return;
}
else if(flow.equals("intentChanged"))
{
doToggle_intent(data);
return;
}
else if(flow.equals("addInstance"))
{
String field = params.getString("field");
addInstance(field, item.getProperties());
ResourcesMetadata form = item.getForm();
List flatList = form.getFlatList();
item.setProperties(flatList);
return;
}
else if(flow.equals("linkResource"))
{
// captureMultipleValues(state, params, false);
createLink(data, state);
//Map new_stack_frame = pushOnStack(state);
//new_stack_frame.put(ResourcesAction.STATE_RESOURCES_HELPER_MODE, ResourcesAction.MODE_ATTACHMENT_SELECT);
state.setAttribute(ResourcesAction.STATE_RESOURCES_HELPER_MODE, ResourcesAction.MODE_ATTACHMENT_SELECT);
return;
}
Set alerts = (Set) state.getAttribute(STATE_EDIT_ALERTS);
if(item.isStructuredArtifact())
{
SchemaBean bean = (SchemaBean) current_stack_frame.get(STATE_STACK_STRUCT_OBJ_SCHEMA);
SaveArtifactAttempt attempt = new SaveArtifactAttempt(item, bean.getSchema());
validateStructuredArtifact(attempt);
Iterator errorIt = attempt.getErrors().iterator();
while(errorIt.hasNext())
{
ValidationError error = (ValidationError) errorIt.next();
alerts.add(error.getDefaultMessage());
}
}
if(alerts.isEmpty())
{
// populate the property list
try
{
// get an edit
ContentCollectionEdit cedit = null;
ContentResourceEdit redit = null;
GroupAwareEdit gedit = null;
ResourcePropertiesEdit pedit = null;
if(item.isFolder())
{
cedit = ContentHostingService.editCollection(item.getId());
gedit = cedit;
pedit = cedit.getPropertiesEdit();
}
else
{
redit = ContentHostingService.editResource(item.getId());
gedit = redit;
pedit = redit.getPropertiesEdit();
}
try
{
if((AccessMode.INHERITED.toString().equals(item.getAccess()) || AccessMode.SITE.toString().equals(item.getAccess())) && AccessMode.GROUPED == gedit.getAccess())
{
gedit.clearGroupAccess();
}
else if(gedit.getAccess() == AccessMode.GROUPED && item.getGroups().isEmpty())
{
gedit.clearGroupAccess();
}
else if(!item.getGroups().isEmpty())
{
Collection groupRefs = new Vector();
Iterator it = item.getGroups().iterator();
while(it.hasNext())
{
Group group = (Group) it.next();
groupRefs.add(group.getReference());
}
gedit.setGroupAccess(groupRefs);
}
}
catch(InconsistentException e)
{
// TODO: Should this be reported to user??
logger.error("ResourcesAction.doSavechanges ***** InconsistentException changing groups ***** " + e.getMessage());
}
if(item.isFolder())
{
}
else
{
if(item.isUrl())
{
redit.setContent(item.getFilename().getBytes());
}
else if(item.isStructuredArtifact())
{
redit.setContentType(item.getMimeType());
redit.setContent(item.getContent());
}
else if(item.contentHasChanged())
{
redit.setContentType(item.getMimeType());
redit.setContent(item.getContent());
}
else if(item.contentTypeHasChanged())
{
redit.setContentType(item.getMimeType());
}
BasicRightsAssignment rightsObj = item.getRights();
rightsObj.addResourceProperties(pedit);
String copyright = StringUtil.trimToNull(params.getString ("copyright"));
String newcopyright = StringUtil.trimToNull(params.getCleanString (NEW_COPYRIGHT));
String copyrightAlert = StringUtil.trimToNull(params.getString("copyrightAlert"));
if (copyright != null)
{
if (state.getAttribute(COPYRIGHT_NEW_COPYRIGHT) != null && copyright.equals(state.getAttribute(COPYRIGHT_NEW_COPYRIGHT)))
{
if (newcopyright != null)
{
pedit.addProperty (ResourceProperties.PROP_COPYRIGHT, newcopyright);
}
else
{
alerts.add(rb.getString("specifycp2"));
// addAlert(state, rb.getString("specifycp2"));
}
}
else if (state.getAttribute(COPYRIGHT_SELF_COPYRIGHT) != null && copyright.equals (state.getAttribute(COPYRIGHT_SELF_COPYRIGHT)))
{
String mycopyright = (String) state.getAttribute (STATE_MY_COPYRIGHT);
pedit.addProperty (ResourceProperties.PROP_COPYRIGHT, mycopyright);
}
pedit.addProperty(ResourceProperties.PROP_COPYRIGHT_CHOICE, copyright);
}
if (copyrightAlert != null)
{
pedit.addProperty (ResourceProperties.PROP_COPYRIGHT_ALERT, copyrightAlert);
}
else
{
pedit.removeProperty (ResourceProperties.PROP_COPYRIGHT_ALERT);
}
}
if (!(item.isFolder() && (item.getId().equals ((String) state.getAttribute (STATE_HOME_COLLECTION_ID)))))
{
pedit.addProperty (ResourceProperties.PROP_DISPLAY_NAME, item.getName());
} // the home collection's title is not modificable
pedit.addProperty (ResourceProperties.PROP_DESCRIPTION, item.getDescription());
// deal with quota (collections only)
if ((cedit != null) && item.canSetQuota())
{
if (item.hasQuota())
{
// set the quota
pedit.addProperty(ResourceProperties.PROP_COLLECTION_BODY_QUOTA, item.getQuota());
}
else
{
// clear the quota
pedit.removeProperty(ResourceProperties.PROP_COLLECTION_BODY_QUOTA);
}
}
List metadataGroups = (List) state.getAttribute(STATE_METADATA_GROUPS);
state.setAttribute(STATE_EDIT_ALERTS, alerts);
saveMetadata(pedit, metadataGroups, item);
alerts = (Set) state.getAttribute(STATE_EDIT_ALERTS);
// commit the change
if (cedit != null)
{
ContentHostingService.commitCollection(cedit);
}
else
{
ContentHostingService.commitResource(redit, item.getNotification());
}
current_stack_frame.put(STATE_STACK_EDIT_INTENT, INTENT_REVISE_FILE);
Boolean preventPublicDisplay = (Boolean) state.getAttribute(STATE_PREVENT_PUBLIC_DISPLAY);
if(preventPublicDisplay == null)
{
preventPublicDisplay = Boolean.FALSE;
state.setAttribute(STATE_PREVENT_PUBLIC_DISPLAY, preventPublicDisplay);
}
if(preventPublicDisplay.equals(Boolean.FALSE))
{
if (! RESOURCES_MODE_DROPBOX.equalsIgnoreCase((String) state.getAttribute(STATE_MODE_RESOURCES)))
{
if (!item.isPubviewset())
{
ContentHostingService.setPubView(item.getId(), item.isPubview());
}
}
}
// need to refresh collection containing current edit item make changes show up
String containerId = ContentHostingService.getContainingCollectionId(item.getId());
Map expandedCollections = (Map) state.getAttribute(STATE_EXPANDED_COLLECTIONS);
Object old = expandedCollections.remove(containerId);
if (old != null)
{
try
{
ContentCollection container = ContentHostingService.getCollection(containerId);
expandedCollections.put(containerId, container);
}
catch (Throwable ignore){}
}
}
catch (TypeException e)
{
alerts.add(rb.getString("typeex") + " " + item.getId());
// addAlert(state," " + rb.getString("typeex") + " " + item.getId());
}
catch (IdUnusedException e)
{
alerts.add(RESOURCE_NOT_EXIST_STRING);
// addAlert(state,RESOURCE_NOT_EXIST_STRING);
}
catch (PermissionException e)
{
alerts.add(rb.getString("notpermis10") + " " + item.getId());
// addAlert(state, rb.getString("notpermis10") + " " + item.getId() + ". " );
}
catch (InUseException e)
{
alerts.add(rb.getString("someone") + " " + item.getId());
// addAlert(state, rb.getString("someone") + " " + item.getId() + ". ");
}
catch (ServerOverloadException e)
{
alerts.add(rb.getString("failed"));
}
catch (OverQuotaException e)
{
alerts.add(rb.getString("changing1") + " " + item.getId() + " " + rb.getString("changing2"));
// addAlert(state, rb.getString("changing1") + " " + item.getId() + " " + rb.getString("changing2"));
}
catch(RuntimeException e)
{
logger.error("ResourcesAction.doSavechanges ***** Unknown Exception ***** " + e.getMessage());
logger.error("ResourcesAction.doSavechanges ***** Unknown Exception ***** ", e);
alerts.add(rb.getString("failed"));
}
} // if - else
if(alerts.isEmpty())
{
// modify properties sucessful
String mode = (String) state.getAttribute(STATE_MODE);
popFromStack(state);
resetCurrentMode(state);
} //if-else
else
{
Iterator alertIt = alerts.iterator();
while(alertIt.hasNext())
{
String alert = (String) alertIt.next();
addAlert(state, alert);
}
alerts.clear();
state.setAttribute(STATE_EDIT_ALERTS, alerts);
// state.setAttribute(STATE_CREATE_MISSING_ITEM, missing);
}
} // doSavechanges
/**
* @param pedit
* @param metadataGroups
* @param metadata
*/
private static void saveMetadata(ResourcePropertiesEdit pedit, List metadataGroups, EditItem item)
{
if(metadataGroups != null && !metadataGroups.isEmpty())
{
MetadataGroup group = null;
Iterator it = metadataGroups.iterator();
while(it.hasNext())
{
group = (MetadataGroup) it.next();
Iterator props = group.iterator();
while(props.hasNext())
{
ResourcesMetadata prop = (ResourcesMetadata) props.next();
if(ResourcesMetadata.WIDGET_DATETIME.equals(prop.getWidget()) || ResourcesMetadata.WIDGET_DATE.equals(prop.getWidget()) || ResourcesMetadata.WIDGET_TIME.equals(prop.getWidget()))
{
Time val = (Time)item.getMetadata().get(prop.getFullname());
if(val != null)
{
pedit.addProperty(prop.getFullname(), val.toString());
}
}
else
{
String val = (String) item.getMetadata().get(prop.getFullname());
pedit.addProperty(prop.getFullname(), val);
}
}
}
}
}
/**
* @param data
*/
protected static void doToggle_intent(RunData data)
{
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
ParameterParser params = data.getParameters ();
String intent = params.getString("intent");
Map current_stack_frame = peekAtStack(state);
current_stack_frame.put(STATE_STACK_EDIT_INTENT, intent);
} // doToggle_intent
/**
* @param data
*/
public static void doHideOtherSites(RunData data)
{
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
state.setAttribute(STATE_SHOW_OTHER_SITES, Boolean.FALSE.toString());
//get the ParameterParser from RunData
ParameterParser params = data.getParameters ();
// save the current selections
Set selectedSet = new TreeSet();
String[] selectedItems = params.getStrings("selectedMembers");
if(selectedItems != null)
{
selectedSet.addAll(Arrays.asList(selectedItems));
}
state.setAttribute(STATE_LIST_SELECTIONS, selectedSet);
}
/**
* @param data
*/
public static void doShowOtherSites(RunData data)
{
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
//get the ParameterParser from RunData
ParameterParser params = data.getParameters ();
// save the current selections
Set selectedSet = new TreeSet();
String[] selectedItems = params.getStrings("selectedMembers");
if(selectedItems != null)
{
selectedSet.addAll(Arrays.asList(selectedItems));
}
state.setAttribute(STATE_LIST_SELECTIONS, selectedSet);
state.setAttribute(STATE_SHOW_OTHER_SITES, Boolean.TRUE.toString());
}
/**
* @param data
*/
public static void doHide_metadata(RunData data)
{
ParameterParser params = data.getParameters ();
String name = params.getString("metadataGroup");
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
List metadataGroups = (List) state.getAttribute(STATE_METADATA_GROUPS);
if(metadataGroups != null && ! metadataGroups.isEmpty())
{
boolean found = false;
MetadataGroup group = null;
Iterator it = metadataGroups.iterator();
while(!found && it.hasNext())
{
group = (MetadataGroup) it.next();
found = (name.equals(Validator.escapeUrl(group.getName())) || name.equals(group.getName()));
}
if(found)
{
group.setShowing(false);
}
}
} // doHide_metadata
/**
* @param data
*/
public static void doShow_metadata(RunData data)
{
ParameterParser params = data.getParameters ();
String name = params.getString("metadataGroup");
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
List metadataGroups = (List) state.getAttribute(STATE_METADATA_GROUPS);
if(metadataGroups != null && ! metadataGroups.isEmpty())
{
boolean found = false;
MetadataGroup group = null;
Iterator it = metadataGroups.iterator();
while(!found && it.hasNext())
{
group = (MetadataGroup) it.next();
found = (name.equals(Validator.escapeUrl(group.getName())) || name.equals(group.getName()));
}
if(found)
{
group.setShowing(true);
}
}
} // doShow_metadata
/**
* Sort based on the given property
*/
public static void doSort ( RunData data)
{
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
//get the ParameterParser from RunData
ParameterParser params = data.getParameters ();
// save the current selections
Set selectedSet = new TreeSet();
String[] selectedItems = data.getParameters ().getStrings ("selectedMembers");
if(selectedItems != null)
{
selectedSet.addAll(Arrays.asList(selectedItems));
}
state.setAttribute(STATE_LIST_SELECTIONS, selectedSet);
String criteria = params.getString ("criteria");
if (criteria.equals ("title"))
{
criteria = ResourceProperties.PROP_DISPLAY_NAME;
}
else if (criteria.equals ("size"))
{
criteria = ResourceProperties.PROP_CONTENT_LENGTH;
}
else if (criteria.equals ("created by"))
{
criteria = ResourceProperties.PROP_CREATOR;
}
else if (criteria.equals ("last modified"))
{
criteria = ResourceProperties.PROP_MODIFIED_DATE;
}
// current sorting sequence
String asc = NULL_STRING;
if (!criteria.equals (state.getAttribute (STATE_SORT_BY)))
{
state.setAttribute (STATE_SORT_BY, criteria);
asc = Boolean.TRUE.toString();
state.setAttribute (STATE_SORT_ASC, asc);
}
else
{
// current sorting sequence
asc = (String) state.getAttribute (STATE_SORT_ASC);
//toggle between the ascending and descending sequence
if (asc.equals (Boolean.TRUE.toString()))
{
asc = Boolean.FALSE.toString();
}
else
{
asc = Boolean.TRUE.toString();
}
state.setAttribute (STATE_SORT_ASC, asc);
}
if (state.getAttribute(STATE_MESSAGE) == null)
{
// sort sucessful
// state.setAttribute (STATE_MODE, MODE_LIST);
} // if-else
} // doSort
/**
* set the state name to be "deletecofirm" if any item has been selected for deleting
*/
public void doDeleteconfirm ( RunData data)
{
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
Set deleteIdSet = new TreeSet();
// cancel copy if there is one in progress
if(! Boolean.FALSE.toString().equals(state.getAttribute (STATE_COPY_FLAG)))
{
initCopyContext(state);
}
// cancel move if there is one in progress
if(! Boolean.FALSE.toString().equals(state.getAttribute (STATE_MOVE_FLAG)))
{
initMoveContext(state);
}
String[] deleteIds = data.getParameters ().getStrings ("selectedMembers");
if (deleteIds == null)
{
// there is no resource selected, show the alert message to the user
addAlert(state, rb.getString("choosefile3"));
}
else
{
deleteIdSet.addAll(Arrays.asList(deleteIds));
List deleteItems = new Vector();
List notDeleteItems = new Vector();
List nonEmptyFolders = new Vector();
List roots = (List) state.getAttribute(STATE_COLLECTION_ROOTS);
Iterator rootIt = roots.iterator();
while(rootIt.hasNext())
{
BrowseItem root = (BrowseItem) rootIt.next();
List members = root.getMembers();
Iterator memberIt = members.iterator();
while(memberIt.hasNext())
{
BrowseItem member = (BrowseItem) memberIt.next();
if(deleteIdSet.contains(member.getId()))
{
if(member.isFolder())
{
if(ContentHostingService.allowRemoveCollection(member.getId()))
{
deleteItems.add(member);
if(! member.isEmpty())
{
nonEmptyFolders.add(member);
}
}
else
{
notDeleteItems.add(member);
}
}
else if(ContentHostingService.allowRemoveResource(member.getId()))
{
deleteItems.add(member);
}
else
{
notDeleteItems.add(member);
}
}
}
}
if(! notDeleteItems.isEmpty())
{
String notDeleteNames = "";
boolean first_item = true;
Iterator notIt = notDeleteItems.iterator();
while(notIt.hasNext())
{
BrowseItem item = (BrowseItem) notIt.next();
if(first_item)
{
notDeleteNames = item.getName();
first_item = false;
}
else if(notIt.hasNext())
{
notDeleteNames += ", " + item.getName();
}
else
{
notDeleteNames += " and " + item.getName();
}
}
addAlert(state, rb.getString("notpermis14") + notDeleteNames);
}
/*
//htripath-SAK-1712 - Set new collectionId as resources are not deleted under 'more' requirement.
if(state.getAttribute(STATE_MESSAGE) == null){
String newCollectionId=ContentHostingService.getContainingCollectionId(currentId);
state.setAttribute(STATE_COLLECTION_ID, newCollectionId);
}
*/
// delete item
state.setAttribute (STATE_DELETE_ITEMS, deleteItems);
state.setAttribute (STATE_DELETE_ITEMS_NOT_EMPTY, nonEmptyFolders);
} // if-else
if (state.getAttribute(STATE_MESSAGE) == null)
{
state.setAttribute (STATE_MODE, MODE_DELETE_CONFIRM);
state.setAttribute(STATE_LIST_SELECTIONS, deleteIdSet);
}
} // doDeleteconfirm
/**
* set the state name to be "cut" if any item has been selected for cutting
*/
public void doCut ( RunData data)
{
// get the state object
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
String[] cutItems = data.getParameters ().getStrings ("selectedMembers");
if (cutItems == null)
{
// there is no resource selected, show the alert message to the user
addAlert(state, rb.getString("choosefile5"));
state.setAttribute (STATE_MODE, MODE_LIST);
}
else
{
Vector cutIdsVector = new Vector ();
String nonCutIds = NULL_STRING;
String cutId = NULL_STRING;
for (int i = 0; i < cutItems.length; i++)
{
cutId = cutItems[i];
try
{
ResourceProperties properties = ContentHostingService.getProperties (cutId);
if (properties.getProperty (ResourceProperties.PROP_IS_COLLECTION).equals (Boolean.TRUE.toString()))
{
String alert = (String) state.getAttribute(STATE_MESSAGE);
if (alert == null || ((alert != null) && (alert.indexOf(RESOURCE_INVALID_OPERATION_ON_COLLECTION_STRING) == -1)))
{
addAlert(state, RESOURCE_INVALID_OPERATION_ON_COLLECTION_STRING);
}
}
else
{
if (ContentHostingService.allowRemoveResource (cutId))
{
cutIdsVector.add (cutId);
}
else
{
nonCutIds = nonCutIds + " " + properties.getProperty (ResourceProperties.PROP_DISPLAY_NAME) + "; ";
}
}
}
catch (PermissionException e)
{
addAlert(state, rb.getString("notpermis15"));
}
catch (IdUnusedException e)
{
addAlert(state,RESOURCE_NOT_EXIST_STRING);
} // try-catch
}
if (state.getAttribute(STATE_MESSAGE) == null)
{
if (nonCutIds.length ()>0)
{
addAlert(state, rb.getString("notpermis16") +" " + nonCutIds);
}
if (cutIdsVector.size ()>0)
{
state.setAttribute (STATE_CUT_FLAG, Boolean.TRUE.toString());
if (((String) state.getAttribute (STATE_SELECT_ALL_FLAG)).equals (Boolean.TRUE.toString()))
{
state.setAttribute (STATE_SELECT_ALL_FLAG, Boolean.FALSE.toString());
}
Vector copiedIds = (Vector) state.getAttribute (STATE_COPIED_IDS);
for (int i = 0; i < cutIdsVector.size (); i++)
{
String currentId = (String) cutIdsVector.elementAt (i);
if ( copiedIds.contains (currentId))
{
copiedIds.remove (currentId);
}
}
if (copiedIds.size ()==0)
{
state.setAttribute (STATE_COPY_FLAG, Boolean.FALSE.toString());
}
state.setAttribute (STATE_COPIED_IDS, copiedIds);
state.setAttribute (STATE_CUT_IDS, cutIdsVector);
}
}
} // if-else
} // doCut
/**
* set the state name to be "copy" if any item has been selected for copying
*/
public void doCopy ( RunData data )
{
// get the state object
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
// cancel copy if there is one in progress
if(! Boolean.FALSE.toString().equals(state.getAttribute (STATE_COPY_FLAG)))
{
initCopyContext(state);
}
// cancel move if there is one in progress
if(! Boolean.FALSE.toString().equals(state.getAttribute (STATE_MOVE_FLAG)))
{
initMoveContext(state);
}
Vector copyItemsVector = new Vector ();
String[] copyItems = data.getParameters ().getStrings ("selectedMembers");
if (copyItems == null)
{
// there is no resource selected, show the alert message to the user
addAlert(state, rb.getString("choosefile6"));
state.setAttribute (STATE_MODE, MODE_LIST);
}
else
{
String copyId = NULL_STRING;
for (int i = 0; i < copyItems.length; i++)
{
copyId = copyItems[i];
try
{
ResourceProperties properties = ContentHostingService.getProperties (copyId);
/*
if (properties.getProperty (ResourceProperties.PROP_IS_COLLECTION).equals (Boolean.TRUE.toString()))
{
String alert = (String) state.getAttribute(STATE_MESSAGE);
if (alert == null || ((alert != null) && (alert.indexOf(RESOURCE_INVALID_OPERATION_ON_COLLECTION_STRING) == -1)))
{
addAlert(state, RESOURCE_INVALID_OPERATION_ON_COLLECTION_STRING);
}
}
*/
}
catch (PermissionException e)
{
addAlert(state, rb.getString("notpermis15"));
}
catch (IdUnusedException e)
{
addAlert(state,RESOURCE_NOT_EXIST_STRING);
} // try-catch
}
if (state.getAttribute(STATE_MESSAGE) == null)
{
state.setAttribute (STATE_COPY_FLAG, Boolean.TRUE.toString());
copyItemsVector.addAll(Arrays.asList(copyItems));
ContentHostingService.eliminateDuplicates(copyItemsVector);
state.setAttribute (STATE_COPIED_IDS, copyItemsVector);
} // if-else
} // if-else
} // doCopy
/**
* Handle user's selection of items to be moved.
*/
public void doMove ( RunData data )
{
// get the state object
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
List moveItemsVector = new Vector();
// cancel copy if there is one in progress
if(! Boolean.FALSE.toString().equals(state.getAttribute (STATE_COPY_FLAG)))
{
initCopyContext(state);
}
// cancel move if there is one in progress
if(! Boolean.FALSE.toString().equals(state.getAttribute (STATE_MOVE_FLAG)))
{
initMoveContext(state);
}
state.setAttribute(STATE_LIST_SELECTIONS, new TreeSet());
String[] moveItems = data.getParameters ().getStrings ("selectedMembers");
if (moveItems == null)
{
// there is no resource selected, show the alert message to the user
addAlert(state, rb.getString("choosefile6"));
state.setAttribute (STATE_MODE, MODE_LIST);
}
else
{
String moveId = NULL_STRING;
for (int i = 0; i < moveItems.length; i++)
{
moveId = moveItems[i];
try
{
ResourceProperties properties = ContentHostingService.getProperties (moveId);
/*
if (properties.getProperty (ResourceProperties.PROP_IS_COLLECTION).equals (Boolean.TRUE.toString()))
{
String alert = (String) state.getAttribute(STATE_MESSAGE);
if (alert == null || ((alert != null) && (alert.indexOf(RESOURCE_INVALID_OPERATION_ON_COLLECTION_STRING) == -1)))
{
addAlert(state, RESOURCE_INVALID_OPERATION_ON_COLLECTION_STRING);
}
}
*/
}
catch (PermissionException e)
{
addAlert(state, rb.getString("notpermis15"));
}
catch (IdUnusedException e)
{
addAlert(state,RESOURCE_NOT_EXIST_STRING);
} // try-catch
}
if (state.getAttribute(STATE_MESSAGE) == null)
{
state.setAttribute (STATE_MOVE_FLAG, Boolean.TRUE.toString());
moveItemsVector.addAll(Arrays.asList(moveItems));
ContentHostingService.eliminateDuplicates(moveItemsVector);
state.setAttribute (STATE_MOVED_IDS, moveItemsVector);
} // if-else
} // if-else
} // doMove
/**
* If copy-flag is set to false, erase the copied-id's list and set copied flags to false
* in all the browse items. If copied-id's list is empty, set copy-flag to false and set
* copied flags to false in all the browse items. If copy-flag is set to true and copied-id's
* list is not empty, update the copied flags of all browse items so copied flags for the
* copied items are set to true and all others are set to false.
*/
protected void setCopyFlags(SessionState state)
{
String copyFlag = (String) state.getAttribute(STATE_COPY_FLAG);
List copyItemsVector = (List) state.getAttribute(STATE_COPIED_IDS);
if(copyFlag == null)
{
copyFlag = Boolean.FALSE.toString();
state.setAttribute(STATE_COPY_FLAG, copyFlag);
}
if(copyFlag.equals(Boolean.TRUE.toString()))
{
if(copyItemsVector == null)
{
copyItemsVector = new Vector();
state.setAttribute(STATE_COPIED_IDS, copyItemsVector);
}
if(copyItemsVector.isEmpty())
{
state.setAttribute(STATE_COPY_FLAG, Boolean.FALSE.toString());
}
}
else
{
copyItemsVector = new Vector();
state.setAttribute(STATE_COPIED_IDS, copyItemsVector);
}
List roots = (List) state.getAttribute(STATE_COLLECTION_ROOTS);
Iterator rootIt = roots.iterator();
while(rootIt.hasNext())
{
BrowseItem root = (BrowseItem) rootIt.next();
boolean root_copied = copyItemsVector.contains(root.getId());
root.setCopied(root_copied);
List members = root.getMembers();
Iterator memberIt = members.iterator();
while(memberIt.hasNext())
{
BrowseItem member = (BrowseItem) memberIt.next();
boolean member_copied = copyItemsVector.contains(member.getId());
member.setCopied(member_copied);
}
}
// check -- jim
state.setAttribute(STATE_COLLECTION_ROOTS, roots);
} // setCopyFlags
/**
* Expand all the collection resources.
*/
static public void doExpandall ( RunData data)
{
// get the state object
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
//get the ParameterParser from RunData
ParameterParser params = data.getParameters ();
// save the current selections
Set selectedSet = new TreeSet();
String[] selectedItems = params.getStrings("selectedMembers");
if(selectedItems != null)
{
selectedSet.addAll(Arrays.asList(selectedItems));
}
state.setAttribute(STATE_LIST_SELECTIONS, selectedSet);
// expansion actually occurs in getBrowseItems method.
state.setAttribute(STATE_EXPAND_ALL_FLAG, Boolean.TRUE.toString());
state.setAttribute(STATE_NEED_TO_EXPAND_ALL, Boolean.TRUE.toString());
} // doExpandall
/**
* Unexpand all the collection resources
*/
public static void doUnexpandall ( RunData data)
{
// get the state object
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
//get the ParameterParser from RunData
ParameterParser params = data.getParameters ();
// save the current selections
Set selectedSet = new TreeSet();
String[] selectedItems = params.getStrings ("selectedMembers");
if(selectedItems != null)
{
selectedSet.addAll(Arrays.asList(selectedItems));
}
state.setAttribute(STATE_LIST_SELECTIONS, selectedSet);
state.setAttribute(STATE_EXPANDED_COLLECTIONS, new HashMap());
state.setAttribute(STATE_EXPAND_ALL_FLAG, Boolean.FALSE.toString());
} // doUnexpandall
/**
* Populate the state object, if needed - override to do something!
*/
protected void initState(SessionState state, VelocityPortlet portlet, JetspeedRunData data)
{
super.initState(state, portlet, data);
if(state.getAttribute(STATE_INITIALIZED) == null)
{
initCopyContext(state);
initMoveContext(state);
}
initStateAttributes(state, portlet);
} // initState
/**
* Remove the state variables used internally, on the way out.
*/
static private void cleanupState(SessionState state)
{
state.removeAttribute(STATE_FROM_TEXT);
state.removeAttribute(STATE_HAS_ATTACHMENT_BEFORE);
state.removeAttribute(STATE_ATTACH_SHOW_DROPBOXES);
state.removeAttribute(STATE_ATTACH_COLLECTION_ID);
state.removeAttribute(COPYRIGHT_FAIRUSE_URL);
state.removeAttribute(COPYRIGHT_NEW_COPYRIGHT);
state.removeAttribute(COPYRIGHT_SELF_COPYRIGHT);
state.removeAttribute(COPYRIGHT_TYPES);
state.removeAttribute(DEFAULT_COPYRIGHT_ALERT);
state.removeAttribute(DEFAULT_COPYRIGHT);
state.removeAttribute(STATE_EXPANDED_COLLECTIONS);
state.removeAttribute(STATE_FILE_UPLOAD_MAX_SIZE);
state.removeAttribute(NEW_COPYRIGHT_INPUT);
state.removeAttribute(STATE_COLLECTION_ID);
state.removeAttribute(STATE_COLLECTION_PATH);
state.removeAttribute(STATE_CONTENT_SERVICE);
state.removeAttribute(STATE_CONTENT_TYPE_IMAGE_SERVICE);
//state.removeAttribute(STATE_STACK_EDIT_INTENT);
state.removeAttribute(STATE_EXPAND_ALL_FLAG);
state.removeAttribute(STATE_HELPER_NEW_ITEMS);
state.removeAttribute(STATE_HELPER_CHANGED);
state.removeAttribute(STATE_HOME_COLLECTION_DISPLAY_NAME);
state.removeAttribute(STATE_HOME_COLLECTION_ID);
state.removeAttribute(STATE_LIST_SELECTIONS);
state.removeAttribute(STATE_MY_COPYRIGHT);
state.removeAttribute(STATE_NAVIGATION_ROOT);
state.removeAttribute(STATE_PASTE_ALLOWED_FLAG);
state.removeAttribute(STATE_SELECT_ALL_FLAG);
state.removeAttribute(STATE_SHOW_ALL_SITES);
state.removeAttribute(STATE_SITE_TITLE);
state.removeAttribute(STATE_SORT_ASC);
state.removeAttribute(STATE_SORT_BY);
state.removeAttribute(STATE_STACK_STRUCTOBJ_TYPE);
state.removeAttribute(STATE_STACK_STRUCTOBJ_TYPE_READONLY);
state.removeAttribute(STATE_INITIALIZED);
state.removeAttribute(VelocityPortletPaneledAction.STATE_HELPER);
} // cleanupState
public static void initStateAttributes(SessionState state, VelocityPortlet portlet)
{
if (state.getAttribute (STATE_INITIALIZED) != null) return;
if (state.getAttribute(STATE_FILE_UPLOAD_MAX_SIZE) == null)
{
state.setAttribute(STATE_FILE_UPLOAD_MAX_SIZE, ServerConfigurationService.getString("content.upload.max", "1"));
}
PortletConfig config = portlet.getPortletConfig();
try
{
Integer size = new Integer(config.getInitParameter(PARAM_PAGESIZE));
if(size == null || size.intValue() < 1)
{
size = new Integer(DEFAULT_PAGE_SIZE);
}
state.setAttribute(STATE_PAGESIZE, size);
}
catch(Exception any)
{
state.setAttribute(STATE_PAGESIZE, new Integer(DEFAULT_PAGE_SIZE));
}
// state.setAttribute(STATE_TOP_PAGE_MESSAGE, "");
state.setAttribute (STATE_CONTENT_SERVICE, ContentHostingService.getInstance());
state.setAttribute (STATE_CONTENT_TYPE_IMAGE_SERVICE, ContentTypeImageService.getInstance());
TimeBreakdown timeBreakdown = (TimeService.newTime()).breakdownLocal ();
String mycopyright = COPYRIGHT_SYMBOL + " " + timeBreakdown.getYear () +", " + UserDirectoryService.getCurrentUser().getDisplayName () + ". All Rights Reserved. ";
state.setAttribute (STATE_MY_COPYRIGHT, mycopyright);
if(state.getAttribute(STATE_MODE) == null)
{
state.setAttribute (STATE_MODE, MODE_LIST);
state.setAttribute (STATE_FROM, NULL_STRING);
}
state.setAttribute (STATE_SORT_BY, ResourceProperties.PROP_DISPLAY_NAME);
state.setAttribute (STATE_SORT_ASC, Boolean.TRUE.toString());
state.setAttribute (STATE_SELECT_ALL_FLAG, Boolean.FALSE.toString());
state.setAttribute (STATE_EXPAND_ALL_FLAG, Boolean.FALSE.toString());
state.setAttribute(STATE_LIST_SELECTIONS, new TreeSet());
state.setAttribute (STATE_COLLECTION_PATH, new Vector ());
// %%STATE_MODE_RESOURCES%%
// In helper mode, calling tool should set attribute STATE_MODE_RESOURCES
String resources_mode = (String) state.getAttribute(STATE_MODE_RESOURCES);
if(resources_mode == null)
{
// get resources mode from tool registry
resources_mode = portlet.getPortletConfig().getInitParameter("resources_mode");
if(resources_mode != null)
{
state.setAttribute(STATE_MODE_RESOURCES, resources_mode);
}
}
boolean show_other_sites = false;
if(RESOURCES_MODE_HELPER.equals(resources_mode))
{
show_other_sites = ServerConfigurationService.getBoolean("resources.show_all_collections.helper", SHOW_ALL_SITES_IN_FILE_PICKER);
}
else if(RESOURCES_MODE_DROPBOX.equals(resources_mode))
{
show_other_sites = ServerConfigurationService.getBoolean("resources.show_all_collections.dropbox", SHOW_ALL_SITES_IN_DROPBOX);
}
else
{
show_other_sites = ServerConfigurationService.getBoolean("resources.show_all_collections.tool", SHOW_ALL_SITES_IN_RESOURCES);
}
/** This attribute indicates whether "Other Sites" twiggle should show */
state.setAttribute(STATE_SHOW_ALL_SITES, Boolean.toString(show_other_sites));
/** This attribute indicates whether "Other Sites" twiggle should be open */
state.setAttribute(STATE_SHOW_OTHER_SITES, Boolean.FALSE.toString());
// set the home collection to the parameter, if present, or the default if not
String home = StringUtil.trimToNull(portlet.getPortletConfig().getInitParameter("home"));
state.setAttribute (STATE_HOME_COLLECTION_DISPLAY_NAME, home);
if ((home == null) || (home.length() == 0))
{
// no home set, see if we are in dropbox mode
if (RESOURCES_MODE_DROPBOX.equalsIgnoreCase(resources_mode))
{
home = ContentHostingService.getDropboxCollection();
// if it came back null, we will pretend not to be in dropbox mode
if (home != null)
{
state.setAttribute(STATE_HOME_COLLECTION_DISPLAY_NAME, ContentHostingService.getDropboxDisplayName());
// create/update the collection of folders in the dropbox
ContentHostingService.createDropboxCollection();
}
}
// if we still don't have a home,
if ((home == null) || (home.length() == 0))
{
home = ContentHostingService.getSiteCollection(ToolManager.getCurrentPlacement().getContext());
// TODO: what's the 'name' of the context? -ggolden
// we'll need this to create the home collection if needed
state.setAttribute (STATE_HOME_COLLECTION_DISPLAY_NAME, ToolManager.getCurrentPlacement().getContext()
/*SiteService.getSiteDisplay(ToolManager.getCurrentPlacement().getContext()) */);
}
}
state.setAttribute (STATE_HOME_COLLECTION_ID, home);
state.setAttribute (STATE_COLLECTION_ID, home);
state.setAttribute (STATE_NAVIGATION_ROOT, home);
HomeFactory factory = (HomeFactory) ComponentManager.get("homeFactory");
if(factory != null)
{
Map homes = factory.getHomes(StructuredArtifactHomeInterface.class);
if(! homes.isEmpty())
{
state.setAttribute(STATE_SHOW_FORM_ITEMS, Boolean.TRUE.toString());
}
}
// state.setAttribute (STATE_COLLECTION_ID, state.getAttribute (STATE_HOME_COLLECTION_ID));
if (state.getAttribute(STATE_SITE_TITLE) == null)
{
String title = "";
try
{
title = ((Site) SiteService.getSite(ToolManager.getCurrentPlacement().getContext())).getTitle();
}
catch (IdUnusedException e)
{ // ignore
}
state.setAttribute(STATE_SITE_TITLE, title);
}
HashMap expandedCollections = new HashMap();
//expandedCollections.add (state.getAttribute (STATE_HOME_COLLECTION_ID));
state.setAttribute(STATE_EXPANDED_COLLECTIONS, expandedCollections);
if(state.getAttribute(STATE_USING_CREATIVE_COMMONS) == null)
{
String usingCreativeCommons = ServerConfigurationService.getString("copyright.use_creative_commons");
if( usingCreativeCommons != null && usingCreativeCommons.equalsIgnoreCase(Boolean.TRUE.toString()))
{
state.setAttribute(STATE_USING_CREATIVE_COMMONS, Boolean.TRUE.toString());
}
else
{
state.setAttribute(STATE_USING_CREATIVE_COMMONS, Boolean.FALSE.toString());
}
}
if (state.getAttribute(COPYRIGHT_TYPES) == null)
{
if (ServerConfigurationService.getStrings("copyrighttype") != null)
{
state.setAttribute(COPYRIGHT_TYPES, new ArrayList(Arrays.asList(ServerConfigurationService.getStrings("copyrighttype"))));
}
}
if (state.getAttribute(DEFAULT_COPYRIGHT) == null)
{
if (ServerConfigurationService.getString("default.copyright") != null)
{
state.setAttribute(DEFAULT_COPYRIGHT, ServerConfigurationService.getString("default.copyright"));
}
}
if (state.getAttribute(DEFAULT_COPYRIGHT_ALERT) == null)
{
if (ServerConfigurationService.getString("default.copyright.alert") != null)
{
state.setAttribute(DEFAULT_COPYRIGHT_ALERT, ServerConfigurationService.getString("default.copyright.alert"));
}
}
if (state.getAttribute(NEW_COPYRIGHT_INPUT) == null)
{
if (ServerConfigurationService.getString("newcopyrightinput") != null)
{
state.setAttribute(NEW_COPYRIGHT_INPUT, ServerConfigurationService.getString("newcopyrightinput"));
}
}
if (state.getAttribute(COPYRIGHT_FAIRUSE_URL) == null)
{
if (ServerConfigurationService.getString("fairuse.url") != null)
{
state.setAttribute(COPYRIGHT_FAIRUSE_URL, ServerConfigurationService.getString("fairuse.url"));
}
}
if (state.getAttribute(COPYRIGHT_SELF_COPYRIGHT) == null)
{
if (ServerConfigurationService.getString("copyrighttype.own") != null)
{
state.setAttribute(COPYRIGHT_SELF_COPYRIGHT, ServerConfigurationService.getString("copyrighttype.own"));
}
}
if (state.getAttribute(COPYRIGHT_NEW_COPYRIGHT) == null)
{
if (ServerConfigurationService.getString("copyrighttype.new") != null)
{
state.setAttribute(COPYRIGHT_NEW_COPYRIGHT, ServerConfigurationService.getString("copyrighttype.new"));
}
}
// get resources mode from tool registry
String optional_properties = portlet.getPortletConfig().getInitParameter("optional_properties");
if(optional_properties != null && "true".equalsIgnoreCase(optional_properties))
{
initMetadataContext(state);
}
state.setAttribute(STATE_PREVENT_PUBLIC_DISPLAY, Boolean.FALSE);
String[] siteTypes = ServerConfigurationService.getStrings("prevent.public.resources");
if(siteTypes != null)
{
Site site;
try
{
site = SiteService.getSite(ToolManager.getCurrentPlacement().getContext());
for(int i = 0; i < siteTypes.length; i++)
{
if ((StringUtil.trimToNull(siteTypes[i])).equals(site.getType()))
{
state.setAttribute(STATE_PREVENT_PUBLIC_DISPLAY, Boolean.TRUE);
}
}
}
catch (IdUnusedException e)
{
// allow public display
}
catch(NullPointerException e)
{
// allow public display
}
}
state.setAttribute (STATE_INITIALIZED, Boolean.TRUE.toString());
}
/**
* Setup our observer to be watching for change events for the collection
*/
private void updateObservation(SessionState state, String peid)
{
// ContentObservingCourier observer = (ContentObservingCourier) state.getAttribute(STATE_OBSERVER);
//
// // the delivery location for this tool
// String deliveryId = clientWindowId(state, peid);
// observer.setDeliveryId(deliveryId);
}
/**
* Add additional resource pattern to the observer
*@param pattern The pattern value to be added
*@param state The state object
*/
private static void addObservingPattern(String pattern, SessionState state)
{
// // get the observer and add the pattern
// ContentObservingCourier o = (ContentObservingCourier) state.getAttribute(STATE_OBSERVER);
// o.addResourcePattern(ContentHostingService.getReference(pattern));
//
// // add it back to state
// state.setAttribute(STATE_OBSERVER, o);
} // addObservingPattern
/**
* Remove a resource pattern from the observer
*@param pattern The pattern value to be removed
*@param state The state object
*/
private static void removeObservingPattern(String pattern, SessionState state)
{
// // get the observer and remove the pattern
// ContentObservingCourier o = (ContentObservingCourier) state.getAttribute(STATE_OBSERVER);
// o.removeResourcePattern(ContentHostingService.getReference(pattern));
//
// // add it back to state
// state.setAttribute(STATE_OBSERVER, o);
} // removeObservingPattern
/**
* initialize the copy context
*/
private static void initCopyContext (SessionState state)
{
state.setAttribute (STATE_COPIED_IDS, new Vector ());
state.setAttribute (STATE_COPY_FLAG, Boolean.FALSE.toString());
} // initCopyContent
/**
* initialize the copy context
*/
private static void initMoveContext (SessionState state)
{
state.setAttribute (STATE_MOVED_IDS, new Vector ());
state.setAttribute (STATE_MOVE_FLAG, Boolean.FALSE.toString());
} // initCopyContent
/**
* initialize the cut context
*/
private void initCutContext (SessionState state)
{
state.setAttribute (STATE_CUT_IDS, new Vector ());
state.setAttribute (STATE_CUT_FLAG, Boolean.FALSE.toString());
} // initCutContent
/**
* find out whether there is a duplicate item in testVector
* @param testVector The Vector to be tested on
* @param testSize The integer of the test range
* @return The index value of the duplicate ite
*/
private int repeatedName (Vector testVector, int testSize)
{
for (int i=1; i <= testSize; i++)
{
String currentName = (String) testVector.get (i);
for (int j=i+1; j <= testSize; j++)
{
String comparedTitle = (String) testVector.get (j);
if (comparedTitle.length()>0 && currentName.length()>0 && comparedTitle.equals (currentName))
{
return j;
}
}
}
return 0;
} // repeatedName
/**
* Is the id already exist in the current resource?
* @param testVector The Vector to be tested on
* @param testSize The integer of the test range
* @parma isCollection Looking for collection or not
* @return The index value of the exist id
*/
private int foundInResource (Vector testVector, int testSize, String collectionId, boolean isCollection)
{
try
{
ContentCollection c = ContentHostingService.getCollection(collectionId);
Iterator membersIterator = c.getMemberResources().iterator();
while (membersIterator.hasNext())
{
ResourceProperties p = ((Entity) membersIterator.next()).getProperties();
String displayName = p.getProperty(ResourceProperties.PROP_DISPLAY_NAME);
if (displayName != null)
{
String collectionOrResource = p.getProperty(ResourceProperties.PROP_IS_COLLECTION);
for (int i=1; i <= testSize; i++)
{
String testName = (String) testVector.get(i);
if ((testName != null) && (displayName.equals (testName))
&& ((isCollection && collectionOrResource.equals (Boolean.TRUE.toString()))
|| (!isCollection && collectionOrResource.equals(Boolean.FALSE.toString()))))
{
return i;
}
} // for
}
}
}
catch (IdUnusedException e){}
catch (TypeException e){}
catch (PermissionException e){}
return 0;
} // foundInResource
/**
* empty String Vector object with the size sepecified
* @param size The Vector object size -1
* @return The Vector object consists of null Strings
*/
private static Vector emptyVector (int size)
{
Vector v = new Vector ();
for (int i=0; i <= size; i++)
{
v.add (i, "");
}
return v;
} // emptyVector
/**
* Setup for customization
**/
public String buildOptionsPanelContext( VelocityPortlet portlet,
Context context,
RunData data,
SessionState state)
{
context.put("tlang",rb);
String home = (String) state.getAttribute(STATE_HOME_COLLECTION_ID);
Reference ref = EntityManager.newReference(ContentHostingService.getReference(home));
String siteId = ref.getContext();
context.put("form-submit", BUTTON + "doConfigure_update");
context.put("form-cancel", BUTTON + "doCancel_options");
context.put("description", "Setting options for Resources in worksite "
+ SiteService.getSiteDisplay(siteId));
// pick the "-customize" template based on the standard template name
String template = (String)getContext(data).get("template");
return template + "-customize";
} // buildOptionsPanelContext
/**
* Handle the configure context's update button
*/
public void doConfigure_update(RunData data, Context context)
{
// access the portlet element id to find our state
String peid = ((JetspeedRunData)data).getJs_peid();
SessionState state = ((JetspeedRunData)data).getPortletSessionState(peid);
// we are done with customization... back to the main (browse) mode
state.setAttribute(STATE_MODE, MODE_LIST);
// commit the change
// saveOptions();
cancelOptions();
} // doConfigure_update
/**
* doCancel_options called for form input tags type="submit" named="eventSubmit_doCancel"
* cancel the options process
*/
public void doCancel_options(RunData data, Context context)
{
// access the portlet element id to find our state
String peid = ((JetspeedRunData)data).getJs_peid();
SessionState state = ((JetspeedRunData)data).getPortletSessionState(peid);
// cancel the options
cancelOptions();
// we are done with customization... back to the main (MODE_LIST) mode
state.setAttribute(STATE_MODE, MODE_LIST);
} // doCancel_options
/**
* Add the collection id into the expanded collection list
* @throws PermissionException
* @throws TypeException
* @throws IdUnusedException
*/
public static void doExpand_collection(RunData data) throws IdUnusedException, TypeException, PermissionException
{
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
HashMap currentMap = (HashMap) state.getAttribute(STATE_EXPANDED_COLLECTIONS);
//get the ParameterParser from RunData
ParameterParser params = data.getParameters ();
// save the current selections
Set selectedSet = new TreeSet();
String[] selectedItems = params.getStrings ("selectedMembers");
if(selectedItems != null)
{
selectedSet.addAll(Arrays.asList(selectedItems));
}
state.setAttribute(STATE_LIST_SELECTIONS, selectedSet);
String id = params.getString("collectionId");
currentMap.put (id,ContentHostingService.getCollection (id));
state.setAttribute(STATE_EXPANDED_COLLECTIONS, currentMap);
// add this folder id into the set to be event-observed
addObservingPattern(id, state);
} // doExpand_collection
/**
* Remove the collection id from the expanded collection list
*/
static public void doCollapse_collection(RunData data)
{
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
HashMap currentMap = (HashMap) state.getAttribute(STATE_EXPANDED_COLLECTIONS);
//get the ParameterParser from RunData
ParameterParser params = data.getParameters ();
String collectionId = params.getString("collectionId");
// save the current selections
Set selectedSet = new TreeSet();
String[] selectedItems = data.getParameters ().getStrings ("selectedMembers");
if(selectedItems != null)
{
selectedSet.addAll(Arrays.asList(selectedItems));
}
state.setAttribute(STATE_LIST_SELECTIONS, selectedSet);
HashMap newSet = new HashMap();
Iterator l = currentMap.keySet().iterator ();
while (l.hasNext ())
{
// remove the collection id and all of the subcollections
// Resource collection = (Resource) l.next();
// String id = (String) collection.getId();
String id = (String) l.next();
if (id.indexOf (collectionId)==-1)
{
// newSet.put(id,collection);
newSet.put(id,currentMap.get(id));
}
}
state.setAttribute(STATE_EXPANDED_COLLECTIONS, newSet);
// remove this folder id into the set to be event-observed
removeObservingPattern(collectionId, state);
} // doCollapse_collection
/**
* @param state
* @param homeCollectionId
* @param currentCollectionId
* @return
*/
public static List getCollectionPath(SessionState state)
{
org.sakaiproject.content.api.ContentHostingService contentService = (org.sakaiproject.content.api.ContentHostingService) state.getAttribute (STATE_CONTENT_SERVICE);
// make sure the channedId is set
String currentCollectionId = (String) state.getAttribute (STATE_COLLECTION_ID);
if(! isStackEmpty(state))
{
Map current_stack_frame = peekAtStack(state);
String createCollectionId = (String) current_stack_frame.get(STATE_STACK_CREATE_COLLECTION_ID);
if(createCollectionId == null)
{
createCollectionId = (String) state.getAttribute(STATE_CREATE_COLLECTION_ID);
}
if(createCollectionId != null)
{
currentCollectionId = createCollectionId;
}
else
{
String editCollectionId = (String) current_stack_frame.get(STATE_EDIT_COLLECTION_ID);
if(editCollectionId == null)
{
editCollectionId = (String) state.getAttribute(STATE_EDIT_COLLECTION_ID);
}
if(editCollectionId != null)
{
currentCollectionId = editCollectionId;
}
}
}
String homeCollectionId = (String) state.getAttribute(STATE_HOME_COLLECTION_ID);
String navRoot = (String) state.getAttribute(STATE_NAVIGATION_ROOT);
LinkedList collectionPath = new LinkedList();
String previousCollectionId = "";
Vector pathitems = new Vector();
while(currentCollectionId != null && ! currentCollectionId.equals(navRoot) && ! currentCollectionId.equals(previousCollectionId))
{
pathitems.add(currentCollectionId);
previousCollectionId = currentCollectionId;
currentCollectionId = contentService.getContainingCollectionId(currentCollectionId);
}
pathitems.add(navRoot);
if(!navRoot.equals(homeCollectionId))
{
pathitems.add(homeCollectionId);
}
Iterator items = pathitems.iterator();
while(items.hasNext())
{
String id = (String) items.next();
try
{
ResourceProperties props = contentService.getProperties(id);
String name = props.getPropertyFormatted(ResourceProperties.PROP_DISPLAY_NAME);
PathItem item = new PathItem(id, name);
boolean canRead = contentService.allowGetCollection(id) || contentService.allowGetResource(id);
item.setCanRead(canRead);
String url = contentService.getUrl(id);
item.setUrl(url);
item.setLast(collectionPath.isEmpty());
if(id.equals(homeCollectionId))
{
item.setRoot(homeCollectionId);
}
else
{
item.setRoot(navRoot);
}
try
{
boolean isFolder = props.getBooleanProperty(ResourceProperties.PROP_IS_COLLECTION);
item.setIsFolder(isFolder);
}
catch (EntityPropertyNotDefinedException e1)
{
}
catch (EntityPropertyTypeException e1)
{
}
collectionPath.addFirst(item);
}
catch (PermissionException e)
{
}
catch (IdUnusedException e)
{
}
}
return collectionPath;
}
/**
* Get the items in this folder that should be seen.
* @param collectionId - String version of
* @param expandedCollections - Hash of collection resources
* @param sortedBy - pass through to ContentHostingComparator
* @param sortedAsc - pass through to ContentHostingComparator
* @param parent - The folder containing this item
* @param isLocal - true if navigation root and home collection id of site are the same, false otherwise
* @param state - The session state
* @return a List of BrowseItem objects
*/
protected static List getBrowseItems(String collectionId, HashMap expandedCollections, Set highlightedItems, String sortedBy, String sortedAsc, BrowseItem parent, boolean isLocal, SessionState state)
{
boolean need_to_expand_all = Boolean.TRUE.toString().equals((String)state.getAttribute(STATE_NEED_TO_EXPAND_ALL));
List newItems = new LinkedList();
try
{
// find the ContentHosting service
org.sakaiproject.content.api.ContentHostingService contentService = (org.sakaiproject.content.api.ContentHostingService) state.getAttribute (STATE_CONTENT_SERVICE);
// get the collection
// try using existing resource first
ContentCollection collection = null;
// get the collection
if (expandedCollections.containsKey(collectionId))
{
collection = (ContentCollection) expandedCollections.get(collectionId);
}
else
{
collection = ContentHostingService.getCollection(collectionId);
if(need_to_expand_all)
{
expandedCollections.put(collectionId, collection);
state.setAttribute(STATE_EXPANDED_COLLECTIONS, expandedCollections);
}
}
String dummyId = collectionId.trim();
if(dummyId.endsWith(Entity.SEPARATOR))
{
dummyId += "dummy";
}
else
{
dummyId += Entity.SEPARATOR + "dummy";
}
boolean canRead = false;
boolean canDelete = false;
boolean canRevise = false;
boolean canAddFolder = false;
boolean canAddItem = false;
boolean canUpdate = false;
int depth = 0;
if(parent == null || ! parent.canRead())
{
canRead = contentService.allowGetCollection(collectionId);
}
else
{
canRead = parent.canRead();
}
if(parent == null || ! parent.canDelete())
{
canDelete = contentService.allowRemoveResource(collectionId);
}
else
{
canDelete = parent.canDelete();
}
if(parent == null || ! parent.canRevise())
{
canRevise = contentService.allowUpdateResource(collectionId);
}
else
{
canRevise = parent.canRevise();
}
if(parent == null || ! parent.canAddFolder())
{
canAddFolder = contentService.allowAddCollection(dummyId);
}
else
{
canAddFolder = parent.canAddFolder();
}
if(parent == null || ! parent.canAddItem())
{
canAddItem = contentService.allowAddResource(dummyId);
}
else
{
canAddItem = parent.canAddItem();
}
if(parent == null || ! parent.canUpdate())
{
canUpdate = AuthzGroupService.allowUpdate(collectionId);
}
else
{
canUpdate = parent.canUpdate();
}
if(parent != null)
{
depth = parent.getDepth() + 1;
}
if(canAddItem)
{
state.setAttribute(STATE_PASTE_ALLOWED_FLAG, Boolean.TRUE.toString());
}
boolean hasDeletableChildren = canDelete;
boolean hasCopyableChildren = canRead;
String homeCollectionId = (String) state.getAttribute(STATE_HOME_COLLECTION_ID);
ResourceProperties cProperties = collection.getProperties();
String folderName = cProperties.getProperty(ResourceProperties.PROP_DISPLAY_NAME);
if(collectionId.equals(homeCollectionId))
{
folderName = (String) state.getAttribute(STATE_HOME_COLLECTION_DISPLAY_NAME);
}
BrowseItem folder = new BrowseItem(collectionId, folderName, "folder");
if(parent == null)
{
folder.setRoot(collectionId);
}
else
{
folder.setRoot(parent.getRoot());
}
BasicRightsAssignment rightsObj = new BasicRightsAssignment(folder.getItemNum(), cProperties);
folder.setRights(rightsObj);
AccessMode access = collection.getAccess();
if(access == null || AccessMode.SITE.equals(access))
{
folder.setAccess(AccessMode.INHERITED.toString());
}
else
{
folder.setAccess(access.toString());
}
AccessMode inherited_access = collection.getInheritedAccess();
if(inherited_access == null || AccessMode.SITE.equals(inherited_access))
{
folder.setInheritedAccess(AccessMode.INHERITED.toString());
}
else
{
folder.setInheritedAccess(inherited_access.toString());
}
Collection access_groups = collection.getGroupObjects();
if(access_groups == null)
{
access_groups = new Vector();
}
Collection inherited_access_groups = collection.getInheritedGroupObjects();
if(inherited_access_groups == null)
{
inherited_access_groups = new Vector();
}
folder.setInheritedGroups(access_groups);
if(highlightedItems == null || highlightedItems.isEmpty())
{
// do nothing
}
else if(parent != null && parent.isHighlighted())
{
folder.setInheritsHighlight(true);
folder.setHighlighted(true);
}
else if(highlightedItems.contains(collectionId))
{
folder.setHighlighted(true);
folder.setInheritsHighlight(false);
}
String containerId = contentService.getContainingCollectionId (collectionId);
folder.setContainer(containerId);
folder.setCanRead(canRead);
folder.setCanRevise(canRevise);
folder.setCanAddItem(canAddItem);
folder.setCanAddFolder(canAddFolder);
folder.setCanDelete(canDelete);
folder.setCanUpdate(canUpdate);
try
{
Time createdTime = cProperties.getTimeProperty(ResourceProperties.PROP_CREATION_DATE);
String createdTimeString = createdTime.toStringLocalShortDate();
folder.setCreatedTime(createdTimeString);
}
catch(Exception e)
{
String createdTimeString = cProperties.getProperty(ResourceProperties.PROP_CREATION_DATE);
folder.setCreatedTime(createdTimeString);
}
try
{
String createdBy = getUserProperty(cProperties, ResourceProperties.PROP_CREATOR).getDisplayName();
folder.setCreatedBy(createdBy);
}
catch(Exception e)
{
String createdBy = cProperties.getProperty(ResourceProperties.PROP_CREATOR);
folder.setCreatedBy(createdBy);
}
try
{
Time modifiedTime = cProperties.getTimeProperty(ResourceProperties.PROP_MODIFIED_DATE);
String modifiedTimeString = modifiedTime.toStringLocalShortDate();
folder.setModifiedTime(modifiedTimeString);
}
catch(Exception e)
{
String modifiedTimeString = cProperties.getProperty(ResourceProperties.PROP_MODIFIED_DATE);
folder.setModifiedTime(modifiedTimeString);
}
try
{
String modifiedBy = getUserProperty(cProperties, ResourceProperties.PROP_MODIFIED_BY).getDisplayName();
folder.setModifiedBy(modifiedBy);
}
catch(Exception e)
{
String modifiedBy = cProperties.getProperty(ResourceProperties.PROP_MODIFIED_BY);
folder.setModifiedBy(modifiedBy);
}
String url = contentService.getUrl(collectionId);
folder.setUrl(url);
try
{
int collection_size = contentService.getCollectionSize(collectionId);
folder.setIsEmpty(collection_size < 1);
folder.setIsTooBig(collection_size > EXPANDABLE_FOLDER_SIZE_LIMIT);
}
catch(RuntimeException e)
{
folder.setIsEmpty(true);
folder.setIsTooBig(false);
}
folder.setDepth(depth);
newItems.add(folder);
if(need_to_expand_all || expandedCollections.containsKey (collectionId))
{
// Get the collection members from the 'new' collection
List newMembers = collection.getMemberResources ();
Collections.sort (newMembers, ContentHostingService.newContentHostingComparator (sortedBy, Boolean.valueOf (sortedAsc).booleanValue ()));
// loop thru the (possibly) new members and add to the list
Iterator it = newMembers.iterator();
while(it.hasNext())
{
ContentEntity resource = (ContentEntity) it.next();
ResourceProperties props = resource.getProperties();
String itemId = resource.getId();
if(resource.isCollection())
{
List offspring = getBrowseItems(itemId, expandedCollections, highlightedItems, sortedBy, sortedAsc, folder, isLocal, state);
if(! offspring.isEmpty())
{
BrowseItem child = (BrowseItem) offspring.get(0);
hasDeletableChildren = hasDeletableChildren || child.hasDeletableChildren();
hasCopyableChildren = hasCopyableChildren || child.hasCopyableChildren();
}
// add all the items in the subfolder to newItems
newItems.addAll(offspring);
}
else
{
String itemType = ((ContentResource)resource).getContentType();
String itemName = props.getProperty(ResourceProperties.PROP_DISPLAY_NAME);
BrowseItem newItem = new BrowseItem(itemId, itemName, itemType);
BasicRightsAssignment rightsObj2 = new BasicRightsAssignment(newItem.getItemNum(), props);
newItem.setRights(rightsObj2);
AccessMode access_mode = ((GroupAwareEntity) resource).getAccess();
if(access_mode == null)
{
newItem.setAccess(AccessMode.SITE.toString());
}
else
{
newItem.setAccess(access_mode.toString());
}
Collection groups = ((GroupAwareEntity) resource).getGroupObjects();
if(groups == null)
{
groups = new Vector();
}
Collection inheritedGroups = ((GroupAwareEntity) resource).getInheritedGroupObjects();
if(inheritedGroups == null)
{
inheritedGroups = new Vector();
}
newItem.setGroups(groups);
newItem.setInheritedGroups(inheritedGroups);
newItem.setContainer(collectionId);
newItem.setRoot(folder.getRoot());
newItem.setCanDelete(canDelete);
newItem.setCanRevise(canRevise);
newItem.setCanRead(canRead);
newItem.setCanCopy(canRead);
newItem.setCanAddItem(canAddItem); // true means this user can add an item in the folder containing this item (used for "duplicate")
if(highlightedItems == null || highlightedItems.isEmpty())
{
// do nothing
}
else if(folder.isHighlighted())
{
newItem.setInheritsHighlight(true);
newItem.setHighlighted(true);
}
else if(highlightedItems.contains(itemId))
{
newItem.setHighlighted(true);
newItem.setInheritsHighlight(false);
}
try
{
Time createdTime = props.getTimeProperty(ResourceProperties.PROP_CREATION_DATE);
String createdTimeString = createdTime.toStringLocalShortDate();
newItem.setCreatedTime(createdTimeString);
}
catch(Exception e)
{
String createdTimeString = props.getProperty(ResourceProperties.PROP_CREATION_DATE);
newItem.setCreatedTime(createdTimeString);
}
try
{
String createdBy = getUserProperty(props, ResourceProperties.PROP_CREATOR).getDisplayName();
newItem.setCreatedBy(createdBy);
}
catch(Exception e)
{
String createdBy = props.getProperty(ResourceProperties.PROP_CREATOR);
newItem.setCreatedBy(createdBy);
}
try
{
Time modifiedTime = props.getTimeProperty(ResourceProperties.PROP_MODIFIED_DATE);
String modifiedTimeString = modifiedTime.toStringLocalShortDate();
newItem.setModifiedTime(modifiedTimeString);
}
catch(Exception e)
{
String modifiedTimeString = props.getProperty(ResourceProperties.PROP_MODIFIED_DATE);
newItem.setModifiedTime(modifiedTimeString);
}
try
{
String modifiedBy = getUserProperty(props, ResourceProperties.PROP_MODIFIED_BY).getDisplayName();
newItem.setModifiedBy(modifiedBy);
}
catch(Exception e)
{
String modifiedBy = props.getProperty(ResourceProperties.PROP_MODIFIED_BY);
newItem.setModifiedBy(modifiedBy);
}
String size = props.getPropertyFormatted(ResourceProperties.PROP_CONTENT_LENGTH);
newItem.setSize(size);
String target = Validator.getResourceTarget(props.getProperty(ResourceProperties.PROP_CONTENT_TYPE));
newItem.setTarget(target);
String newUrl = contentService.getUrl(itemId);
newItem.setUrl(newUrl);
try
{
boolean copyrightAlert = props.getBooleanProperty(ResourceProperties.PROP_COPYRIGHT_ALERT);
newItem.setCopyrightAlert(copyrightAlert);
}
catch(Exception e)
{}
newItem.setDepth(depth + 1);
if (checkItemFilter((ContentResource)resource, newItem, state))
{
newItems.add(newItem);
}
}
}
}
folder.seDeletableChildren(hasDeletableChildren);
folder.setCopyableChildren(hasCopyableChildren);
// return newItems;
}
catch (IdUnusedException ignore)
{
// this condition indicates a site that does not have a resources collection (mercury?)
}
catch (TypeException e)
{
addAlert(state, "TypeException.");
}
catch (PermissionException e)
{
// ignore -- we'll just skip this collection since user lacks permission to access it.
//addAlert(state, "PermissionException");
}
return newItems;
} // getBrowseItems
protected static boolean checkItemFilter(ContentResource resource, BrowseItem newItem, SessionState state)
{
ContentResourceFilter filter = (ContentResourceFilter)state.getAttribute(STATE_ATTACH_FILTER);
if (filter != null)
{
if (newItem != null)
{
newItem.setCanSelect(filter.allowSelect(resource));
}
return filter.allowView(resource);
}
else if (newItem != null)
{
newItem.setCanSelect(true);
}
return true;
}
protected static boolean checkSelctItemFilter(ContentResource resource, SessionState state)
{
ContentResourceFilter filter = (ContentResourceFilter)state.getAttribute(STATE_ATTACH_FILTER);
if (filter != null)
{
return filter.allowSelect(resource);
}
return true;
}
/**
* set the state name to be "copy" if any item has been selected for copying
*/
public void doCopyitem ( RunData data )
{
// get the state object
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
String itemId = data.getParameters ().getString ("itemId");
if (itemId == null)
{
// there is no resource selected, show the alert message to the user
addAlert(state, rb.getString("choosefile6"));
state.setAttribute (STATE_MODE, MODE_LIST);
}
else
{
try
{
ResourceProperties properties = ContentHostingService.getProperties (itemId);
/*
if (properties.getProperty (ResourceProperties.PROP_IS_COLLECTION).equals (Boolean.TRUE.toString()))
{
String alert = (String) state.getAttribute(STATE_MESSAGE);
if (alert == null || ((alert != null) && (alert.indexOf(RESOURCE_INVALID_OPERATION_ON_COLLECTION_STRING) == -1)))
{
addAlert(state, RESOURCE_INVALID_OPERATION_ON_COLLECTION_STRING);
}
}
*/
}
catch (PermissionException e)
{
addAlert(state, rb.getString("notpermis15"));
}
catch (IdUnusedException e)
{
addAlert(state,RESOURCE_NOT_EXIST_STRING);
} // try-catch
if (state.getAttribute(STATE_MESSAGE) == null)
{
state.setAttribute (STATE_COPY_FLAG, Boolean.TRUE.toString());
state.setAttribute (STATE_COPIED_ID, itemId);
} // if-else
} // if-else
} // doCopyitem
/**
* Paste the previously copied item(s)
*/
public static void doPasteitems ( RunData data)
{
ParameterParser params = data.getParameters ();
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
List items = (List) state.getAttribute(STATE_COPIED_IDS);
String collectionId = params.getString ("collectionId");
Iterator itemIter = items.iterator();
while (itemIter.hasNext())
{
// get the copied item to be pasted
String itemId = (String) itemIter.next();
String originalDisplayName = NULL_STRING;
try
{
String id = ContentHostingService.copyIntoFolder(itemId, collectionId);
String mode = (String) state.getAttribute(STATE_MODE);
if(MODE_HELPER.equals(mode))
{
String helper_mode = (String) state.getAttribute(STATE_RESOURCES_HELPER_MODE);
if(helper_mode != null && MODE_ATTACHMENT_NEW_ITEM.equals(helper_mode))
{
// add to the attachments vector
List attachments = EntityManager.newReferenceList();
Reference ref = EntityManager.newReference(ContentHostingService.getReference(id));
attachments.add(ref);
cleanupState(state);
state.setAttribute(STATE_ATTACHMENTS, attachments);
}
else
{
if(state.getAttribute(STATE_ATTACH_LINKS) == null)
{
attachItem(id, state);
}
else
{
attachLink(id, state);
}
}
}
}
catch (PermissionException e)
{
addAlert(state, rb.getString("notpermis8") + " " + originalDisplayName + ". ");
}
catch (IdUnusedException e)
{
addAlert(state,RESOURCE_NOT_EXIST_STRING);
}
catch (InUseException e)
{
addAlert(state, rb.getString("someone") + " " + originalDisplayName);
}
catch (TypeException e)
{
addAlert(state, rb.getString("pasteitem") + " " + originalDisplayName + " " + rb.getString("mismatch"));
}
catch(IdUsedException e)
{
addAlert(state, rb.getString("toomany"));
}
catch(IdLengthException e)
{
addAlert(state, rb.getString("toolong") + " " + e.getMessage());
}
catch(IdUniquenessException e)
{
addAlert(state, "Could not add this item to this folder");
}
catch(ServerOverloadException e)
{
addAlert(state, rb.getString("failed"));
}
catch(InconsistentException e)
{
addAlert(state, rb.getString("recursive") + " " + itemId);
}
catch (OverQuotaException e)
{
addAlert(state, rb.getString("overquota"));
} // try-catch
catch(RuntimeException e)
{
logger.error("ResourcesAction.doPasteitems ***** Unknown Exception ***** " + e.getMessage());
addAlert(state, rb.getString("failed"));
}
if (state.getAttribute(STATE_MESSAGE) == null)
{
// delete sucessful
String mode = (String) state.getAttribute(STATE_MODE);
if(MODE_HELPER.equals(mode))
{
state.setAttribute(STATE_RESOURCES_HELPER_MODE, MODE_ATTACHMENT_SELECT);
}
else
{
state.setAttribute (STATE_MODE, MODE_LIST);
}
// try to expand the collection
HashMap expandedCollections = (HashMap) state.getAttribute(STATE_EXPANDED_COLLECTIONS);
if(! expandedCollections.containsKey(collectionId))
{
org.sakaiproject.content.api.ContentHostingService contentService = (org.sakaiproject.content.api.ContentHostingService) state.getAttribute (STATE_CONTENT_SERVICE);
try
{
ContentCollection coll = contentService.getCollection(collectionId);
expandedCollections.put(collectionId, coll);
}
catch(Exception ignore){}
}
// reset the copy flag
if (((String)state.getAttribute (STATE_COPY_FLAG)).equals (Boolean.TRUE.toString()))
{
state.setAttribute (STATE_COPY_FLAG, Boolean.FALSE.toString());
}
}
}
} // doPasteitems
/**
* Paste the item(s) selected to be moved
*/
public static void doMoveitems ( RunData data)
{
ParameterParser params = data.getParameters ();
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
// cancel copy if there is one in progress
if(! Boolean.FALSE.toString().equals(state.getAttribute (STATE_COPY_FLAG)))
{
initCopyContext(state);
}
List items = (List) state.getAttribute(STATE_MOVED_IDS);
String collectionId = params.getString ("collectionId");
Iterator itemIter = items.iterator();
while (itemIter.hasNext())
{
// get the copied item to be pasted
String itemId = (String) itemIter.next();
String originalDisplayName = NULL_STRING;
try
{
/*
ResourceProperties properties = ContentHostingService.getProperties (itemId);
originalDisplayName = properties.getPropertyFormatted (ResourceProperties.PROP_DISPLAY_NAME);
// copy, cut and paste not operated on collections
if (properties.getProperty (ResourceProperties.PROP_IS_COLLECTION).equals (Boolean.TRUE.toString()))
{
String alert = (String) state.getAttribute(STATE_MESSAGE);
if (alert == null || ((alert != null) && (alert.indexOf(RESOURCE_INVALID_OPERATION_ON_COLLECTION_STRING) == -1)))
{
addAlert(state, RESOURCE_INVALID_OPERATION_ON_COLLECTION_STRING);
}
}
else
*/
{
ContentHostingService.moveIntoFolder(itemId, collectionId);
} // if-else
}
catch (PermissionException e)
{
addAlert(state, rb.getString("notpermis8") + " " + originalDisplayName + ". ");
}
catch (IdUnusedException e)
{
addAlert(state,RESOURCE_NOT_EXIST_STRING);
}
catch (InUseException e)
{
addAlert(state, rb.getString("someone") + " " + originalDisplayName);
}
catch (TypeException e)
{
addAlert(state, rb.getString("pasteitem") + " " + originalDisplayName + " " + rb.getString("mismatch"));
}
catch (InconsistentException e)
{
addAlert(state, rb.getString("recursive") + " " + itemId);
}
catch(IdUsedException e)
{
addAlert(state, rb.getString("toomany"));
}
catch(ServerOverloadException e)
{
addAlert(state, rb.getString("failed"));
}
catch (OverQuotaException e)
{
addAlert(state, rb.getString("overquota"));
} // try-catch
catch(RuntimeException e)
{
logger.error("ResourcesAction.doMoveitems ***** Unknown Exception ***** " + e.getMessage());
addAlert(state, rb.getString("failed"));
}
if (state.getAttribute(STATE_MESSAGE) == null)
{
// delete sucessful
String mode = (String) state.getAttribute(STATE_MODE);
if(MODE_HELPER.equals(mode))
{
state.setAttribute(STATE_RESOURCES_HELPER_MODE, MODE_ATTACHMENT_SELECT);
}
else
{
state.setAttribute (STATE_MODE, MODE_LIST);
}
// try to expand the collection
HashMap expandedCollections = (HashMap) state.getAttribute(STATE_EXPANDED_COLLECTIONS);
if(! expandedCollections.containsKey(collectionId))
{
org.sakaiproject.content.api.ContentHostingService contentService = (org.sakaiproject.content.api.ContentHostingService) state.getAttribute (STATE_CONTENT_SERVICE);
try
{
ContentCollection coll = contentService.getCollection(collectionId);
expandedCollections.put(collectionId, coll);
}
catch(Exception ignore){}
}
// reset the copy flag
if (((String)state.getAttribute (STATE_MOVE_FLAG)).equals (Boolean.TRUE.toString()))
{
state.setAttribute (STATE_MOVE_FLAG, Boolean.FALSE.toString());
}
}
}
} // doMoveitems
/**
* Paste the previously copied item(s)
*/
public static void doPasteitem ( RunData data)
{
ParameterParser params = data.getParameters ();
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
// get the copied item to be pasted
String itemId = params.getString("itemId");
String collectionId = params.getString ("collectionId");
String originalDisplayName = NULL_STRING;
try
{
ResourceProperties properties = ContentHostingService.getProperties (itemId);
originalDisplayName = properties.getPropertyFormatted (ResourceProperties.PROP_DISPLAY_NAME);
// copy, cut and paste not operated on collections
if (properties.getProperty (ResourceProperties.PROP_IS_COLLECTION).equals (Boolean.TRUE.toString()))
{
String alert = (String) state.getAttribute(STATE_MESSAGE);
if (alert == null || ((alert != null) && (alert.indexOf(RESOURCE_INVALID_OPERATION_ON_COLLECTION_STRING) == -1)))
{
addAlert(state, RESOURCE_INVALID_OPERATION_ON_COLLECTION_STRING);
}
}
else
{
// paste the resource
ContentResource resource = ContentHostingService.getResource (itemId);
ResourceProperties p = ContentHostingService.getProperties(itemId);
String displayName = DUPLICATE_STRING + p.getProperty(ResourceProperties.PROP_DISPLAY_NAME);
String newItemId = ContentHostingService.copyIntoFolder(itemId, collectionId);
ContentResourceEdit copy = ContentHostingService.editResource(newItemId);
ResourcePropertiesEdit pedit = copy.getPropertiesEdit();
pedit.addProperty(ResourceProperties.PROP_DISPLAY_NAME, displayName);
ContentHostingService.commitResource(copy, NotificationService.NOTI_NONE);
} // if-else
}
catch (PermissionException e)
{
addAlert(state, rb.getString("notpermis8") + " " + originalDisplayName + ". ");
}
catch (IdUnusedException e)
{
addAlert(state,RESOURCE_NOT_EXIST_STRING);
}
catch (IdUsedException e)
{
addAlert(state, rb.getString("notaddreso") + " " + originalDisplayName + " " + rb.getString("used2"));
}
catch(IdLengthException e)
{
addAlert(state, rb.getString("toolong") + " " + e.getMessage());
}
catch(IdUniquenessException e)
{
addAlert(state, "Could not add this item to this folder");
}
catch (InconsistentException ee)
{
addAlert(state, RESOURCE_INVALID_TITLE_STRING);
}
catch(InUseException e)
{
addAlert(state, rb.getString("someone") + " " + originalDisplayName + ". ");
}
catch(OverQuotaException e)
{
addAlert(state, rb.getString("overquota"));
}
catch(ServerOverloadException e)
{
// this represents temporary unavailability of server's filesystem
// for server configured to save resource body in filesystem
addAlert(state, rb.getString("failed"));
}
catch (TypeException e)
{
addAlert(state, rb.getString("pasteitem") + " " + originalDisplayName + " " + rb.getString("mismatch"));
} // try-catch
if (state.getAttribute(STATE_MESSAGE) == null)
{
// delete sucessful
String mode = (String) state.getAttribute(STATE_MODE);
if(MODE_HELPER.equals(mode))
{
state.setAttribute(STATE_RESOURCES_HELPER_MODE, MODE_ATTACHMENT_SELECT);
}
else
{
state.setAttribute (STATE_MODE, MODE_LIST);
}
// try to expand the collection
HashMap expandedCollections = (HashMap) state.getAttribute(STATE_EXPANDED_COLLECTIONS);
if(! expandedCollections.containsKey(collectionId))
{
org.sakaiproject.content.api.ContentHostingService contentService = (org.sakaiproject.content.api.ContentHostingService) state.getAttribute (STATE_CONTENT_SERVICE);
try
{
ContentCollection coll = contentService.getCollection(collectionId);
expandedCollections.put(collectionId, coll);
}
catch(Exception ignore){}
}
// reset the copy flag
if (((String)state.getAttribute (STATE_COPY_FLAG)).equals (Boolean.TRUE.toString()))
{
state.setAttribute (STATE_COPY_FLAG, Boolean.FALSE.toString());
}
}
} // doPasteitem
/**
* Fire up the permissions editor for the current folder's permissions
*/
public void doFolder_permissions(RunData data, Context context)
{
SessionState state = ((JetspeedRunData)data).getPortletSessionState(((JetspeedRunData)data).getJs_peid());
ParameterParser params = data.getParameters();
// cancel copy if there is one in progress
if(! Boolean.FALSE.toString().equals(state.getAttribute (STATE_COPY_FLAG)))
{
initCopyContext(state);
}
// cancel move if there is one in progress
if(! Boolean.FALSE.toString().equals(state.getAttribute (STATE_MOVE_FLAG)))
{
initMoveContext(state);
}
// get the current collection id and the related site
String collectionId = params.getString("collectionId"); //(String) state.getAttribute (STATE_COLLECTION_ID);
String title = "";
try
{
title = ContentHostingService.getProperties(collectionId).getProperty(ResourceProperties.PROP_DISPLAY_NAME);
}
catch (PermissionException e)
{
addAlert(state, rb.getString("notread"));
}
catch (IdUnusedException e)
{
addAlert(state, rb.getString("notfindfol"));
}
// the folder to edit
Reference ref = EntityManager.newReference(ContentHostingService.getReference(collectionId));
state.setAttribute(PermissionsHelper.TARGET_REF, ref.getReference());
// use the folder's context (as a site) for roles
String siteRef = SiteService.siteReference(ref.getContext());
state.setAttribute(PermissionsHelper.ROLES_REF, siteRef);
// ... with this description
state.setAttribute(PermissionsHelper.DESCRIPTION, rb.getString("setpermis") + " " + title);
// ... showing only locks that are prpefixed with this
state.setAttribute(PermissionsHelper.PREFIX, "content.");
// get into helper mode with this helper tool
startHelper(data.getRequest(), "sakai.permissions.helper");
} // doFolder_permissions
/**
* Fire up the permissions editor for the tool's permissions
*/
public void doPermissions(RunData data, Context context)
{
SessionState state = ((JetspeedRunData)data).getPortletSessionState(((JetspeedRunData)data).getJs_peid());
// cancel copy if there is one in progress
if(! Boolean.FALSE.toString().equals(state.getAttribute (STATE_COPY_FLAG)))
{
initCopyContext(state);
}
// cancel move if there is one in progress
if(! Boolean.FALSE.toString().equals(state.getAttribute (STATE_MOVE_FLAG)))
{
initMoveContext(state);
}
// should we save here?
state.setAttribute(STATE_LIST_SELECTIONS, new TreeSet());
// get the current home collection id and the related site
String collectionId = (String) state.getAttribute (STATE_HOME_COLLECTION_ID);
Reference ref = EntityManager.newReference(ContentHostingService.getReference(collectionId));
String siteRef = SiteService.siteReference(ref.getContext());
// setup for editing the permissions of the site for this tool, using the roles of this site, too
state.setAttribute(PermissionsHelper.TARGET_REF, siteRef);
// ... with this description
state.setAttribute(PermissionsHelper.DESCRIPTION, rb.getString("setpermis1")
+ SiteService.getSiteDisplay(ref.getContext()));
// ... showing only locks that are prpefixed with this
state.setAttribute(PermissionsHelper.PREFIX, "content.");
// get into helper mode with this helper tool
startHelper(data.getRequest(), "sakai.permissions.helper");
} // doPermissions
/**
* is notification enabled?
*/
protected boolean notificationEnabled(SessionState state)
{
return true;
} // notificationEnabled
/**
* Processes the HTML document that is coming back from the browser
* (from the formatted text editing widget).
* @param state Used to pass in any user-visible alerts or errors when processing the text
* @param strFromBrowser The string from the browser
* @return The formatted text
*/
private String processHtmlDocumentFromBrowser(SessionState state, String strFromBrowser)
{
StringBuffer alertMsg = new StringBuffer();
String text = FormattedText.processHtmlDocument(strFromBrowser, alertMsg);
if (alertMsg.length() > 0) addAlert(state, alertMsg.toString());
return text;
}
/**
*
* Whether a resource item can be replaced
* @param p The ResourceProperties object for the resource item
* @return true If it can be replaced; false otherwise
*/
private static boolean replaceable(ResourceProperties p)
{
boolean rv = true;
if (p.getPropertyFormatted (ResourceProperties.PROP_IS_COLLECTION).equals (Boolean.TRUE.toString()))
{
rv = false;
}
else if (p.getProperty (ResourceProperties.PROP_CONTENT_TYPE).equals (ResourceProperties.TYPE_URL))
{
rv = false;
}
String displayName = p.getPropertyFormatted (ResourceProperties.PROP_DISPLAY_NAME);
if (displayName.indexOf(SHORTCUT_STRING) != -1)
{
rv = false;
}
return rv;
} // replaceable
/**
*
* put copyright info into context
*/
private static void copyrightChoicesIntoContext(SessionState state, Context context)
{
boolean usingCreativeCommons = state.getAttribute(STATE_USING_CREATIVE_COMMONS) != null && state.getAttribute(STATE_USING_CREATIVE_COMMONS).equals(Boolean.TRUE.toString());
if(usingCreativeCommons)
{
String ccOwnershipLabel = "Who created this resource?";
List ccOwnershipList = new Vector();
ccOwnershipList.add("-- Select --");
ccOwnershipList.add("I created this resource");
ccOwnershipList.add("Someone else created this resource");
String ccMyGrantLabel = "Terms of use";
List ccMyGrantOptions = new Vector();
ccMyGrantOptions.add("-- Select --");
ccMyGrantOptions.add("Use my copyright");
ccMyGrantOptions.add("Use Creative Commons License");
ccMyGrantOptions.add("Use Public Domain Dedication");
String ccCommercialLabel = "Allow commercial use?";
List ccCommercialList = new Vector();
ccCommercialList.add("Yes");
ccCommercialList.add("No");
String ccModificationLabel = "Allow Modifications?";
List ccModificationList = new Vector();
ccModificationList.add("Yes");
ccModificationList.add("Yes, share alike");
ccModificationList.add("No");
String ccOtherGrantLabel = "Terms of use";
List ccOtherGrantList = new Vector();
ccOtherGrantList.add("Subject to fair-use exception");
ccOtherGrantList.add("Public domain (created before copyright law applied)");
ccOtherGrantList.add("Public domain (copyright has expired)");
ccOtherGrantList.add("Public domain (government document not subject to copyright)");
String ccRightsYear = "Year";
String ccRightsOwner = "Copyright owner";
String ccAcknowledgeLabel = "Require users to acknowledge author's rights before access?";
List ccAcknowledgeList = new Vector();
ccAcknowledgeList.add("Yes");
ccAcknowledgeList.add("No");
String ccInfoUrl = "";
int year = TimeService.newTime().breakdownLocal().getYear();
String username = UserDirectoryService.getCurrentUser().getDisplayName();
context.put("usingCreativeCommons", Boolean.TRUE);
context.put("ccOwnershipLabel", ccOwnershipLabel);
context.put("ccOwnershipList", ccOwnershipList);
context.put("ccMyGrantLabel", ccMyGrantLabel);
context.put("ccMyGrantOptions", ccMyGrantOptions);
context.put("ccCommercialLabel", ccCommercialLabel);
context.put("ccCommercialList", ccCommercialList);
context.put("ccModificationLabel", ccModificationLabel);
context.put("ccModificationList", ccModificationList);
context.put("ccOtherGrantLabel", ccOtherGrantLabel);
context.put("ccOtherGrantList", ccOtherGrantList);
context.put("ccRightsYear", ccRightsYear);
context.put("ccRightsOwner", ccRightsOwner);
context.put("ccAcknowledgeLabel", ccAcknowledgeLabel);
context.put("ccAcknowledgeList", ccAcknowledgeList);
context.put("ccInfoUrl", ccInfoUrl);
context.put("ccThisYear", Integer.toString(year));
context.put("ccThisUser", username);
}
else
{
//copyright
if (state.getAttribute(COPYRIGHT_FAIRUSE_URL) != null)
{
context.put("fairuseurl", state.getAttribute(COPYRIGHT_FAIRUSE_URL));
}
if (state.getAttribute(NEW_COPYRIGHT_INPUT) != null)
{
context.put("newcopyrightinput", state.getAttribute(NEW_COPYRIGHT_INPUT));
}
if (state.getAttribute(COPYRIGHT_TYPES) != null)
{
List copyrightTypes = (List) state.getAttribute(COPYRIGHT_TYPES);
context.put("copyrightTypes", copyrightTypes);
context.put("copyrightTypesSize", new Integer(copyrightTypes.size() - 1));
context.put("USE_THIS_COPYRIGHT", copyrightTypes.get(copyrightTypes.size() - 1));
}
}
Boolean preventPublicDisplay = (Boolean) state.getAttribute(STATE_PREVENT_PUBLIC_DISPLAY);
if(preventPublicDisplay == null)
{
preventPublicDisplay = Boolean.FALSE;
state.setAttribute(STATE_PREVENT_PUBLIC_DISPLAY, preventPublicDisplay);
}
context.put("preventPublicDisplay", preventPublicDisplay);
} // copyrightChoicesIntoContext
/**
* Add variables and constants to the velocity context to render an editor
* for inputing and modifying optional metadata properties about a resource.
*/
private static void metadataGroupsIntoContext(SessionState state, Context context)
{
context.put("STRING", ResourcesMetadata.WIDGET_STRING);
context.put("TEXTAREA", ResourcesMetadata.WIDGET_TEXTAREA);
context.put("BOOLEAN", ResourcesMetadata.WIDGET_BOOLEAN);
context.put("INTEGER", ResourcesMetadata.WIDGET_INTEGER);
context.put("DOUBLE", ResourcesMetadata.WIDGET_DOUBLE);
context.put("DATE", ResourcesMetadata.WIDGET_DATE);
context.put("TIME", ResourcesMetadata.WIDGET_TIME);
context.put("DATETIME", ResourcesMetadata.WIDGET_DATETIME);
context.put("ANYURI", ResourcesMetadata.WIDGET_ANYURI);
context.put("WYSIWYG", ResourcesMetadata.WIDGET_WYSIWYG);
context.put("today", TimeService.newTime());
List metadataGroups = (List) state.getAttribute(STATE_METADATA_GROUPS);
if(metadataGroups != null && !metadataGroups.isEmpty())
{
context.put("metadataGroups", metadataGroups);
}
} // metadataGroupsIntoContext
/**
* initialize the metadata context
*/
private static void initMetadataContext(SessionState state)
{
// define MetadataSets map
List metadataGroups = (List) state.getAttribute(STATE_METADATA_GROUPS);
if(metadataGroups == null)
{
metadataGroups = new Vector();
state.setAttribute(STATE_METADATA_GROUPS, metadataGroups);
}
// define DublinCore
if( !metadataGroups.contains(new MetadataGroup(rb.getString("opt_props"))) )
{
MetadataGroup dc = new MetadataGroup( rb.getString("opt_props") );
// dc.add(ResourcesMetadata.PROPERTY_DC_TITLE);
// dc.add(ResourcesMetadata.PROPERTY_DC_DESCRIPTION);
dc.add(ResourcesMetadata.PROPERTY_DC_ALTERNATIVE);
dc.add(ResourcesMetadata.PROPERTY_DC_CREATOR);
dc.add(ResourcesMetadata.PROPERTY_DC_PUBLISHER);
dc.add(ResourcesMetadata.PROPERTY_DC_SUBJECT);
dc.add(ResourcesMetadata.PROPERTY_DC_CREATED);
dc.add(ResourcesMetadata.PROPERTY_DC_ISSUED);
// dc.add(ResourcesMetadata.PROPERTY_DC_MODIFIED);
// dc.add(ResourcesMetadata.PROPERTY_DC_TABLEOFCONTENTS);
dc.add(ResourcesMetadata.PROPERTY_DC_ABSTRACT);
dc.add(ResourcesMetadata.PROPERTY_DC_CONTRIBUTOR);
// dc.add(ResourcesMetadata.PROPERTY_DC_TYPE);
// dc.add(ResourcesMetadata.PROPERTY_DC_FORMAT);
// dc.add(ResourcesMetadata.PROPERTY_DC_IDENTIFIER);
// dc.add(ResourcesMetadata.PROPERTY_DC_SOURCE);
// dc.add(ResourcesMetadata.PROPERTY_DC_LANGUAGE);
// dc.add(ResourcesMetadata.PROPERTY_DC_COVERAGE);
// dc.add(ResourcesMetadata.PROPERTY_DC_RIGHTS);
dc.add(ResourcesMetadata.PROPERTY_DC_AUDIENCE);
dc.add(ResourcesMetadata.PROPERTY_DC_EDULEVEL);
metadataGroups.add(dc);
state.setAttribute(STATE_METADATA_GROUPS, metadataGroups);
}
/*
// define DublinCore
if(!metadataGroups.contains(new MetadataGroup("Test of Datatypes")))
{
MetadataGroup dc = new MetadataGroup("Test of Datatypes");
dc.add(ResourcesMetadata.PROPERTY_DC_TITLE);
dc.add(ResourcesMetadata.PROPERTY_DC_DESCRIPTION);
dc.add(ResourcesMetadata.PROPERTY_DC_ANYURI);
dc.add(ResourcesMetadata.PROPERTY_DC_DOUBLE);
dc.add(ResourcesMetadata.PROPERTY_DC_DATETIME);
dc.add(ResourcesMetadata.PROPERTY_DC_TIME);
dc.add(ResourcesMetadata.PROPERTY_DC_DATE);
dc.add(ResourcesMetadata.PROPERTY_DC_BOOLEAN);
dc.add(ResourcesMetadata.PROPERTY_DC_INTEGER);
metadataGroups.add(dc);
state.setAttribute(STATE_METADATA_GROUPS, metadataGroups);
}
*/
}
/**
* Internal class that encapsulates all information about a resource that is needed in the browse mode
*/
public static class BrowseItem
{
protected static Integer seqnum = new Integer(0);
private String m_itemnum;
// attributes of all resources
protected String m_name;
protected String m_id;
protected String m_type;
protected boolean m_canRead;
protected boolean m_canRevise;
protected boolean m_canDelete;
protected boolean m_canCopy;
protected boolean m_isCopied;
protected boolean m_canAddItem;
protected boolean m_canAddFolder;
protected boolean m_canSelect;
protected List m_members;
protected boolean m_isEmpty;
protected boolean m_isHighlighted;
protected boolean m_inheritsHighlight;
protected String m_createdBy;
protected String m_createdTime;
protected String m_modifiedBy;
protected String m_modifiedTime;
protected String m_size;
protected String m_target;
protected String m_container;
protected String m_root;
protected int m_depth;
protected boolean m_hasDeletableChildren;
protected boolean m_hasCopyableChildren;
protected boolean m_copyrightAlert;
protected String m_url;
protected boolean m_isLocal;
protected boolean m_isAttached;
private boolean m_isMoved;
private boolean m_canUpdate;
private boolean m_toobig;
protected String m_access;
protected String m_inheritedAccess;
protected List m_groups;
protected List m_inheritedGroups;
protected BasicRightsAssignment m_rights;
/**
* @param id
* @param name
* @param type
*/
public BrowseItem(String id, String name, String type)
{
m_name = name;
m_id = id;
m_type = type;
Integer snum;
synchronized(seqnum)
{
snum = seqnum;
seqnum = new Integer((seqnum.intValue() + 1) % 10000);
}
m_itemnum = "Item00000000".substring(0,10 - snum.toString().length()) + snum.toString();
// set defaults
m_rights = new BasicRightsAssignment(m_itemnum, false);
m_members = new LinkedList();
m_canRead = false;
m_canRevise = false;
m_canDelete = false;
m_canCopy = false;
m_isEmpty = true;
m_toobig = false;
m_isCopied = false;
m_isMoved = false;
m_isAttached = false;
m_canSelect = true; // default is true.
m_hasDeletableChildren = false;
m_hasCopyableChildren = false;
m_createdBy = "";
m_modifiedBy = "";
// m_createdTime = TimeService.newTime().toStringLocalDate();
// m_modifiedTime = TimeService.newTime().toStringLocalDate();
m_size = "";
m_depth = 0;
m_copyrightAlert = false;
m_url = "";
m_target = "";
m_root = "";
m_isHighlighted = false;
m_inheritsHighlight = false;
m_canAddItem = false;
m_canAddFolder = false;
m_canUpdate = false;
m_access = AccessMode.INHERITED.toString();
m_groups = new Vector();
}
public String getItemNum()
{
return m_itemnum;
}
public void setIsTooBig(boolean toobig)
{
m_toobig = toobig;
}
public boolean isTooBig()
{
return m_toobig;
}
/**
* @param name
*/
public void setName(String name)
{
m_name = name;
}
/**
* @param root
*/
public void setRoot(String root)
{
m_root = root;
}
/**
* @return
*/
public String getRoot()
{
return m_root;
}
/**
* @return
*/
public List getMembers()
{
List rv = new LinkedList();
if(m_members != null)
{
rv.addAll(m_members);
}
return rv;
}
/**
* @param members
*/
public void addMembers(Collection members)
{
if(m_members == null)
{
m_members = new LinkedList();
}
m_members.addAll(members);
}
/**
* @return
*/
public boolean canAddItem()
{
return m_canAddItem;
}
/**
* @return
*/
public boolean canDelete()
{
return m_canDelete;
}
/**
* @return
*/
public boolean canRead()
{
return m_canRead;
}
public boolean canSelect() {
return m_canSelect;
}
/**
* @return
*/
public boolean canRevise()
{
return m_canRevise;
}
/**
* @return
*/
public String getId()
{
return m_id;
}
/**
* @return
*/
public String getName()
{
return m_name;
}
/**
* @return
*/
public int getDepth()
{
return m_depth;
}
/**
* @param depth
*/
public void setDepth(int depth)
{
m_depth = depth;
}
/**
* @param canCreate
*/
public void setCanAddItem(boolean canAddItem)
{
m_canAddItem = canAddItem;
}
/**
* @param canDelete
*/
public void setCanDelete(boolean canDelete)
{
m_canDelete = canDelete;
}
/**
* @param canRead
*/
public void setCanRead(boolean canRead)
{
m_canRead = canRead;
}
public void setCanSelect(boolean canSelect) {
m_canSelect = canSelect;
}
/**
* @param canRevise
*/
public void setCanRevise(boolean canRevise)
{
m_canRevise = canRevise;
}
/**
* @return
*/
public boolean isFolder()
{
return TYPE_FOLDER.equals(m_type);
}
/**
* @return
*/
public String getType()
{
return m_type;
}
/**
* @return
*/
public boolean canAddFolder()
{
return m_canAddFolder;
}
/**
* @param b
*/
public void setCanAddFolder(boolean canAddFolder)
{
m_canAddFolder = canAddFolder;
}
/**
* @return
*/
public boolean canCopy()
{
return m_canCopy;
}
/**
* @param canCopy
*/
public void setCanCopy(boolean canCopy)
{
m_canCopy = canCopy;
}
/**
* @return
*/
public boolean hasCopyrightAlert()
{
return m_copyrightAlert;
}
/**
* @param copyrightAlert
*/
public void setCopyrightAlert(boolean copyrightAlert)
{
m_copyrightAlert = copyrightAlert;
}
/**
* @return
*/
public String getUrl()
{
return m_url;
}
/**
* @param url
*/
public void setUrl(String url)
{
m_url = url;
}
/**
* @return
*/
public boolean isCopied()
{
return m_isCopied;
}
/**
* @param isCopied
*/
public void setCopied(boolean isCopied)
{
m_isCopied = isCopied;
}
/**
* @return
*/
public boolean isMoved()
{
return m_isMoved;
}
/**
* @param isCopied
*/
public void setMoved(boolean isMoved)
{
m_isMoved = isMoved;
}
/**
* @return
*/
public String getCreatedBy()
{
return m_createdBy;
}
/**
* @return
*/
public String getCreatedTime()
{
return m_createdTime;
}
/**
* @return
*/
public String getModifiedBy()
{
return m_modifiedBy;
}
/**
* @return
*/
public String getModifiedTime()
{
return m_modifiedTime;
}
/**
* @return
*/
public String getSize()
{
if(m_size == null)
{
m_size = "";
}
return m_size;
}
/**
* @param creator
*/
public void setCreatedBy(String creator)
{
m_createdBy = creator;
}
/**
* @param time
*/
public void setCreatedTime(String time)
{
m_createdTime = time;
}
/**
* @param modifier
*/
public void setModifiedBy(String modifier)
{
m_modifiedBy = modifier;
}
/**
* @param time
*/
public void setModifiedTime(String time)
{
m_modifiedTime = time;
}
/**
* @param size
*/
public void setSize(String size)
{
m_size = size;
}
/**
* @return
*/
public String getTarget()
{
return m_target;
}
/**
* @param target
*/
public void setTarget(String target)
{
m_target = target;
}
/**
* @return
*/
public boolean isEmpty()
{
return m_isEmpty;
}
/**
* @param isEmpty
*/
public void setIsEmpty(boolean isEmpty)
{
m_isEmpty = isEmpty;
}
/**
* @return
*/
public String getContainer()
{
return m_container;
}
/**
* @param container
*/
public void setContainer(String container)
{
m_container = container;
}
public void setIsLocal(boolean isLocal)
{
m_isLocal = isLocal;
}
public boolean isLocal()
{
return m_isLocal;
}
/**
* @return Returns the isAttached.
*/
public boolean isAttached()
{
return m_isAttached;
}
/**
* @param isAttached The isAttached to set.
*/
public void setAttached(boolean isAttached)
{
this.m_isAttached = isAttached;
}
/**
* @return Returns the hasCopyableChildren.
*/
public boolean hasCopyableChildren()
{
return m_hasCopyableChildren;
}
/**
* @param hasCopyableChildren The hasCopyableChildren to set.
*/
public void setCopyableChildren(boolean hasCopyableChildren)
{
this.m_hasCopyableChildren = hasCopyableChildren;
}
/**
* @return Returns the hasDeletableChildren.
*/
public boolean hasDeletableChildren()
{
return m_hasDeletableChildren;
}
/**
* @param hasDeletableChildren The hasDeletableChildren to set.
*/
public void seDeletableChildren(boolean hasDeletableChildren)
{
this.m_hasDeletableChildren = hasDeletableChildren;
}
/**
* @return Returns the canUpdate.
*/
public boolean canUpdate()
{
return m_canUpdate;
}
/**
* @param canUpdate The canUpdate to set.
*/
public void setCanUpdate(boolean canUpdate)
{
m_canUpdate = canUpdate;
}
public void setHighlighted(boolean isHighlighted)
{
m_isHighlighted = isHighlighted;
}
public boolean isHighlighted()
{
return m_isHighlighted;
}
public void setInheritsHighlight(boolean inheritsHighlight)
{
m_inheritsHighlight = inheritsHighlight;
}
public boolean inheritsHighlighted()
{
return m_inheritsHighlight;
}
/**
* Access the access mode for this item.
* @return The access mode.
*/
public String getAccess()
{
return m_access;
}
/**
* Access the access mode for this item.
* @return The access mode.
*/
public String getInheritedAccess()
{
return m_inheritedAccess;
}
public String getEntityAccess()
{
String rv = AccessMode.INHERITED.toString();
boolean sameGroups = true;
if(AccessMode.GROUPED.toString().equals(m_access))
{
Iterator it = getGroups().iterator();
while(sameGroups && it.hasNext())
{
Group g = (Group) it.next();
sameGroups = inheritsGroup(g.getReference());
}
it = getInheritedGroups().iterator();
while(sameGroups && it.hasNext())
{
Group g = (Group) it.next();
sameGroups = hasGroup(g.getReference());
}
if(!sameGroups)
{
rv = AccessMode.GROUPED.toString();
}
}
return rv;
}
/**
* Set the access mode for this item.
* @param access
*/
public void setAccess(String access)
{
m_access = access;
}
/**
* Set the access mode for this item.
* @param access
*/
public void setInheritedAccess(String access)
{
m_inheritedAccess = access;
}
/**
* Access a list of Group objects that can access this item.
* @return Returns the groups.
*/
public List getGroups()
{
if(m_groups == null)
{
m_groups = new Vector();
}
return m_groups;
}
/**
* Access a list of Group objects that can access this item.
* @return Returns the groups.
*/
public List getInheritedGroups()
{
if(m_inheritedGroups == null)
{
m_inheritedGroups = new Vector();
}
return m_inheritedGroups;
}
/**
* Determine whether a group has access to this item.
* @param groupRef The internal reference string that uniquely identifies the group.
* @return true if the group has access, false otherwise.
*/
public boolean hasGroup(String groupRef)
{
if(m_groups == null)
{
m_groups = new Vector();
}
boolean found = false;
Iterator it = m_groups.iterator();
while(it.hasNext() && !found)
{
Group gr = (Group) it.next();
found = gr.getReference().equals(groupRef);
}
return found;
}
/**
* Determine whether a group has access to this item.
* @param groupRef The internal reference string that uniquely identifies the group.
* @return true if the group has access, false otherwise.
*/
public boolean inheritsGroup(String groupRef)
{
if(m_inheritedGroups == null)
{
m_inheritedGroups = new Vector();
}
boolean found = false;
Iterator it = m_inheritedGroups.iterator();
while(it.hasNext() && !found)
{
Group gr = (Group) it.next();
found = gr.getReference().equals(groupRef);
}
return found;
}
/**
* Replace the current list of groups with this list of Group objects representing the groups that have access to this item.
* @param groups The groups to set.
*/
public void setGroups(Collection groups)
{
if(groups == null)
{
return;
}
if(m_groups == null)
{
m_groups = new Vector();
}
m_groups.clear();
Iterator it = groups.iterator();
while(it.hasNext())
{
Object obj = it.next();
if(obj instanceof Group)
{
m_groups.add(obj);
}
else if(obj instanceof String)
{
addGroup((String) obj);
}
}
}
/**
* Replace the current list of groups with this list of Group objects representing the groups that have access to this item.
* @param groups The groups to set.
*/
public void setInheritedGroups(Collection groups)
{
if(groups == null)
{
return;
}
if(m_inheritedGroups == null)
{
m_inheritedGroups = new Vector();
}
m_inheritedGroups.clear();
Iterator it = groups.iterator();
while(it.hasNext())
{
Object obj = it.next();
if(obj instanceof Group)
{
m_inheritedGroups.add(obj);
}
else if(obj instanceof String)
{
addInheritedGroup((String) obj);
}
}
}
/**
* Add a string reference identifying a Group to the list of groups that have access to this item.
* @param groupRef
*/
public void addGroup(String groupId)
{
if(m_groups == null)
{
m_groups = new Vector();
}
if(m_container == null)
{
if(m_id == null)
{
m_container = ContentHostingService.getSiteCollection(ToolManager.getCurrentPlacement().getContext());
}
else
{
m_container = ContentHostingService.getContainingCollectionId(m_id);
}
if(m_container == null || m_container.trim() == "")
{
m_container = ContentHostingService.getSiteCollection(ToolManager.getCurrentPlacement().getContext());
}
}
boolean found = false;
Collection groups = ContentHostingService.getGroupsWithReadAccess(m_container);
Iterator it = groups.iterator();
while( it.hasNext() && !found )
{
Group group = (Group) it.next();
if(group.getId().equals(groupId))
{
if(! hasGroup(group.getReference()))
{
m_groups.add(group);
}
found = true;
}
}
}
/**
* Add a string reference identifying a Group to the list of groups that have access to this item.
* @param groupRef
*/
public void addInheritedGroup(String groupId)
{
if(m_inheritedGroups == null)
{
m_inheritedGroups = new Vector();
}
if(m_container == null)
{
if(m_id == null)
{
m_container = ContentHostingService.getSiteCollection(ToolManager.getCurrentPlacement().getContext());
}
else
{
m_container = ContentHostingService.getContainingCollectionId(m_id);
}
if(m_container == null || m_container.trim() == "")
{
m_container = ContentHostingService.getSiteCollection(ToolManager.getCurrentPlacement().getContext());
}
}
boolean found = false;
Collection groups = ContentHostingService.getGroupsWithReadAccess(m_container);
Iterator it = groups.iterator();
while( it.hasNext() && !found )
{
Group group = (Group) it.next();
if(group.getId().equals(groupId))
{
if(! hasGroup(group.getReference()))
{
m_inheritedGroups.add(group);
}
found = true;
}
}
}
/**
* Remove all groups from the item.
*/
public void clearGroups()
{
if(this.m_groups == null)
{
m_groups = new Vector();
}
m_groups.clear();
}
/**
* Remove all inherited groups from the item.
*/
public void clearInheritedGroups()
{
if(m_inheritedGroups == null)
{
m_inheritedGroups = new Vector();
}
m_inheritedGroups.clear();
}
/**
* @return Returns the rights.
*/
public BasicRightsAssignment getRights()
{
return m_rights;
}
/**
* @param rights The rights to set.
*/
public void setRights(BasicRightsAssignment rights)
{
this.m_rights = rights;
}
} // inner class BrowseItem
/**
* Inner class encapsulates information about resources (folders and items) for editing
*/
public static class EditItem
extends BrowseItem
{
protected String m_copyrightStatus;
protected String m_copyrightInfo;
// protected boolean m_copyrightAlert;
protected boolean m_pubview;
protected boolean m_pubviewset;
protected String m_filename;
protected byte[] m_content;
protected String m_encoding;
protected String m_mimetype;
protected String m_description;
protected Map m_metadata;
protected boolean m_hasQuota;
protected boolean m_canSetQuota;
protected String m_quota;
protected boolean m_isUrl;
protected boolean m_contentHasChanged;
protected boolean m_contentTypeHasChanged;
- protected int m_notification;
+ protected int m_notification = NotificationService.NOTI_NONE;
protected String m_formtype;
protected String m_rootname;
protected Map m_structuredArtifact;
protected List m_properties;
protected Set m_metadataGroupsShowing;
protected Set m_missingInformation;
protected boolean m_hasBeenAdded;
protected ResourcesMetadata m_form;
protected boolean m_isBlank;
protected String m_instruction;
protected String m_ccRightsownership;
protected String m_ccLicense;
protected String m_ccCommercial;
protected String m_ccModification;
protected String m_ccRightsOwner;
protected String m_ccRightsYear;
/**
* @param id
* @param name
* @param type
*/
public EditItem(String id, String name, String type)
{
super(id, name, type);
m_filename = "";
m_contentHasChanged = false;
m_contentTypeHasChanged = false;
m_metadata = new Hashtable();
m_structuredArtifact = new Hashtable();
m_metadataGroupsShowing = new HashSet();
m_mimetype = type;
m_content = null;
m_encoding = "UTF-8";
m_notification = NotificationService.NOTI_NONE;
m_hasQuota = false;
m_canSetQuota = false;
m_formtype = "";
m_rootname = "";
m_missingInformation = new HashSet();
m_hasBeenAdded = false;
m_properties = new Vector();
m_isBlank = true;
m_instruction = "";
m_pubview = false;
m_pubviewset = false;
m_ccRightsownership = "";
m_ccLicense = "";
// m_copyrightStatus = ServerConfigurationService.getString("default.copyright");
}
public void setRightsowner(String ccRightsOwner)
{
m_ccRightsOwner = ccRightsOwner;
}
public String getRightsowner()
{
return m_ccRightsOwner;
}
public void setRightstyear(String ccRightsYear)
{
m_ccRightsYear = ccRightsYear;
}
public String getRightsyear()
{
return m_ccRightsYear;
}
public void setAllowModifications(String ccModification)
{
m_ccModification = ccModification;
}
public String getAllowModifications()
{
return m_ccModification;
}
public void setAllowCommercial(String ccCommercial)
{
m_ccCommercial = ccCommercial;
}
public String getAllowCommercial()
{
return m_ccCommercial;
}
/**
*
* @param license
*/
public void setLicense(String license)
{
m_ccLicense = license;
}
/**
*
* @return
*/
public String getLicense()
{
return m_ccLicense;
}
/**
* Record a value for instructions to be displayed to the user in the editor (for Form Items).
* @param instruction The value of the instructions.
*/
public void setInstruction(String instruction)
{
if(instruction == null)
{
instruction = "";
}
m_instruction = instruction.trim();
}
/**
* Access instructions to be displayed to the user in the editor (for Form Items).
* @return The instructions.
*/
public String getInstruction()
{
return m_instruction;
}
/**
* Set the character encoding type that will be used when converting content body between strings and byte arrays.
* Default is "UTF-8".
* @param encoding A valid name for a character set encoding scheme (@see java.lang.Charset)
*/
public void setEncoding(String encoding)
{
m_encoding = encoding;
}
/**
* Get the character encoding type that is used when converting content body between strings and byte arrays.
* Default is "UTF-8".
* @return The name of the character set encoding scheme (@see java.lang.Charset)
*/
public String getEncoding()
{
return m_encoding;
}
/**
* Set marker indicating whether current item is a blank entry
* @param isBlank
*/
public void markAsBlank(boolean isBlank)
{
m_isBlank = isBlank;
}
/**
* Access marker indicating whether current item is a blank entry
* @return true if current entry is blank, false otherwise
*/
public boolean isBlank()
{
return m_isBlank;
}
/**
* Change the root ResourcesMetadata object that defines the form for a Structured Artifact.
* @param form
*/
public void setForm(ResourcesMetadata form)
{
m_form = form;
}
/**
* Access the root ResourcesMetadata object that defines the form for a Structured Artifact.
* @return the form.
*/
public ResourcesMetadata getForm()
{
return m_form;
}
/**
* @param properties
*/
public void setProperties(List properties)
{
m_properties = properties;
}
public List getProperties()
{
return m_properties;
}
/**
* Replace current values of Structured Artifact with new values.
* @param map The new values.
*/
public void setValues(Map map)
{
m_structuredArtifact = map;
}
/**
* Access the entire set of values stored in the Structured Artifact
* @return The set of values.
*/
public Map getValues()
{
return m_structuredArtifact;
}
/**
* @param id
* @param name
* @param type
*/
public EditItem(String type)
{
this(null, "", type);
}
/**
* @param id
*/
public void setId(String id)
{
m_id = id;
}
/**
* Show the indicated metadata group for the item
* @param group
*/
public void showMetadataGroup(String group)
{
m_metadataGroupsShowing.add(group);
}
/**
* Hide the indicated metadata group for the item
* @param group
*/
public void hideMetadataGroup(String group)
{
m_metadataGroupsShowing.remove(group);
m_metadataGroupsShowing.remove(Validator.escapeUrl(group));
}
/**
* Query whether the indicated metadata group is showing for the item
* @param group
* @return true if the metadata group is showing, false otherwise
*/
public boolean isGroupShowing(String group)
{
return m_metadataGroupsShowing.contains(group) || m_metadataGroupsShowing.contains(Validator.escapeUrl(group));
}
/**
* @return
*/
public boolean isFileUpload()
{
return !isFolder() && !isUrl() && !isHtml() && !isPlaintext() && !isStructuredArtifact();
}
/**
* @param type
*/
public void setType(String type)
{
m_type = type;
}
/**
* @param mimetype
*/
public void setMimeType(String mimetype)
{
m_mimetype = mimetype;
}
public String getRightsownership()
{
return m_ccRightsownership;
}
public void setRightsownership(String owner)
{
m_ccRightsownership = owner;
}
/**
* @return
*/
public String getMimeType()
{
return m_mimetype;
}
public String getMimeCategory()
{
if(this.m_mimetype == null || this.m_mimetype.equals(""))
{
return "";
}
int index = this.m_mimetype.indexOf("/");
if(index < 0)
{
return this.m_mimetype;
}
return this.m_mimetype.substring(0, index);
}
public String getMimeSubtype()
{
if(this.m_mimetype == null || this.m_mimetype.equals(""))
{
return "";
}
int index = this.m_mimetype.indexOf("/");
if(index < 0 || index + 1 == this.m_mimetype.length())
{
return "";
}
return this.m_mimetype.substring(index + 1);
}
/**
* @param formtype
*/
public void setFormtype(String formtype)
{
m_formtype = formtype;
}
/**
* @return
*/
public String getFormtype()
{
return m_formtype;
}
/**
* @return Returns the copyrightInfo.
*/
public String getCopyrightInfo() {
return m_copyrightInfo;
}
/**
* @param copyrightInfo The copyrightInfo to set.
*/
public void setCopyrightInfo(String copyrightInfo) {
m_copyrightInfo = copyrightInfo;
}
/**
* @return Returns the copyrightStatus.
*/
public String getCopyrightStatus() {
return m_copyrightStatus;
}
/**
* @param copyrightStatus The copyrightStatus to set.
*/
public void setCopyrightStatus(String copyrightStatus) {
m_copyrightStatus = copyrightStatus;
}
/**
* @return Returns the description.
*/
public String getDescription() {
return m_description;
}
/**
* @param description The description to set.
*/
public void setDescription(String description) {
m_description = description;
}
/**
* @return Returns the filename.
*/
public String getFilename() {
return m_filename;
}
/**
* @param filename The filename to set.
*/
public void setFilename(String filename) {
m_filename = filename;
}
/**
* @return Returns the metadata.
*/
public Map getMetadata() {
return m_metadata;
}
/**
* @param metadata The metadata to set.
*/
public void setMetadata(Map metadata) {
m_metadata = metadata;
}
/**
* @param name
* @param value
*/
public void setMetadataItem(String name, Object value)
{
m_metadata.put(name, value);
}
/**
* @return Returns the pubview.
*/
public boolean isPubview() {
return m_pubview;
}
/**
* @param pubview The pubview to set.
*/
public void setPubview(boolean pubview) {
m_pubview = pubview;
}
/**
* @return Returns the pubviewset.
*/
public boolean isPubviewset() {
return m_pubviewset;
}
/**
* @param pubviewset The pubviewset to set.
*/
public void setPubviewset(boolean pubviewset) {
m_pubviewset = pubviewset;
}
/**
* @return Returns the content.
*/
public byte[] getContent() {
return m_content;
}
/**
* @return Returns the content as a String.
*/
public String getContentstring()
{
String rv = "";
if(m_content != null && m_content.length > 0)
{
try
{
rv = new String( m_content, m_encoding );
}
catch(UnsupportedEncodingException e)
{
rv = new String( m_content );
}
}
return rv;
}
/**
* @param content The content to set.
*/
public void setContent(byte[] content) {
m_content = content;
}
/**
* @param content The content to set.
*/
public void setContent(String content) {
try
{
m_content = content.getBytes(m_encoding);
}
catch(UnsupportedEncodingException e)
{
m_content = content.getBytes();
}
}
/**
* @return Returns the canSetQuota.
*/
public boolean canSetQuota() {
return m_canSetQuota;
}
/**
* @param canSetQuota The canSetQuota to set.
*/
public void setCanSetQuota(boolean canSetQuota) {
m_canSetQuota = canSetQuota;
}
/**
* @return Returns the hasQuota.
*/
public boolean hasQuota() {
return m_hasQuota;
}
/**
* @param hasQuota The hasQuota to set.
*/
public void setHasQuota(boolean hasQuota) {
m_hasQuota = hasQuota;
}
/**
* @return Returns the quota.
*/
public String getQuota() {
return m_quota;
}
/**
* @param quota The quota to set.
*/
public void setQuota(String quota) {
m_quota = quota;
}
/**
* @return true if content-type of item indicates it represents a URL, false otherwise
*/
public boolean isUrl()
{
return TYPE_URL.equals(m_type) || ResourceProperties.TYPE_URL.equals(m_mimetype);
}
/**
* @return true if content-type of item indicates it represents a URL, false otherwise
*/
public boolean isStructuredArtifact()
{
return TYPE_FORM.equals(m_type);
}
/**
* @return true if content-type of item is "text/text" (plain text), false otherwise
*/
public boolean isPlaintext()
{
return MIME_TYPE_DOCUMENT_PLAINTEXT.equals(m_mimetype) || MIME_TYPE_DOCUMENT_PLAINTEXT.equals(m_type);
}
/**
* @return true if content-type of item is "text/html" (an html document), false otherwise
*/
public boolean isHtml()
{
return MIME_TYPE_DOCUMENT_HTML.equals(m_mimetype) || MIME_TYPE_DOCUMENT_HTML.equals(m_type);
}
public boolean contentHasChanged()
{
return m_contentHasChanged;
}
public void setContentHasChanged(boolean changed)
{
m_contentHasChanged = changed;
}
public boolean contentTypeHasChanged()
{
return m_contentTypeHasChanged;
}
public void setContentTypeHasChanged(boolean changed)
{
m_contentTypeHasChanged = changed;
}
public void setNotification(int notification)
{
m_notification = notification;
}
public int getNotification()
{
return m_notification;
}
/**
* @return Returns the artifact.
*/
public Map getStructuredArtifact()
{
return m_structuredArtifact;
}
/**
* @param artifact The artifact to set.
*/
public void setStructuredArtifact(Map artifact)
{
this.m_structuredArtifact = artifact;
}
/**
* @param name
* @param value
*/
public void setValue(String name, Object value)
{
setValue(name, 0, value);
}
/**
* @param name
* @param index
* @param value
*/
public void setValue(String name, int index, Object value)
{
List list = getList(name);
try
{
list.set(index, value);
}
catch(ArrayIndexOutOfBoundsException e)
{
list.add(value);
}
m_structuredArtifact.put(name, list);
}
/**
* Access a value of a structured artifact field of type String.
* @param name The name of the field to access.
* @return the value, or null if the named field is null or not a String.
*/
public String getString(String name)
{
if(m_structuredArtifact == null)
{
m_structuredArtifact = new Hashtable();
}
Object value = m_structuredArtifact.get(name);
String rv = "";
if(value == null)
{
// do nothing
}
else if(value instanceof String)
{
rv = (String) value;
}
else
{
rv = value.toString();
}
return rv;
}
public Object getValue(String name, int index)
{
List list = getList(name);
Object rv = null;
try
{
rv = list.get(index);
}
catch(ArrayIndexOutOfBoundsException e)
{
// return null
}
return rv;
}
public Object getPropertyValue(String name)
{
return getPropertyValue(name, 0);
}
/**
* Access a particular value in a Structured Artifact, as identified by the parameter "name". This
* implementation of the method assumes that the name is a series of String identifiers delimited
* by the ResourcesAction.ResourcesMetadata.DOT String.
* @param name The delimited identifier for the item.
* @return The value identified by the name, or null if the name does not identify a valid item.
*/
public Object getPropertyValue(String name, int index)
{
String[] names = name.split(ResourcesMetadata.DOT);
Object rv = null;
if(m_properties == null)
{
m_properties = new Vector();
}
Iterator it = m_properties.iterator();
while(rv == null && it.hasNext())
{
ResourcesMetadata prop = (ResourcesMetadata) it.next();
if(name.equals(prop.getDottedname()))
{
rv = prop.getValue(index);
}
}
return rv;
}
public void setPropertyValue(String name, Object value)
{
setPropertyValue(name, 0, value);
}
/**
* Access a particular value in a Structured Artifact, as identified by the parameter "name". This
* implementation of the method assumes that the name is a series of String identifiers delimited
* by the ResourcesAction.ResourcesMetadata.DOT String.
* @param name The delimited identifier for the item.
* @return The value identified by the name, or null if the name does not identify a valid item.
*/
public void setPropertyValue(String name, int index, Object value)
{
if(m_properties == null)
{
m_properties = new Vector();
}
boolean found = false;
Iterator it = m_properties.iterator();
while(!found && it.hasNext())
{
ResourcesMetadata prop = (ResourcesMetadata) it.next();
if(name.equals(prop.getDottedname()))
{
found = true;
prop.setValue(index, value);
}
}
}
/**
* Access a particular value in a Structured Artifact, as identified by the parameter "name". This
* implementation of the method assumes that the name is a series of String identifiers delimited
* by the ResourcesAction.ResourcesMetadata.DOT String.
* @param name The delimited identifier for the item.
* @return The value identified by the name, or null if the name does not identify a valid item.
*/
public Object getValue(String name)
{
String[] names = name.split(ResourcesMetadata.DOT);
Object rv = m_structuredArtifact;
if(rv != null && (rv instanceof Map) && ((Map) rv).isEmpty())
{
rv = null;
}
for(int i = 1; rv != null && i < names.length; i++)
{
if(rv instanceof Map)
{
rv = ((Map) rv).get(names[i]);
}
else
{
rv = null;
}
}
return rv;
}
/**
* Access a list of values associated with a named property of a structured artifact.
* @param name The name of the property.
* @return The list of values associated with that name, or an empty list if the property is not defined.
*/
public List getList(String name)
{
if(m_structuredArtifact == null)
{
m_structuredArtifact = new Hashtable();
}
Object value = m_structuredArtifact.get(name);
List rv = new Vector();
if(value == null)
{
m_structuredArtifact.put(name, rv);
}
else if(value instanceof Collection)
{
rv.addAll((Collection)value);
}
else
{
rv.add(value);
}
return rv;
}
/**
* @return
*/
/*
public Element exportStructuredArtifact(List properties)
{
return null;
}
*/
/**
* @return Returns the name of the root of a structured artifact definition.
*/
public String getRootname()
{
return m_rootname;
}
/**
* @param rootname The name to be assigned for the root of a structured artifact.
*/
public void setRootname(String rootname)
{
m_rootname = rootname;
}
/**
* Add a property name to the list of properties missing from the input.
* @param propname The name of the property.
*/
public void setMissing(String propname)
{
m_missingInformation.add(propname);
}
/**
* Query whether a particular property is missing
* @param propname The name of the property
* @return The value "true" if the property is missing, "false" otherwise.
*/
public boolean isMissing(String propname)
{
return m_missingInformation.contains(propname) || m_missingInformation.contains(Validator.escapeUrl(propname));
}
/**
* Empty the list of missing properties.
*/
public void clearMissing()
{
m_missingInformation.clear();
}
public void setAdded(boolean added)
{
m_hasBeenAdded = added;
}
public boolean hasBeenAdded()
{
return m_hasBeenAdded;
}
} // inner class EditItem
/**
* Inner class encapsulates information about folders (and final item?) in a collection path (a.k.a. breadcrumb)
*/
public static class PathItem
{
protected String m_url;
protected String m_name;
protected String m_id;
protected boolean m_canRead;
protected boolean m_isFolder;
protected boolean m_isLast;
protected String m_root;
protected boolean m_isLocal;
public PathItem(String id, String name)
{
m_id = id;
m_name = name;
m_canRead = false;
m_isFolder = false;
m_isLast = false;
m_url = "";
m_isLocal = true;
}
/**
* @return
*/
public boolean canRead()
{
return m_canRead;
}
/**
* @return
*/
public String getId()
{
return m_id;
}
/**
* @return
*/
public boolean isFolder()
{
return m_isFolder;
}
/**
* @return
*/
public boolean isLast()
{
return m_isLast;
}
/**
* @return
*/
public String getName()
{
return m_name;
}
/**
* @param canRead
*/
public void setCanRead(boolean canRead)
{
m_canRead = canRead;
}
/**
* @param id
*/
public void setId(String id)
{
m_id = id;
}
/**
* @param isFolder
*/
public void setIsFolder(boolean isFolder)
{
m_isFolder = isFolder;
}
/**
* @param isLast
*/
public void setLast(boolean isLast)
{
m_isLast = isLast;
}
/**
* @param name
*/
public void setName(String name)
{
m_name = name;
}
/**
* @return
*/
public String getUrl()
{
return m_url;
}
/**
* @param url
*/
public void setUrl(String url)
{
m_url = url;
}
/**
* @param root
*/
public void setRoot(String root)
{
m_root = root;
}
/**
* @return
*/
public String getRoot()
{
return m_root;
}
public void setIsLocal(boolean isLocal)
{
m_isLocal = isLocal;
}
public boolean isLocal()
{
return m_isLocal;
}
} // inner class PathItem
/**
*
* inner class encapsulates information about groups of metadata tags (such as DC, LOM, etc.)
*
*/
public static class MetadataGroup
extends Vector
{
/**
*
*/
private static final long serialVersionUID = -821054142728929236L;
protected String m_name;
protected boolean m_isShowing;
/**
* @param name
*/
public MetadataGroup(String name)
{
super();
m_name = name;
m_isShowing = false;
}
/**
* @return
*/
public boolean isShowing()
{
return m_isShowing;
}
/**
* @param isShowing
*/
public void setShowing(boolean isShowing)
{
m_isShowing = isShowing;
}
/**
* @return
*/
public String getName()
{
return m_name;
}
/**
* @param name
*/
public void setName(String name)
{
m_name = name;
}
/* (non-Javadoc)
* @see java.lang.Object#equals(java.lang.Object)
* needed to determine List.contains()
*/
public boolean equals(Object obj)
{
MetadataGroup mg = (MetadataGroup) obj;
boolean rv = (obj != null) && (m_name.equals(mg));
return rv;
}
}
public static class AttachItem
{
protected String m_id;
protected String m_displayName;
protected String m_accessUrl;
protected String m_collectionId;
protected String m_contentType;
/**
* @param id
* @param displayName
* @param collectionId
* @param accessUrl
*/
public AttachItem(String id, String displayName, String collectionId, String accessUrl)
{
m_id = id;
m_displayName = displayName;
m_collectionId = collectionId;
m_accessUrl = accessUrl;
}
/**
* @return Returns the accessUrl.
*/
public String getAccessUrl()
{
return m_accessUrl;
}
/**
* @param accessUrl The accessUrl to set.
*/
public void setAccessUrl(String accessUrl)
{
m_accessUrl = accessUrl;
}
/**
* @return Returns the collectionId.
*/
public String getCollectionId()
{
return m_collectionId;
}
/**
* @param collectionId The collectionId to set.
*/
public void setCollectionId(String collectionId)
{
m_collectionId = collectionId;
}
/**
* @return Returns the id.
*/
public String getId()
{
return m_id;
}
/**
* @param id The id to set.
*/
public void setId(String id)
{
m_id = id;
}
/**
* @return Returns the name.
*/
public String getDisplayName()
{
String displayName = m_displayName;
if(displayName == null || displayName.trim().equals(""))
{
displayName = isolateName(m_id);
}
return displayName;
}
/**
* @param name The name to set.
*/
public void setDisplayName(String name)
{
m_displayName = name;
}
/**
* @return Returns the contentType.
*/
public String getContentType()
{
return m_contentType;
}
/**
* @param contentType
*/
public void setContentType(String contentType)
{
this.m_contentType = contentType;
}
} // Inner class AttachItem
public static class ElementCarrier
{
protected Element element;
protected String parent;
public ElementCarrier(Element element, String parent)
{
this.element = element;
this.parent = parent;
}
public Element getElement()
{
return element;
}
public void setElement(Element element)
{
this.element = element;
}
public String getParent()
{
return parent;
}
public void setParent(String parent)
{
this.parent = parent;
}
}
public static class SaveArtifactAttempt
{
protected EditItem item;
protected List errors;
protected SchemaNode schema;
public SaveArtifactAttempt(EditItem item, SchemaNode schema)
{
this.item = item;
this.schema = schema;
}
/**
* @return Returns the errors.
*/
public List getErrors()
{
return errors;
}
/**
* @param errors The errors to set.
*/
public void setErrors(List errors)
{
this.errors = errors;
}
/**
* @return Returns the item.
*/
public EditItem getItem()
{
return item;
}
/**
* @param item The item to set.
*/
public void setItem(EditItem item)
{
this.item = item;
}
/**
* @return Returns the schema.
*/
public SchemaNode getSchema()
{
return schema;
}
/**
* @param schema The schema to set.
*/
public void setSchema(SchemaNode schema)
{
this.schema = schema;
}
}
/**
* Develop a list of all the site collections that there are to page.
* Sort them as appropriate, and apply search criteria.
*/
protected static List readAllResources(SessionState state)
{
List other_sites = new Vector();
String collectionId = (String) state.getAttribute (STATE_ATTACH_COLLECTION_ID);
if(collectionId == null)
{
collectionId = (String) state.getAttribute (STATE_COLLECTION_ID);
}
HashMap expandedCollections = (HashMap) state.getAttribute(STATE_EXPANDED_COLLECTIONS);
// set the sort values
String sortedBy = (String) state.getAttribute (STATE_SORT_BY);
String sortedAsc = (String) state.getAttribute (STATE_SORT_ASC);
Boolean showRemove = (Boolean) state.getAttribute(STATE_SHOW_REMOVE_ACTION);
boolean showRemoveAction = showRemove != null && showRemove.booleanValue();
Boolean showMove = (Boolean) state.getAttribute(STATE_SHOW_MOVE_ACTION);
boolean showMoveAction = showMove != null && showMove.booleanValue();
Boolean showCopy = (Boolean) state.getAttribute(STATE_SHOW_COPY_ACTION);
boolean showCopyAction = showCopy != null && showCopy.booleanValue();
Set highlightedItems = (Set) state.getAttribute(STATE_HIGHLIGHTED_ITEMS);
// add user's personal workspace
User user = UserDirectoryService.getCurrentUser();
String userId = user.getId();
String userName = user.getDisplayName();
String wsId = SiteService.getUserSiteId(userId);
String wsCollectionId = ContentHostingService.getSiteCollection(wsId);
if(! collectionId.equals(wsCollectionId))
{
List members = getBrowseItems(wsCollectionId, expandedCollections, highlightedItems, sortedBy, sortedAsc, (BrowseItem) null, false, state);
if(members != null && members.size() > 0)
{
BrowseItem root = (BrowseItem) members.remove(0);
showRemoveAction = showRemoveAction || root.hasDeletableChildren();
showMoveAction = showMoveAction || root.hasDeletableChildren();
showCopyAction = showCopyAction || root.hasCopyableChildren();
root.addMembers(members);
root.setName(userName + " " + rb.getString("gen.wsreso"));
other_sites.add(root);
}
}
// add all other sites user has access to
/*
* NOTE: This does not (and should not) get all sites for admin.
* Getting all sites for admin is too big a request and
* would result in too big a display to render in html.
*/
Map othersites = ContentHostingService.getCollectionMap();
Iterator siteIt = othersites.keySet().iterator();
SortedSet sort = new TreeSet();
while(siteIt.hasNext())
{
String collId = (String) siteIt.next();
String displayName = (String) othersites.get(collId);
sort.add(displayName + DELIM + collId);
}
Iterator sortIt = sort.iterator();
while(sortIt.hasNext())
{
String item = (String) sortIt.next();
String displayName = item.substring(0, item.lastIndexOf(DELIM));
String collId = item.substring(item.lastIndexOf(DELIM) + 1);
if(! collectionId.equals(collId) && ! wsCollectionId.equals(collId))
{
List members = getBrowseItems(collId, expandedCollections, highlightedItems, sortedBy, sortedAsc, (BrowseItem) null, false, state);
if(members != null && members.size() > 0)
{
BrowseItem root = (BrowseItem) members.remove(0);
root.addMembers(members);
root.setName(displayName);
other_sites.add(root);
}
}
}
return other_sites;
}
/**
* Prepare the current page of site collections to display.
* @return List of BrowseItem objects to display on this page.
*/
protected static List prepPage(SessionState state)
{
List rv = new Vector();
// access the page size
int pageSize = ((Integer) state.getAttribute(STATE_PAGESIZE)).intValue();
// cleanup prior prep
state.removeAttribute(STATE_NUM_MESSAGES);
// are we going next or prev, first or last page?
boolean goNextPage = state.getAttribute(STATE_GO_NEXT_PAGE) != null;
boolean goPrevPage = state.getAttribute(STATE_GO_PREV_PAGE) != null;
boolean goFirstPage = state.getAttribute(STATE_GO_FIRST_PAGE) != null;
boolean goLastPage = state.getAttribute(STATE_GO_LAST_PAGE) != null;
state.removeAttribute(STATE_GO_NEXT_PAGE);
state.removeAttribute(STATE_GO_PREV_PAGE);
state.removeAttribute(STATE_GO_FIRST_PAGE);
state.removeAttribute(STATE_GO_LAST_PAGE);
// are we going next or prev message?
boolean goNext = state.getAttribute(STATE_GO_NEXT) != null;
boolean goPrev = state.getAttribute(STATE_GO_PREV) != null;
state.removeAttribute(STATE_GO_NEXT);
state.removeAttribute(STATE_GO_PREV);
// read all channel messages
List allMessages = readAllResources(state);
if (allMessages == null)
{
return rv;
}
String messageIdAtTheTopOfThePage = null;
Object topMsgId = state.getAttribute(STATE_TOP_PAGE_MESSAGE);
if(topMsgId == null)
{
// do nothing
}
else if(topMsgId instanceof Integer)
{
messageIdAtTheTopOfThePage = ((Integer) topMsgId).toString();
}
else if(topMsgId instanceof String)
{
messageIdAtTheTopOfThePage = (String) topMsgId;
}
// if we have no prev page and do have a top message, then we will stay "pinned" to the top
boolean pinToTop = ( (messageIdAtTheTopOfThePage != null)
&& (state.getAttribute(STATE_PREV_PAGE_EXISTS) == null)
&& !goNextPage && !goPrevPage && !goNext && !goPrev && !goFirstPage && !goLastPage);
// if we have no next page and do have a top message, then we will stay "pinned" to the bottom
boolean pinToBottom = ( (messageIdAtTheTopOfThePage != null)
&& (state.getAttribute(STATE_NEXT_PAGE_EXISTS) == null)
&& !goNextPage && !goPrevPage && !goNext && !goPrev && !goFirstPage && !goLastPage);
// how many messages, total
int numMessages = allMessages.size();
if (numMessages == 0)
{
return rv;
}
// save the number of messges
state.setAttribute(STATE_NUM_MESSAGES, new Integer(numMessages));
// find the position of the message that is the top first on the page
int posStart = 0;
if (messageIdAtTheTopOfThePage != null)
{
// find the next page
posStart = findResourceInList(allMessages, messageIdAtTheTopOfThePage);
// if missing, start at the top
if (posStart == -1)
{
posStart = 0;
}
}
// if going to the next page, adjust
if (goNextPage)
{
posStart += pageSize;
}
// if going to the prev page, adjust
else if (goPrevPage)
{
posStart -= pageSize;
if (posStart < 0) posStart = 0;
}
// if going to the first page, adjust
else if (goFirstPage)
{
posStart = 0;
}
// if going to the last page, adjust
else if (goLastPage)
{
posStart = numMessages - pageSize;
if (posStart < 0) posStart = 0;
}
// pinning
if (pinToTop)
{
posStart = 0;
}
else if (pinToBottom)
{
posStart = numMessages - pageSize;
if (posStart < 0) posStart = 0;
}
// get the last page fully displayed
if (posStart + pageSize > numMessages)
{
posStart = numMessages - pageSize;
if (posStart < 0) posStart = 0;
}
// compute the end to a page size, adjusted for the number of messages available
int posEnd = posStart + (pageSize-1);
if (posEnd >= numMessages) posEnd = numMessages-1;
int numMessagesOnThisPage = (posEnd - posStart) + 1;
// select the messages on this page
for (int i = posStart; i <= posEnd; i++)
{
rv.add(allMessages.get(i));
}
// save which message is at the top of the page
BrowseItem itemAtTheTopOfThePage = (BrowseItem) allMessages.get(posStart);
state.setAttribute(STATE_TOP_PAGE_MESSAGE, itemAtTheTopOfThePage.getId());
state.setAttribute(STATE_TOP_MESSAGE_INDEX, new Integer(posStart));
// which message starts the next page (if any)
int next = posStart + pageSize;
if (next < numMessages)
{
state.setAttribute(STATE_NEXT_PAGE_EXISTS, "");
}
else
{
state.removeAttribute(STATE_NEXT_PAGE_EXISTS);
}
// which message ends the prior page (if any)
int prev = posStart - 1;
if (prev >= 0)
{
state.setAttribute(STATE_PREV_PAGE_EXISTS, "");
}
else
{
state.removeAttribute(STATE_PREV_PAGE_EXISTS);
}
if (state.getAttribute(STATE_VIEW_ID) != null)
{
int viewPos = findResourceInList(allMessages, (String) state.getAttribute(STATE_VIEW_ID));
// are we moving to the next message
if (goNext)
{
// advance
viewPos++;
if (viewPos >= numMessages) viewPos = numMessages-1;
}
// are we moving to the prev message
if (goPrev)
{
// retreat
viewPos--;
if (viewPos < 0) viewPos = 0;
}
// update the view message
state.setAttribute(STATE_VIEW_ID, ((BrowseItem) allMessages.get(viewPos)).getId());
// if the view message is no longer on the current page, adjust the page
// Note: next time through this will get processed
if (viewPos < posStart)
{
state.setAttribute(STATE_GO_PREV_PAGE, "");
}
else if (viewPos > posEnd)
{
state.setAttribute(STATE_GO_NEXT_PAGE, "");
}
if (viewPos > 0)
{
state.setAttribute(STATE_PREV_EXISTS,"");
}
else
{
state.removeAttribute(STATE_PREV_EXISTS);
}
if (viewPos < numMessages-1)
{
state.setAttribute(STATE_NEXT_EXISTS,"");
}
else
{
state.removeAttribute(STATE_NEXT_EXISTS);
}
}
return rv;
} // prepPage
/**
* Find the resource with this id in the list.
* @param messages The list of messages.
* @param id The message id.
* @return The index position in the list of the message with this id, or -1 if not found.
*/
protected static int findResourceInList(List resources, String id)
{
for (int i = 0; i < resources.size(); i++)
{
// if this is the one, return this index
if (((BrowseItem) (resources.get(i))).getId().equals(id)) return i;
}
// not found
return -1;
} // findResourceInList
protected static User getUserProperty(ResourceProperties props, String name)
{
String id = props.getProperty(name);
if (id != null)
{
try
{
return UserDirectoryService.getUser(id);
}
catch (UserNotDefinedException e)
{
}
}
return null;
}
/**
* Find the resource name of a given resource id or filepath.
*
* @param id
* The resource id.
* @return the resource name.
*/
protected static String isolateName(String id)
{
if (id == null) return null;
if (id.length() == 0) return null;
// take after the last resource path separator, not counting one at the very end if there
boolean lastIsSeparator = id.charAt(id.length() - 1) == '/';
return id.substring(id.lastIndexOf('/', id.length() - 2) + 1, (lastIsSeparator ? id.length() - 1 : id.length()));
} // isolateName
} // ResourcesAction
| true | true | public void doHandlepaste ( RunData data)
{
ParameterParser params = data.getParameters ();
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
// get the cut items to be pasted
Vector pasteCutItems = (Vector) state.getAttribute (STATE_CUT_IDS);
// get the copied items to be pasted
Vector pasteCopiedItems = (Vector) state.getAttribute (STATE_COPIED_IDS);
String collectionId = params.getString ("collectionId");
String originalDisplayName = NULL_STRING;
// handle cut and paste
if (((String) state.getAttribute (STATE_CUT_FLAG)).equals (Boolean.TRUE.toString()))
{
for (int i = 0; i < pasteCutItems.size (); i++)
{
String currentPasteCutItem = (String) pasteCutItems.get (i);
try
{
ResourceProperties properties = ContentHostingService.getProperties (currentPasteCutItem);
originalDisplayName = properties.getPropertyFormatted (ResourceProperties.PROP_DISPLAY_NAME);
/*
if (Boolean.TRUE.toString().equals(properties.getProperty (ResourceProperties.PROP_IS_COLLECTION)))
{
String alert = (String) state.getAttribute(STATE_MESSAGE);
if (alert == null || ((alert != null) && (alert.indexOf(RESOURCE_INVALID_OPERATION_ON_COLLECTION_STRING) == -1)))
{
addAlert(state, RESOURCE_INVALID_OPERATION_ON_COLLECTION_STRING);
}
}
else
{
*/
// paste the resource
ContentResource resource = ContentHostingService.getResource (currentPasteCutItem);
ResourceProperties p = ContentHostingService.getProperties(currentPasteCutItem);
String id = collectionId + Validator.escapeResourceName(p.getProperty(ResourceProperties.PROP_DISPLAY_NAME));
// cut-paste to the same collection?
boolean cutPasteSameCollection = false;
String displayName = p.getProperty(ResourceProperties.PROP_DISPLAY_NAME);
// till paste successfully or it fails
ResourcePropertiesEdit resourceProperties = ContentHostingService.newResourceProperties ();
// add the properties of the pasted item
Iterator propertyNames = properties.getPropertyNames ();
while ( propertyNames.hasNext ())
{
String propertyName = (String) propertyNames.next ();
if (!properties.isLiveProperty (propertyName))
{
if (propertyName.equals (ResourceProperties.PROP_DISPLAY_NAME)&&(displayName.length ()>0))
{
resourceProperties.addProperty (propertyName, displayName);
}
else
{
resourceProperties.addProperty (propertyName, properties.getProperty (propertyName));
} // if-else
} // if
} // while
try
{
// paste the cutted resource to the new collection - no notification
ContentResource newResource = ContentHostingService.addResource (id, resource.getContentType (), resource.getContent (), resourceProperties, NotificationService.NOTI_NONE);
String uuid = ContentHostingService.getUuid(resource.getId());
ContentHostingService.setUuid(id, uuid);
}
catch (InconsistentException e)
{
addAlert(state,RESOURCE_INVALID_TITLE_STRING);
}
catch (OverQuotaException e)
{
addAlert(state, rb.getString("overquota"));
}
catch (IdInvalidException e)
{
addAlert(state, rb.getString("title") + " " + e.getMessage ());
}
catch(ServerOverloadException e)
{
// this represents temporary unavailability of server's filesystem
// for server configured to save resource body in filesystem
addAlert(state, rb.getString("failed"));
}
catch (IdUsedException e)
{
// cut and paste to the same collection; stop adding new resource
if (id.equals(currentPasteCutItem))
{
cutPasteSameCollection = true;
}
else
{
addAlert(state, rb.getString("notaddreso") + " " + id + rb.getString("used2"));
/*
// pasted to the same folder as before; add "Copy of "/ "copy (n) of" to the id
if (countNumber==1)
{
displayName = DUPLICATE_STRING + p.getProperty(ResourceProperties.PROP_DISPLAY_NAME);
id = collectionId + Validator.escapeResourceName(displayName);
}
else
{
displayName = "Copy (" + countNumber + ") of " + p.getProperty(ResourceProperties.PROP_DISPLAY_NAME);
id = collectionId + Validator.escapeResourceName(displayName);
}
countNumber++;
*/
}
} // try-catch
catch(RuntimeException e)
{
logger.error("ResourcesAction.doHandlepaste ***** Unknown Exception ***** " + e.getMessage());
addAlert(state, rb.getString("failed"));
}
if (!cutPasteSameCollection)
{
// remove the cutted resource
ContentHostingService.removeResource (currentPasteCutItem);
}
// } // if-else
}
catch (InUseException e)
{
addAlert(state, rb.getString("someone") + " " + originalDisplayName + ". ");
}
catch (PermissionException e)
{
addAlert(state, rb.getString("notpermis7") + " " + originalDisplayName + ". ");
}
catch (IdUnusedException e)
{
addAlert(state,RESOURCE_NOT_EXIST_STRING);
}
catch (TypeException e)
{
addAlert(state, rb.getString("pasteitem") + " " + originalDisplayName + " " + rb.getString("mismatch"));
} // try-catch
catch(RuntimeException e)
{
logger.error("ResourcesAction.doHandlepaste ***** Unknown Exception ***** " + e.getMessage());
addAlert(state, rb.getString("failed"));
}
} // for
} // cut
// handling copy and paste
if (Boolean.toString(true).equalsIgnoreCase((String) state.getAttribute (STATE_COPY_FLAG)))
{
for (int i = 0; i < pasteCopiedItems.size (); i++)
{
String currentPasteCopiedItem = (String) pasteCopiedItems.get (i);
try
{
ResourceProperties properties = ContentHostingService.getProperties (currentPasteCopiedItem);
originalDisplayName = properties.getPropertyFormatted (ResourceProperties.PROP_DISPLAY_NAME);
// copy, cut and paste not operated on collections
if (properties.getProperty (ResourceProperties.PROP_IS_COLLECTION).equals (Boolean.TRUE.toString()))
{
String alert = (String) state.getAttribute(STATE_MESSAGE);
if (alert == null || ((alert != null) && (alert.indexOf(RESOURCE_INVALID_OPERATION_ON_COLLECTION_STRING) == -1)))
{
addAlert(state, RESOURCE_INVALID_OPERATION_ON_COLLECTION_STRING);
}
}
else
{
// paste the resource
ContentResource resource = ContentHostingService.getResource (currentPasteCopiedItem);
ResourceProperties p = ContentHostingService.getProperties(currentPasteCopiedItem);
String displayName = DUPLICATE_STRING + p.getProperty(ResourceProperties.PROP_DISPLAY_NAME);
String id = collectionId + Validator.escapeResourceName(displayName);
ResourcePropertiesEdit resourceProperties = ContentHostingService.newResourceProperties ();
// add the properties of the pasted item
Iterator propertyNames = properties.getPropertyNames ();
while ( propertyNames.hasNext ())
{
String propertyName = (String) propertyNames.next ();
if (!properties.isLiveProperty (propertyName))
{
if (propertyName.equals (ResourceProperties.PROP_DISPLAY_NAME)&&(displayName.length ()>0))
{
resourceProperties.addProperty (propertyName, displayName);
}
else
{
resourceProperties.addProperty (propertyName, properties.getProperty (propertyName));
}
}
}
try
{
// paste the copied resource to the new collection
ContentResource newResource = ContentHostingService.addResource (id, resource.getContentType (), resource.getContent (), resourceProperties, NotificationService.NOTI_NONE);
}
catch (InconsistentException e)
{
addAlert(state,RESOURCE_INVALID_TITLE_STRING);
}
catch (IdInvalidException e)
{
addAlert(state,rb.getString("title") + " " + e.getMessage ());
}
catch (OverQuotaException e)
{
addAlert(state, rb.getString("overquota"));
}
catch (ServerOverloadException e)
{
addAlert(state, rb.getString("failed"));
}
catch (IdUsedException e)
{
addAlert(state, rb.getString("notaddreso") + " " + id + rb.getString("used2"));
/*
// copying
// pasted to the same folder as before; add "Copy of " to the id
if (countNumber > 1)
{
displayName = "Copy (" + countNumber + ") of " + p.getProperty(ResourceProperties.PROP_DISPLAY_NAME);
}
else if (countNumber == 1)
{
displayName = "Copy of " + p.getProperty(ResourceProperties.PROP_DISPLAY_NAME);
}
id = collectionId + Validator.escapeResourceName(displayName);
countNumber++;
*/
} // try-catch
catch(RuntimeException e)
{
logger.error("ResourcesAction.doHandlepaste ***** Unknown Exception ***** " + e.getMessage());
addAlert(state, rb.getString("failed"));
}
} // if-else
}
catch (PermissionException e)
{
addAlert(state, rb.getString("notpermis8") + " " + originalDisplayName + ". ");
}
catch (IdUnusedException e)
{
addAlert(state,RESOURCE_NOT_EXIST_STRING);
}
catch (TypeException e)
{
addAlert(state, rb.getString("pasteitem") + " " + originalDisplayName + " " + rb.getString("mismatch"));
} // try-catch
} // for
} // copy
if (state.getAttribute(STATE_MESSAGE) == null)
{
// delete sucessful
state.setAttribute (STATE_MODE, MODE_LIST);
// reset the cut flag
if (((String)state.getAttribute (STATE_CUT_FLAG)).equals (Boolean.TRUE.toString()))
{
state.setAttribute (STATE_CUT_FLAG, Boolean.FALSE.toString());
}
// reset the copy flag
if (Boolean.toString(true).equalsIgnoreCase((String)state.getAttribute (STATE_COPY_FLAG)))
{
state.setAttribute (STATE_COPY_FLAG, Boolean.FALSE.toString());
}
// try to expand the collection
HashMap expandedCollections = (HashMap) state.getAttribute(STATE_EXPANDED_COLLECTIONS);
if(! expandedCollections.containsKey(collectionId))
{
org.sakaiproject.content.api.ContentHostingService contentService = (org.sakaiproject.content.api.ContentHostingService) state.getAttribute (STATE_CONTENT_SERVICE);
try
{
ContentCollection coll = contentService.getCollection(collectionId);
expandedCollections.put(collectionId, coll);
}
catch(Exception ignore){}
}
}
} // doHandlepaste
/**
* Paste the shortcut(s) of previously copied item(s)
*/
public void doHandlepasteshortcut ( RunData data)
{
ParameterParser params = data.getParameters ();
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
// get the items to be pasted
Vector pasteItems = new Vector ();
if (((String) state.getAttribute (STATE_COPY_FLAG)).equals (Boolean.TRUE.toString()))
{
pasteItems = (Vector) ( (Vector) state.getAttribute (STATE_COPIED_IDS)).clone ();
}
if (((String) state.getAttribute (STATE_CUT_FLAG)).equals (Boolean.TRUE.toString()))
{
addAlert(state, rb.getString("choosecp"));
}
if (state.getAttribute(STATE_MESSAGE) == null)
{
String collectionId = params.getString ("collectionId");
String originalDisplayName = NULL_STRING;
for (int i = 0; i < pasteItems.size (); i++)
{
String currentPasteItem = (String) pasteItems.get (i);
try
{
ResourceProperties properties = ContentHostingService.getProperties (currentPasteItem);
originalDisplayName = properties.getPropertyFormatted (ResourceProperties.PROP_DISPLAY_NAME);
if (properties.getProperty (ResourceProperties.PROP_IS_COLLECTION).equals (Boolean.TRUE.toString()))
{
// paste the collection
}
else
{
// paste the resource
ContentResource resource = ContentHostingService.getResource (currentPasteItem);
ResourceProperties p = ContentHostingService.getProperties(currentPasteItem);
String displayName = SHORTCUT_STRING + p.getProperty(ResourceProperties.PROP_DISPLAY_NAME);
String id = collectionId + Validator.escapeResourceName(displayName);
//int countNumber = 2;
ResourcePropertiesEdit resourceProperties = ContentHostingService.newResourceProperties ();
// add the properties of the pasted item
Iterator propertyNames = properties.getPropertyNames ();
while ( propertyNames.hasNext ())
{
String propertyName = (String) propertyNames.next ();
if ((!properties.isLiveProperty (propertyName)) && (!propertyName.equals (ResourceProperties.PROP_DISPLAY_NAME)))
{
resourceProperties.addProperty (propertyName, properties.getProperty (propertyName));
}
}
// %%%%% should be _blank for items that can be displayed in browser, _self for others
// resourceProperties.addProperty (ResourceProperties.PROP_OPEN_NEWWINDOW, "_self");
resourceProperties.addProperty (ResourceProperties.PROP_DISPLAY_NAME, displayName);
try
{
ContentResource referedResource= ContentHostingService.getResource (currentPasteItem);
ContentResource newResource = ContentHostingService.addResource (id, ResourceProperties.TYPE_URL, referedResource.getUrl().getBytes (), resourceProperties, NotificationService.NOTI_NONE);
}
catch (InconsistentException e)
{
addAlert(state, RESOURCE_INVALID_TITLE_STRING);
}
catch (OverQuotaException e)
{
addAlert(state, rb.getString("overquota"));
}
catch (IdInvalidException e)
{
addAlert(state, rb.getString("title") + " " + e.getMessage ());
}
catch (ServerOverloadException e)
{
addAlert(state, rb.getString("failed"));
}
catch (IdUsedException e)
{
addAlert(state, rb.getString("notaddreso") + " " + id + rb.getString("used2"));
/*
// pasted shortcut to the same folder as before; add countNumber to the id
displayName = "Shortcut (" + countNumber + ") to " + p.getProperty(ResourceProperties.PROP_DISPLAY_NAME);
id = collectionId + Validator.escapeResourceName(displayName);
countNumber++;
*/
} // try-catch
catch(RuntimeException e)
{
logger.error("ResourcesAction.doHandlepasteshortcut ***** Unknown Exception ***** " + e.getMessage());
addAlert(state, rb.getString("failed"));
}
} // if-else
}
catch (PermissionException e)
{
addAlert(state, rb.getString("notpermis9") + " " + currentPasteItem.substring (currentPasteItem.lastIndexOf (Entity.SEPARATOR)+1) + ". ");
}
catch (IdUnusedException e)
{
addAlert(state,RESOURCE_NOT_EXIST_STRING);
}
catch (TypeException e)
{
addAlert(state, rb.getString("pasteitem") + " " + currentPasteItem.substring (currentPasteItem.lastIndexOf (Entity.SEPARATOR)+1) + " " + rb.getString("mismatch"));
} // try-catch
} // for
}
if (state.getAttribute(STATE_MESSAGE) == null)
{
if (((String) state.getAttribute (STATE_COPY_FLAG)).equals (Boolean.TRUE.toString()))
{
// reset the copy flag
state.setAttribute (STATE_COPY_FLAG, Boolean.FALSE.toString());
}
// paste shortcut sucessful
state.setAttribute (STATE_MODE, MODE_LIST);
}
} // doHandlepasteshortcut
/**
* Edit the editable collection/resource properties
*/
public static void doEdit ( RunData data )
{
ParameterParser params = data.getParameters ();
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
Map current_stack_frame = pushOnStack(state);
state.setAttribute(STATE_LIST_SELECTIONS, new TreeSet());
// cancel copy if there is one in progress
if(! Boolean.FALSE.toString().equals(state.getAttribute (STATE_COPY_FLAG)))
{
initCopyContext(state);
}
// cancel move if there is one in progress
if(! Boolean.FALSE.toString().equals(state.getAttribute (STATE_MOVE_FLAG)))
{
initMoveContext(state);
}
String id = NULL_STRING;
id = params.getString ("id");
if(id == null || id.length() == 0)
{
// there is no resource selected, show the alert message to the user
addAlert(state, rb.getString("choosefile2"));
return;
}
current_stack_frame.put(STATE_STACK_EDIT_ID, id);
String collectionId = (String) params.getString("collectionId");
if(collectionId == null)
{
collectionId = ContentHostingService.getSiteCollection(ToolManager.getCurrentPlacement().getContext());
state.setAttribute(STATE_HOME_COLLECTION_ID, collectionId);
}
current_stack_frame.put(STATE_STACK_EDIT_COLLECTION_ID, collectionId);
EditItem item = getEditItem(id, collectionId, data);
if (state.getAttribute(STATE_MESSAGE) == null)
{
// got resource and sucessfully populated item with values
// state.setAttribute (STATE_MODE, MODE_EDIT);
state.setAttribute(ResourcesAction.STATE_RESOURCES_HELPER_MODE, ResourcesAction.MODE_ATTACHMENT_EDIT_ITEM_INIT);
state.setAttribute(STATE_EDIT_ALERTS, new HashSet());
current_stack_frame.put(STATE_STACK_EDIT_ITEM, item);
}
else
{
popFromStack(state);
}
} // doEdit
public static EditItem getEditItem(String id, String collectionId, RunData data)
{
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
Stack operations_stack = (Stack) state.getAttribute(STATE_SUSPENDED_OPERATIONS_STACK);
Map current_stack_frame = peekAtStack(state);
EditItem item = null;
// populate an EditItem object with values from the resource and return the EditItem
try
{
ResourceProperties properties = ContentHostingService.getProperties(id);
boolean isCollection = false;
try
{
isCollection = properties.getBooleanProperty(ResourceProperties.PROP_IS_COLLECTION);
}
catch(Exception e)
{
// assume isCollection is false if property is not set
}
ContentEntity entity = null;
String itemType = "";
byte[] content = null;
if(isCollection)
{
itemType = "folder";
entity = ContentHostingService.getCollection(id);
}
else
{
entity = ContentHostingService.getResource(id);
itemType = ((ContentResource) entity).getContentType();
content = ((ContentResource) entity).getContent();
}
String itemName = properties.getProperty(ResourceProperties.PROP_DISPLAY_NAME);
item = new EditItem(id, itemName, itemType);
BasicRightsAssignment rightsObj = new BasicRightsAssignment(item.getItemNum(), properties);
item.setRights(rightsObj);
String encoding = data.getRequest().getCharacterEncoding();
if(encoding != null)
{
item.setEncoding(encoding);
}
String defaultCopyrightStatus = (String) state.getAttribute(DEFAULT_COPYRIGHT);
if(defaultCopyrightStatus == null || defaultCopyrightStatus.trim().equals(""))
{
defaultCopyrightStatus = ServerConfigurationService.getString("default.copyright");
state.setAttribute(DEFAULT_COPYRIGHT, defaultCopyrightStatus);
}
item.setCopyrightStatus(defaultCopyrightStatus);
if(content != null)
{
item.setContent(content);
}
String dummyId = collectionId.trim();
if(dummyId.endsWith(Entity.SEPARATOR))
{
dummyId += "dummy";
}
else
{
dummyId += Entity.SEPARATOR + "dummy";
}
String containerId = ContentHostingService.getContainingCollectionId (id);
item.setContainer(containerId);
boolean canRead = ContentHostingService.allowGetCollection(id);
boolean canAddFolder = ContentHostingService.allowAddCollection(id);
boolean canAddItem = ContentHostingService.allowAddResource(id);
boolean canDelete = ContentHostingService.allowRemoveResource(id);
boolean canRevise = ContentHostingService.allowUpdateResource(id);
item.setCanRead(canRead);
item.setCanRevise(canRevise);
item.setCanAddItem(canAddItem);
item.setCanAddFolder(canAddFolder);
item.setCanDelete(canDelete);
// item.setIsUrl(isUrl);
AccessMode access = ((GroupAwareEntity) entity).getAccess();
if(access == null)
{
item.setAccess(AccessMode.INHERITED.toString());
}
else
{
item.setAccess(access.toString());
}
AccessMode inherited_access = ((GroupAwareEntity) entity).getInheritedAccess();
if(inherited_access == null || inherited_access.equals(AccessMode.SITE))
{
item.setInheritedAccess(AccessMode.INHERITED.toString());
}
else
{
item.setInheritedAccess(inherited_access.toString());
}
List access_groups = new Vector(((GroupAwareEntity) entity).getGroups());
if(access_groups != null)
{
Site site = SiteService.getSite(ToolManager.getCurrentPlacement().getContext());
Iterator it = access_groups.iterator();
while(it.hasNext())
{
String groupRef = (String) it.next();
Group group = site.getGroup(groupRef);
item.addGroup(group.getId());
}
}
List inherited_access_groups = new Vector(((GroupAwareEntity) entity).getInheritedGroups());
if(inherited_access_groups != null)
{
Site site = SiteService.getSite(ToolManager.getCurrentPlacement().getContext());
Iterator it = inherited_access_groups.iterator();
while(it.hasNext())
{
String groupRef = (String) it.next();
Group group = site.getGroup(groupRef);
item.addGroup(group.getId());
}
}
if(item.isUrl())
{
String url = new String(content);
item.setFilename(url);
}
else if(item.isStructuredArtifact())
{
String formtype = properties.getProperty(ResourceProperties.PROP_STRUCTOBJ_TYPE);
current_stack_frame.put(STATE_STACK_STRUCTOBJ_TYPE, formtype);
current_stack_frame.put(STATE_STACK_EDIT_ITEM, item);
setupStructuredObjects(state);
Document doc = Xml.readDocumentFromString(new String(content));
Element root = doc.getDocumentElement();
importStructuredArtifact(root, item.getForm());
List flatList = item.getForm().getFlatList();
item.setProperties(flatList);
}
else if(item.isHtml() || item.isPlaintext() || item.isFileUpload())
{
String filename = properties.getProperty(ResourceProperties.PROP_ORIGINAL_FILENAME);
if(filename == null)
{
// this is a hack to deal with the fact that original filenames were not saved for some time.
if(containerId != null && item.getId().startsWith(containerId) && containerId.length() < item.getId().length())
{
filename = item.getId().substring(containerId.length());
}
}
if(filename == null)
{
item.setFilename(itemName);
}
else
{
item.setFilename(filename);
}
}
String description = properties.getProperty(ResourceProperties.PROP_DESCRIPTION);
item.setDescription(description);
try
{
Time creTime = properties.getTimeProperty(ResourceProperties.PROP_CREATION_DATE);
String createdTime = creTime.toStringLocalShortDate() + " " + creTime.toStringLocalShort();
item.setCreatedTime(createdTime);
}
catch(Exception e)
{
String createdTime = properties.getProperty(ResourceProperties.PROP_CREATION_DATE);
item.setCreatedTime(createdTime);
}
try
{
String createdBy = getUserProperty(properties, ResourceProperties.PROP_CREATOR).getDisplayName();
item.setCreatedBy(createdBy);
}
catch(Exception e)
{
String createdBy = properties.getProperty(ResourceProperties.PROP_CREATOR);
item.setCreatedBy(createdBy);
}
try
{
Time modTime = properties.getTimeProperty(ResourceProperties.PROP_MODIFIED_DATE);
String modifiedTime = modTime.toStringLocalShortDate() + " " + modTime.toStringLocalShort();
item.setModifiedTime(modifiedTime);
}
catch(Exception e)
{
String modifiedTime = properties.getProperty(ResourceProperties.PROP_MODIFIED_DATE);
item.setModifiedTime(modifiedTime);
}
try
{
String modifiedBy = getUserProperty(properties, ResourceProperties.PROP_MODIFIED_BY).getDisplayName();
item.setModifiedBy(modifiedBy);
}
catch(Exception e)
{
String modifiedBy = properties.getProperty(ResourceProperties.PROP_MODIFIED_BY);
item.setModifiedBy(modifiedBy);
}
String url = ContentHostingService.getUrl(id);
item.setUrl(url);
String size = "";
if(properties.getProperty(ResourceProperties.PROP_CONTENT_LENGTH) != null)
{
size = properties.getPropertyFormatted(ResourceProperties.PROP_CONTENT_LENGTH) + " (" + Validator.getFileSizeWithDividor(properties.getProperty(ResourceProperties.PROP_CONTENT_LENGTH)) +" bytes)";
}
item.setSize(size);
String copyrightStatus = properties.getProperty(properties.getNamePropCopyrightChoice());
if(copyrightStatus == null || copyrightStatus.trim().equals(""))
{
copyrightStatus = (String) state.getAttribute(DEFAULT_COPYRIGHT);
}
item.setCopyrightStatus(copyrightStatus);
String copyrightInfo = properties.getPropertyFormatted(properties.getNamePropCopyright());
item.setCopyrightInfo(copyrightInfo);
String copyrightAlert = properties.getProperty(properties.getNamePropCopyrightAlert());
if("true".equalsIgnoreCase(copyrightAlert))
{
item.setCopyrightAlert(true);
}
else
{
item.setCopyrightAlert(false);
}
boolean pubviewset = ContentHostingService.isInheritingPubView(containerId) || ContentHostingService.isPubView(containerId);
item.setPubviewset(pubviewset);
boolean pubview = pubviewset;
if (!pubview)
{
pubview = ContentHostingService.isPubView(id);
}
item.setPubview(pubview);
Map metadata = new Hashtable();
List groups = (List) state.getAttribute(STATE_METADATA_GROUPS);
if(groups != null && ! groups.isEmpty())
{
Iterator it = groups.iterator();
while(it.hasNext())
{
MetadataGroup group = (MetadataGroup) it.next();
Iterator propIt = group.iterator();
while(propIt.hasNext())
{
ResourcesMetadata prop = (ResourcesMetadata) propIt.next();
String name = prop.getFullname();
String widget = prop.getWidget();
if(widget.equals(ResourcesMetadata.WIDGET_DATE) || widget.equals(ResourcesMetadata.WIDGET_DATETIME) || widget.equals(ResourcesMetadata.WIDGET_TIME))
{
Time time = TimeService.newTime();
try
{
time = properties.getTimeProperty(name);
}
catch(Exception ignore)
{
// use "now" as default in that case
}
metadata.put(name, time);
}
else
{
String value = properties.getPropertyFormatted(name);
metadata.put(name, value);
}
}
}
item.setMetadata(metadata);
}
else
{
item.setMetadata(new Hashtable());
}
// for collections only
if(item.isFolder())
{
// setup for quota - ADMIN only, site-root collection only
if (SecurityService.isSuperUser())
{
Reference ref = EntityManager.newReference(entity.getReference());
String context = ref.getContext();
String siteCollectionId = ContentHostingService.getSiteCollection(context);
if(siteCollectionId.equals(entity.getId()))
{
item.setCanSetQuota(true);
try
{
long quota = properties.getLongProperty(ResourceProperties.PROP_COLLECTION_BODY_QUOTA);
item.setHasQuota(true);
item.setQuota(Long.toString(quota));
}
catch (Exception any)
{
}
}
}
}
}
catch (IdUnusedException e)
{
addAlert(state, RESOURCE_NOT_EXIST_STRING);
}
catch (PermissionException e)
{
addAlert(state, rb.getString("notpermis2") + " " + id + ". " );
}
catch(TypeException e)
{
addAlert(state," " + rb.getString("typeex") + " " + id);
}
catch(ServerOverloadException e)
{
// this represents temporary unavailability of server's filesystem
// for server configured to save resource body in filesystem
addAlert(state, rb.getString("failed"));
}
catch(RuntimeException e)
{
logger.error("ResourcesAction.doEdit ***** Unknown Exception ***** " + e.getMessage());
addAlert(state, rb.getString("failed"));
}
return item;
}
/**
* This method updates the session state with information needed to create or modify
* structured artifacts in the resources tool. Among other things, it obtains a list
* of "forms" available to the user and places that list in state indexed as
* "STATE_STRUCTOBJ_HOMES". If the current formtype is known (in state indexed as
* "STATE_STACK_STRUCTOBJ_TYPE"), the list of properties associated with that form type is
* generated. If we are in a "create" context, the properties are added to each of
* the items in the list of items indexed as "STATE_STACK_CREATE_ITEMS". If we are in an
* "edit" context, the properties are added to the current item being edited (a state
* attribute indexed as "STATE_STACK_EDIT_ITEM"). The metaobj SchemaBean associated with
* the current form and its root SchemaNode object are also placed in state for later
* reference.
*/
public static void setupStructuredObjects(SessionState state)
{
Map current_stack_frame = peekAtStack(state);
String formtype = (String) current_stack_frame.get(STATE_STACK_STRUCTOBJ_TYPE);
if(formtype == null)
{
formtype = (String) state.getAttribute(STATE_STRUCTOBJ_TYPE);
if(formtype == null)
{
formtype = "";
}
current_stack_frame.put(STATE_STACK_STRUCTOBJ_TYPE, formtype);
}
HomeFactory factory = (HomeFactory) ComponentManager.get("homeFactory");
Map homes = factory.getHomes(StructuredArtifactHomeInterface.class);
List listOfHomes = new Vector();
Iterator it = homes.keySet().iterator();
while(it.hasNext())
{
String key = (String) it.next();
try
{
Object obj = homes.get(key);
listOfHomes.add(obj);
}
catch(Exception ignore)
{}
}
current_stack_frame.put(STATE_STRUCTOBJ_HOMES, listOfHomes);
StructuredArtifactHomeInterface home = null;
SchemaBean rootSchema = null;
ResourcesMetadata elements = null;
if(formtype == null || formtype.equals(""))
{
formtype = "";
current_stack_frame.put(STATE_STACK_STRUCTOBJ_TYPE, formtype);
}
else if(listOfHomes.isEmpty())
{
// hmmm
}
else
{
try
{
home = (StructuredArtifactHomeInterface) factory.getHome(formtype);
}
catch(NullPointerException ignore)
{
home = null;
}
}
if(home != null)
{
rootSchema = new SchemaBean(home.getRootNode(), home.getSchema(), formtype, home.getType().getDescription());
List fields = rootSchema.getFields();
String docRoot = rootSchema.getFieldName();
elements = new ResourcesMetadata("", docRoot, "", "", ResourcesMetadata.WIDGET_NESTED, ResourcesMetadata.WIDGET_NESTED);
elements.setDottedparts(docRoot);
elements.setContainer(null);
elements = createHierarchicalList(elements, fields, 1);
String instruction = home.getInstruction();
current_stack_frame.put(STATE_STACK_STRUCTOBJ_ROOTNAME, docRoot);
current_stack_frame.put(STATE_STACK_STRUCT_OBJ_SCHEMA, rootSchema);
List new_items = (List) current_stack_frame.get(STATE_STACK_CREATE_ITEMS);
if(new_items != null)
{
Integer number = (Integer) current_stack_frame.get(STATE_STACK_CREATE_NUMBER);
if(number == null)
{
number = (Integer) state.getAttribute(STATE_CREATE_NUMBER);
current_stack_frame.put(STATE_STACK_CREATE_NUMBER, number);
}
if(number == null)
{
number = new Integer(1);
current_stack_frame.put(STATE_STACK_CREATE_NUMBER, number);
}
List flatList = elements.getFlatList();
for(int i = 0; i < number.intValue(); i++)
{
//%%%%% doing this wipes out data that's been stored previously
EditItem item = (EditItem) new_items.get(i);
item.setRootname(docRoot);
item.setFormtype(formtype);
item.setInstruction(instruction);
item.setProperties(flatList);
item.setForm(elements);
}
current_stack_frame.put(STATE_STACK_CREATE_ITEMS, new_items);
}
else if(current_stack_frame.get(STATE_STACK_EDIT_ITEM) != null)
{
EditItem item = (EditItem) current_stack_frame.get(STATE_STACK_EDIT_ITEM);
item.setRootname(docRoot);
item.setFormtype(formtype);
item.setInstruction(instruction);
item.setForm(elements);
}
}
} // setupStructuredArtifacts
/**
* This method navigates through a list of SchemaNode objects representing fields in a form,
* creates a ResourcesMetadata object for each field and adds those as nested fields within
* a root element. If a field contains nested fields, a recursive call adds nested fields
* in the corresponding ResourcesMetadata object.
* @param element The root element to which field descriptions are added.
* @param fields A list of metaobj SchemaNode objects.
* @param depth The depth of nesting, corresponding to the amount of indent that will be used
* when displaying the list.
* @return The update root element.
*/
private static ResourcesMetadata createHierarchicalList(ResourcesMetadata element, List fields, int depth)
{
List properties = new Vector();
for(Iterator fieldIt = fields.iterator(); fieldIt.hasNext(); )
{
SchemaBean field = (SchemaBean) fieldIt.next();
SchemaNode node = field.getSchema();
Map annotations = field.getAnnotations();
Pattern pattern = null;
String localname = field.getFieldName();
String description = field.getDescription();
String label = (String) annotations.get("label");
if(label == null || label.trim().equals(""))
{
label = description;
}
String richText = (String) annotations.get("isRichText");
boolean isRichText = richText != null && richText.equalsIgnoreCase(Boolean.TRUE.toString());
Class javaclass = node.getObjectType();
String typename = javaclass.getName();
String widget = ResourcesMetadata.WIDGET_STRING;
int length = 0;
List enumerals = null;
if(field.getFields().size() > 0)
{
widget = ResourcesMetadata.WIDGET_NESTED;
}
else if(node.hasEnumerations())
{
enumerals = node.getEnumeration();
typename = String.class.getName();
widget = ResourcesMetadata.WIDGET_ENUM;
}
else if(typename.equals(String.class.getName()))
{
length = node.getType().getMaxLength();
String baseType = node.getType().getBaseType();
if(isRichText)
{
widget = ResourcesMetadata.WIDGET_WYSIWYG;
}
else if(baseType.trim().equalsIgnoreCase(ResourcesMetadata.NAMESPACE_XSD_ABBREV + ResourcesMetadata.XSD_NORMALIZED_STRING))
{
widget = ResourcesMetadata.WIDGET_STRING;
if(length > 50)
{
length = 50;
}
}
else if(length > 100 || length < 1)
{
widget = ResourcesMetadata.WIDGET_TEXTAREA;
}
else if(length > 50)
{
length = 50;
}
pattern = node.getType().getPattern();
}
else if(typename.equals(Date.class.getName()))
{
widget = ResourcesMetadata.WIDGET_DATE;
}
else if(typename.equals(Boolean.class.getName()))
{
widget = ResourcesMetadata.WIDGET_BOOLEAN;
}
else if(typename.equals(URI.class.getName()))
{
widget = ResourcesMetadata.WIDGET_ANYURI;
}
else if(typename.equals(Number.class.getName()))
{
widget = ResourcesMetadata.WIDGET_INTEGER;
//length = node.getType().getTotalDigits();
length = INTEGER_WIDGET_LENGTH;
}
else if(typename.equals(Double.class.getName()))
{
widget = ResourcesMetadata.WIDGET_DOUBLE;
length = DOUBLE_WIDGET_LENGTH;
}
int minCard = node.getMinOccurs();
int maxCard = node.getMaxOccurs();
if(maxCard < 1)
{
maxCard = Integer.MAX_VALUE;
}
if(minCard < 0)
{
minCard = 0;
}
minCard = java.lang.Math.max(0,minCard);
maxCard = java.lang.Math.max(1,maxCard);
int currentCount = java.lang.Math.min(java.lang.Math.max(1,minCard),maxCard);
ResourcesMetadata prop = new ResourcesMetadata(element.getDottedname(), localname, label, description, typename, widget);
List parts = new Vector(element.getDottedparts());
parts.add(localname);
prop.setDottedparts(parts);
prop.setContainer(element);
if(ResourcesMetadata.WIDGET_NESTED.equals(widget))
{
prop = createHierarchicalList(prop, field.getFields(), depth + 1);
}
prop.setMinCardinality(minCard);
prop.setMaxCardinality(maxCard);
prop.setCurrentCount(currentCount);
prop.setDepth(depth);
if(enumerals != null)
{
prop.setEnumeration(enumerals);
}
if(length > 0)
{
prop.setLength(length);
}
if(pattern != null)
{
prop.setPattern(pattern);
}
properties.add(prop);
}
element.setNested(properties);
return element;
} // createHierarchicalList
/**
* This method captures property values from an org.w3c.dom.Document and inserts them
* into a hierarchical list of ResourcesMetadata objects which describes the structure
* of the form. The values are added by inserting nested instances into the properties.
*
* @param element An org.w3c.dom.Element containing values to be imported.
* @param properties A hierarchical list of ResourcesMetadata objects describing a form
*/
public static void importStructuredArtifact(Node node, ResourcesMetadata property)
{
if(property == null || node == null)
{
return;
}
String tagname = property.getLocalname();
String nodename = node.getLocalName();
if(! tagname.equals(nodename))
{
// return;
}
if(property.getNested().size() == 0)
{
boolean value_found = false;
Node child = node.getFirstChild();
while(! value_found && child != null)
{
if(child.getNodeType() == Node.TEXT_NODE)
{
Text value = (Text) child;
if(ResourcesMetadata.WIDGET_DATE.equals(property.getWidget()) || ResourcesMetadata.WIDGET_DATETIME.equals(property.getWidget()) || ResourcesMetadata.WIDGET_TIME.equals(property.getWidget()))
{
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
Time time = TimeService.newTime();
try
{
Date date = df.parse(value.getData());
time = TimeService.newTime(date.getTime());
}
catch(Exception ignore)
{
// use "now" as default in that case
}
property.setValue(0, time);
}
else if(ResourcesMetadata.WIDGET_ANYURI.equals(property.getWidget()))
{
Reference ref = EntityManager.newReference(ContentHostingService.getReference(value.getData()));
property.setValue(0, ref);
}
else
{
property.setValue(0, value.getData());
}
}
child = child.getNextSibling();
}
}
else if(node instanceof Element)
{
// a nested element
Iterator nestedIt = property.getNested().iterator();
while(nestedIt.hasNext())
{
ResourcesMetadata prop = (ResourcesMetadata) nestedIt.next();
NodeList nodes = ((Element) node).getElementsByTagName(prop.getLocalname());
if(nodes == null)
{
continue;
}
for(int i = 0; i < nodes.getLength(); i++)
{
Node n = nodes.item(i);
if(n != null)
{
ResourcesMetadata instance = prop.addInstance();
if(instance != null)
{
importStructuredArtifact(n, instance);
}
}
}
}
}
} // importStructuredArtifact
protected static String validateURL(String url) throws MalformedURLException
{
if (url.equals (NULL_STRING))
{
// ignore the empty url field
}
else if (url.indexOf ("://") == -1)
{
// if it's missing the transport, add http://
url = "http://" + url;
}
if(!url.equals(NULL_STRING))
{
// valid protocol?
try
{
// test to see if the input validates as a URL.
// Checks string for format only.
URL u = new URL(url);
}
catch (MalformedURLException e1)
{
try
{
Pattern pattern = Pattern.compile("\\s*([a-zA-Z0-9]+)://([^\\n]+)");
Matcher matcher = pattern.matcher(url);
if(matcher.matches())
{
// if URL has "unknown" protocol, check remaider with
// "http" protocol and accept input it that validates.
URL test = new URL("http://" + matcher.group(2));
}
else
{
throw e1;
}
}
catch (MalformedURLException e2)
{
throw e1;
}
}
}
return url;
}
/**
* Retrieve values for an item from edit context. Edit context contains just one item at a time of a known type
* (folder, file, text document, structured-artifact, etc). This method retrieves the data apppropriate to the
* type and updates the values of the EditItem stored as the STATE_STACK_EDIT_ITEM attribute in state.
* @param state
* @param params
* @param item
*/
protected static void captureValues(SessionState state, ParameterParser params)
{
Map current_stack_frame = peekAtStack(state);
EditItem item = (EditItem) current_stack_frame.get(STATE_STACK_EDIT_ITEM);
Set alerts = (Set) state.getAttribute(STATE_EDIT_ALERTS);
if(alerts == null)
{
alerts = new HashSet();
state.setAttribute(STATE_EDIT_ALERTS, alerts);
}
String flow = params.getString("flow");
boolean intentChanged = "intentChanged".equals(flow);
String check_fileName = params.getString("check_fileName");
boolean expectFile = "true".equals(check_fileName);
String intent = params.getString("intent");
String oldintent = (String) current_stack_frame.get(STATE_STACK_EDIT_INTENT);
boolean upload_file = expectFile && item.isFileUpload() || ((item.isHtml() || item.isPlaintext()) && !intentChanged && INTENT_REPLACE_FILE.equals(intent) && INTENT_REPLACE_FILE.equals(oldintent));
boolean revise_file = (item.isHtml() || item.isPlaintext()) && !intentChanged && INTENT_REVISE_FILE.equals(intent) && INTENT_REVISE_FILE.equals(oldintent);
String name = params.getString("name");
if(name == null || "".equals(name.trim()))
{
alerts.add(rb.getString("titlenotnull"));
// addAlert(state, rb.getString("titlenotnull"));
}
else
{
item.setName(name.trim());
}
String description = params.getString("description");
if(description == null)
{
item.setDescription("");
}
else
{
item.setDescription(description);
}
item.setContentHasChanged(false);
if(upload_file)
{
String max_file_size_mb = (String) state.getAttribute(STATE_FILE_UPLOAD_MAX_SIZE);
int max_bytes = 1096 * 1096;
try
{
max_bytes = Integer.parseInt(max_file_size_mb) * 1096 * 1096;
}
catch(Exception e)
{
// if unable to parse an integer from the value
// in the properties file, use 1 MB as a default
max_file_size_mb = "1";
max_bytes = 1096 * 1096;
}
/*
// params.getContentLength() returns m_req.getContentLength()
if(params.getContentLength() >= max_bytes)
{
alerts.add(rb.getString("size") + " " + max_file_size_mb + "MB " + rb.getString("exceeded2"));
}
else
*/
{
// check for file replacement
FileItem fileitem = params.getFileItem("fileName");
if(fileitem == null)
{
// "The user submitted a file to upload but it was too big!"
alerts.clear();
alerts.add(rb.getString("size") + " " + max_file_size_mb + "MB " + rb.getString("exceeded2"));
//item.setMissing("fileName");
}
else if (fileitem.getFileName() == null || fileitem.getFileName().length() == 0)
{
if(item.getContent() == null || item.getContent().length <= 0)
{
// "The user submitted the form, but didn't select a file to upload!"
alerts.add(rb.getString("choosefile") + ". ");
//item.setMissing("fileName");
}
}
else if (fileitem.getFileName().length() > 0)
{
String filename = Validator.getFileName(fileitem.getFileName());
byte[] bytes = fileitem.get();
String contenttype = fileitem.getContentType();
if(bytes.length >= max_bytes)
{
alerts.clear();
alerts.add(rb.getString("size") + " " + max_file_size_mb + "MB " + rb.getString("exceeded2"));
// item.setMissing("fileName");
}
else if(bytes.length > 0)
{
item.setContent(bytes);
item.setContentHasChanged(true);
item.setMimeType(contenttype);
item.setFilename(filename);
}
}
}
}
else if(revise_file)
{
// check for input from editor (textarea)
String content = params.getString("content");
if(content != null)
{
item.setContent(content);
item.setContentHasChanged(true);
}
}
else if(item.isUrl())
{
String url = params.getString("Url");
if(url == null || url.trim().equals(""))
{
item.setFilename("");
alerts.add(rb.getString("validurl"));
}
else
{
// valid protocol?
item.setFilename(url);
try
{
// test format of input
URL u = new URL(url);
}
catch (MalformedURLException e1)
{
try
{
// if URL did not validate, check whether the problem was an
// unrecognized protocol, and accept input if that's the case.
Pattern pattern = Pattern.compile("\\s*([a-zA-Z0-9]+)://([^\\n]+)");
Matcher matcher = pattern.matcher(url);
if(matcher.matches())
{
URL test = new URL("http://" + matcher.group(2));
}
else
{
url = "http://" + url;
URL test = new URL(url);
item.setFilename(url);
}
}
catch (MalformedURLException e2)
{
// invalid url
alerts.add(rb.getString("validurl"));
}
}
}
}
else if(item.isFolder())
{
if(item.canSetQuota())
{
// read the quota fields
String setQuota = params.getString("setQuota");
boolean hasQuota = params.getBoolean("hasQuota");
item.setHasQuota(hasQuota);
if(hasQuota)
{
int q = params.getInt("quota");
item.setQuota(Integer.toString(q));
}
}
}
else if(item.isStructuredArtifact())
{
String formtype = (String) current_stack_frame.get(STATE_STACK_STRUCTOBJ_TYPE);
if(formtype == null)
{
formtype = (String) state.getAttribute(STATE_STRUCTOBJ_TYPE);
if(formtype == null)
{
formtype = "";
}
current_stack_frame.put(STATE_STACK_STRUCTOBJ_TYPE, formtype);
}
String formtype_check = params.getString("formtype");
if(formtype_check == null || formtype_check.equals(""))
{
alerts.add(rb.getString("type"));
item.setMissing("formtype");
}
else if(formtype_check.equals(formtype))
{
item.setFormtype(formtype);
capturePropertyValues(params, item, item.getProperties());
}
}
if(! item.isFolder() && ! item.isStructuredArtifact() && ! item.isUrl())
{
String mime_category = params.getString("mime_category");
String mime_subtype = params.getString("mime_subtype");
if(mime_category != null && mime_subtype != null)
{
String mimetype = mime_category + "/" + mime_subtype;
if(! mimetype.equals(item.getMimeType()))
{
item.setMimeType(mimetype);
item.setContentTypeHasChanged(true);
}
}
}
if(item.isFileUpload() || item.isHtml() || item.isPlaintext())
{
BasicRightsAssignment rightsObj = item.getRights();
rightsObj.captureValues(params);
boolean usingCreativeCommons = state.getAttribute(STATE_USING_CREATIVE_COMMONS) != null && state.getAttribute(STATE_USING_CREATIVE_COMMONS).equals(Boolean.TRUE.toString());
if(usingCreativeCommons)
{
String ccOwnership = params.getString("ccOwnership");
if(ccOwnership != null)
{
item.setRightsownership(ccOwnership);
}
String ccTerms = params.getString("ccTerms");
if(ccTerms != null)
{
item.setLicense(ccTerms);
}
String ccCommercial = params.getString("ccCommercial");
if(ccCommercial != null)
{
item.setAllowCommercial(ccCommercial);
}
String ccModification = params.getString("ccModification");
if(ccCommercial != null)
{
item.setAllowModifications(ccModification);
}
String ccRightsYear = params.getString("ccRightsYear");
if(ccRightsYear != null)
{
item.setRightstyear(ccRightsYear);
}
String ccRightsOwner = params.getString("ccRightsOwner");
if(ccRightsOwner != null)
{
item.setRightsowner(ccRightsOwner);
}
/*
ccValues.ccOwner = new Array();
ccValues.myRights = new Array();
ccValues.otherRights = new Array();
ccValues.ccCommercial = new Array();
ccValues.ccModifications = new Array();
ccValues.ccRightsYear = new Array();
ccValues.ccRightsOwner = new Array();
*/
}
else
{
// check for copyright status
// check for copyright info
// check for copyright alert
String copyrightStatus = StringUtil.trimToNull(params.getString ("copyrightStatus"));
String copyrightInfo = StringUtil.trimToNull(params.getCleanString ("copyrightInfo"));
String copyrightAlert = StringUtil.trimToNull(params.getString("copyrightAlert"));
if (copyrightStatus != null)
{
if (state.getAttribute(COPYRIGHT_NEW_COPYRIGHT) != null && copyrightStatus.equals(state.getAttribute(COPYRIGHT_NEW_COPYRIGHT)))
{
if (copyrightInfo != null)
{
item.setCopyrightInfo( copyrightInfo );
}
else
{
alerts.add(rb.getString("specifycp2"));
// addAlert(state, rb.getString("specifycp2"));
}
}
else if (state.getAttribute(COPYRIGHT_SELF_COPYRIGHT) != null && copyrightStatus.equals (state.getAttribute(COPYRIGHT_SELF_COPYRIGHT)))
{
item.setCopyrightInfo((String) state.getAttribute (STATE_MY_COPYRIGHT));
}
item.setCopyrightStatus( copyrightStatus );
}
item.setCopyrightAlert(copyrightAlert != null);
}
}
String access_mode = params.getString("access_mode");
if(access_mode != null)
{
item.setAccess(access_mode);
if(AccessMode.GROUPED.toString().equals(access_mode))
{
String xxx = params.getString("access_groups");
String[] access_groups = params.getStrings("access_groups");
item.clearGroups();
for(int gr = 0; gr < access_groups.length; gr++)
{
item.addGroup(access_groups[gr]);
}
}
}
Boolean preventPublicDisplay = (Boolean) state.getAttribute(STATE_PREVENT_PUBLIC_DISPLAY);
if(preventPublicDisplay == null)
{
preventPublicDisplay = Boolean.FALSE;
state.setAttribute(STATE_PREVENT_PUBLIC_DISPLAY, preventPublicDisplay);
}
if(preventPublicDisplay.equals(Boolean.FALSE))
{
boolean pubviewset = item.isPubviewset();
boolean pubview = false;
if (! RESOURCES_MODE_DROPBOX.equalsIgnoreCase((String) state.getAttribute(STATE_MODE_RESOURCES)))
{
if (!pubviewset)
{
pubview = params.getBoolean("pubview");
item.setPubview(pubview);
}
}
}
int noti = NotificationService.NOTI_NONE;
// %%STATE_MODE_RESOURCES%%
if (RESOURCES_MODE_DROPBOX.equalsIgnoreCase((String) state.getAttribute(STATE_MODE_RESOURCES)))
{
// set noti to none if in dropbox mode
noti = NotificationService.NOTI_NONE;
}
else
{
// read the notification options
String notification = params.getString("notify");
if ("r".equals(notification))
{
noti = NotificationService.NOTI_REQUIRED;
}
else if ("o".equals(notification))
{
noti = NotificationService.NOTI_OPTIONAL;
}
}
item.setNotification(noti);
List metadataGroups = (List) state.getAttribute(STATE_METADATA_GROUPS);
if(metadataGroups != null && ! metadataGroups.isEmpty())
{
Iterator groupIt = metadataGroups.iterator();
while(groupIt.hasNext())
{
MetadataGroup group = (MetadataGroup) groupIt.next();
if(group.isShowing())
{
Iterator propIt = group.iterator();
while(propIt.hasNext())
{
ResourcesMetadata prop = (ResourcesMetadata) propIt.next();
String propname = prop.getFullname();
if(ResourcesMetadata.WIDGET_DATE.equals(prop.getWidget()) || ResourcesMetadata.WIDGET_DATETIME.equals(prop.getWidget()) || ResourcesMetadata.WIDGET_TIME.equals(prop.getWidget()))
{
int year = 0;
int month = 0;
int day = 0;
int hour = 0;
int minute = 0;
int second = 0;
int millisecond = 0;
String ampm = "";
if(prop.getWidget().equals(ResourcesMetadata.WIDGET_DATE) ||
prop.getWidget().equals(ResourcesMetadata.WIDGET_DATETIME))
{
year = params.getInt(propname + "_year", year);
month = params.getInt(propname + "_month", month);
day = params.getInt(propname + "_day", day);
}
if(prop.getWidget().equals(ResourcesMetadata.WIDGET_TIME) ||
prop.getWidget().equals(ResourcesMetadata.WIDGET_DATETIME))
{
hour = params.getInt(propname + "_hour", hour);
minute = params.getInt(propname + "_minute", minute);
second = params.getInt(propname + "_second", second);
millisecond = params.getInt(propname + "_millisecond", millisecond);
ampm = params.getString(propname + "_ampm").trim();
if("pm".equalsIgnoreCase("ampm"))
{
if(hour < 12)
{
hour += 12;
}
}
else if(hour == 12)
{
hour = 0;
}
}
if(hour > 23)
{
hour = hour % 24;
day++;
}
Time value = TimeService.newTimeLocal(year, month, day, hour, minute, second, millisecond);
item.setMetadataItem(propname,value);
}
else
{
String value = params.getString(propname);
if(value != null)
{
item.setMetadataItem(propname, value);
}
}
}
}
}
}
current_stack_frame.put(STATE_STACK_EDIT_ITEM, item);
state.setAttribute(STATE_EDIT_ALERTS, alerts);
} // captureValues
/**
* Retrieve from an html form all the values needed to create a new resource
* @param item The EditItem object in which the values are temporarily stored.
* @param index The index of the item (used as a suffix in the name of the form element)
* @param state
* @param params
* @param markMissing Indicates whether to mark required elements if they are missing.
* @return
*/
public static Set captureValues(EditItem item, int index, SessionState state, ParameterParser params, boolean markMissing)
{
Map current_stack_frame = peekAtStack(state);
Set item_alerts = new HashSet();
boolean blank_entry = true;
item.clearMissing();
String name = params.getString("name" + index);
if(name == null || name.trim().equals(""))
{
if(markMissing)
{
item_alerts.add(rb.getString("titlenotnull"));
item.setMissing("name");
}
item.setName("");
// addAlert(state, rb.getString("titlenotnull"));
}
else
{
item.setName(name);
blank_entry = false;
}
String description = params.getString("description" + index);
if(description == null || description.trim().equals(""))
{
item.setDescription("");
}
else
{
item.setDescription(description);
blank_entry = false;
}
item.setContentHasChanged(false);
if(item.isFileUpload())
{
String max_file_size_mb = (String) state.getAttribute(STATE_FILE_UPLOAD_MAX_SIZE);
int max_bytes = 1096 * 1096;
try
{
max_bytes = Integer.parseInt(max_file_size_mb) * 1096 * 1096;
}
catch(Exception e)
{
// if unable to parse an integer from the value
// in the properties file, use 1 MB as a default
max_file_size_mb = "1";
max_bytes = 1096 * 1096;
}
/*
// params.getContentLength() returns m_req.getContentLength()
if(params.getContentLength() >= max_bytes)
{
item_alerts.add(rb.getString("size") + " " + max_file_size_mb + "MB " + rb.getString("exceeded2"));
}
else
*/
{
// check for file replacement
FileItem fileitem = null;
try
{
fileitem = params.getFileItem("fileName" + index);
}
catch(Exception e)
{
// this is an error in Firefox, Mozilla and Netscape
// "The user didn't select a file to upload!"
if(item.getContent() == null || item.getContent().length <= 0)
{
item_alerts.add(rb.getString("choosefile") + " " + (index + 1) + ". ");
item.setMissing("fileName");
}
}
if(fileitem == null)
{
// "The user submitted a file to upload but it was too big!"
item_alerts.clear();
item_alerts.add(rb.getString("size") + " " + max_file_size_mb + "MB " + rb.getString("exceeded2"));
item.setMissing("fileName");
}
else if (fileitem.getFileName() == null || fileitem.getFileName().length() == 0)
{
if(item.getContent() == null || item.getContent().length <= 0)
{
// "The user submitted the form, but didn't select a file to upload!"
item_alerts.add(rb.getString("choosefile") + " " + (index + 1) + ". ");
item.setMissing("fileName");
}
}
else if (fileitem.getFileName().length() > 0)
{
String filename = Validator.getFileName(fileitem.getFileName());
byte[] bytes = fileitem.get();
String contenttype = fileitem.getContentType();
if(bytes.length >= max_bytes)
{
item_alerts.clear();
item_alerts.add(rb.getString("size") + " " + max_file_size_mb + "MB " + rb.getString("exceeded2"));
item.setMissing("fileName");
}
else if(bytes.length > 0)
{
item.setContent(bytes);
item.setContentHasChanged(true);
item.setMimeType(contenttype);
item.setFilename(filename);
blank_entry = false;
}
else
{
item_alerts.add(rb.getString("choosefile") + " " + (index + 1) + ". ");
item.setMissing("fileName");
}
}
}
}
else if(item.isPlaintext())
{
// check for input from editor (textarea)
String content = params.getString("content" + index);
if(content != null)
{
item.setContentHasChanged(true);
item.setContent(content);
blank_entry = false;
}
item.setMimeType(MIME_TYPE_DOCUMENT_PLAINTEXT);
}
else if(item.isHtml())
{
// check for input from editor (textarea)
String content = params.getCleanString("content" + index);
StringBuffer alertMsg = new StringBuffer();
content = FormattedText.processHtmlDocument(content, alertMsg);
if (alertMsg.length() > 0)
{
item_alerts.add(alertMsg.toString());
}
if(content != null && !content.equals(""))
{
item.setContent(content);
item.setContentHasChanged(true);
blank_entry = false;
}
item.setMimeType(MIME_TYPE_DOCUMENT_HTML);
}
else if(item.isUrl())
{
item.setMimeType(ResourceProperties.TYPE_URL);
String url = params.getString("Url" + index);
if(url == null || url.trim().equals(""))
{
item.setFilename("");
item_alerts.add(rb.getString("specifyurl"));
item.setMissing("Url");
}
else
{
item.setFilename(url);
blank_entry = false;
// is protocol supplied and, if so, is it recognized?
try
{
// check format of input
URL u = new URL(url);
}
catch (MalformedURLException e1)
{
try
{
// if URL did not validate, check whether the problem was an
// unrecognized protocol, and accept input if that's the case.
Pattern pattern = Pattern.compile("\\s*([a-zA-Z0-9]+)://([^\\n]+)");
Matcher matcher = pattern.matcher(url);
if(matcher.matches())
{
URL test = new URL("http://" + matcher.group(2));
}
else
{
url = "http://" + url;
URL test = new URL(url);
item.setFilename(url);
}
}
catch (MalformedURLException e2)
{
// invalid url
item_alerts.add(rb.getString("validurl"));
item.setMissing("Url");
}
}
}
}
else if(item.isStructuredArtifact())
{
String formtype = (String) current_stack_frame.get(STATE_STACK_STRUCTOBJ_TYPE);
if(formtype == null)
{
formtype = (String) state.getAttribute(STATE_STRUCTOBJ_TYPE);
if(formtype == null)
{
formtype = "";
}
current_stack_frame.put(STATE_STACK_STRUCTOBJ_TYPE, formtype);
}
String formtype_check = params.getString("formtype");
if(formtype_check == null || formtype_check.equals(""))
{
item_alerts.add("Must select a form type");
item.setMissing("formtype");
}
else if(formtype_check.equals(formtype))
{
item.setFormtype(formtype);
capturePropertyValues(params, item, item.getProperties());
// blank_entry = false;
}
item.setMimeType(MIME_TYPE_STRUCTOBJ);
}
if(item.isFileUpload() || item.isHtml() || item.isPlaintext())
{
BasicRightsAssignment rightsObj = item.getRights();
rightsObj.captureValues(params);
boolean usingCreativeCommons = state.getAttribute(STATE_USING_CREATIVE_COMMONS) != null && state.getAttribute(STATE_USING_CREATIVE_COMMONS).equals(Boolean.TRUE.toString());
if(usingCreativeCommons)
{
String ccOwnership = params.getString("ccOwnership" + index);
if(ccOwnership != null)
{
item.setRightsownership(ccOwnership);
}
String ccTerms = params.getString("ccTerms" + index);
if(ccTerms != null)
{
item.setLicense(ccTerms);
}
String ccCommercial = params.getString("ccCommercial" + index);
if(ccCommercial != null)
{
item.setAllowCommercial(ccCommercial);
}
String ccModification = params.getString("ccModification" + index);
if(ccCommercial != null)
{
item.setAllowModifications(ccModification);
}
String ccRightsYear = params.getString("ccRightsYear" + index);
if(ccRightsYear != null)
{
item.setRightstyear(ccRightsYear);
}
String ccRightsOwner = params.getString("ccRightsOwner" + index);
if(ccRightsOwner != null)
{
item.setRightsowner(ccRightsOwner);
}
/*
ccValues.ccOwner = new Array();
ccValues.myRights = new Array();
ccValues.otherRights = new Array();
ccValues.ccCommercial = new Array();
ccValues.ccModifications = new Array();
ccValues.ccRightsYear = new Array();
ccValues.ccRightsOwner = new Array();
*/
}
else
{
// check for copyright status
// check for copyright info
// check for copyright alert
String copyrightStatus = StringUtil.trimToNull(params.getString ("copyright" + index));
String copyrightInfo = StringUtil.trimToNull(params.getCleanString ("newcopyright" + index));
String copyrightAlert = StringUtil.trimToNull(params.getString("copyrightAlert" + index));
if (copyrightStatus != null)
{
if (state.getAttribute(COPYRIGHT_NEW_COPYRIGHT) != null && copyrightStatus.equals(state.getAttribute(COPYRIGHT_NEW_COPYRIGHT)))
{
if (copyrightInfo != null)
{
item.setCopyrightInfo( copyrightInfo );
}
else
{
item_alerts.add(rb.getString("specifycp2"));
// addAlert(state, rb.getString("specifycp2"));
}
}
else if (state.getAttribute(COPYRIGHT_SELF_COPYRIGHT) != null && copyrightStatus.equals (state.getAttribute(COPYRIGHT_SELF_COPYRIGHT)))
{
item.setCopyrightInfo((String) state.getAttribute (STATE_MY_COPYRIGHT));
}
item.setCopyrightStatus( copyrightStatus );
}
item.setCopyrightAlert(copyrightAlert != null);
}
}
Boolean preventPublicDisplay = (Boolean) state.getAttribute(STATE_PREVENT_PUBLIC_DISPLAY);
if(preventPublicDisplay == null)
{
preventPublicDisplay = Boolean.FALSE;
state.setAttribute(STATE_PREVENT_PUBLIC_DISPLAY, preventPublicDisplay);
}
if(preventPublicDisplay.equals(Boolean.FALSE))
{
boolean pubviewset = item.isPubviewset();
boolean pubview = false;
if (! RESOURCES_MODE_DROPBOX.equalsIgnoreCase((String) state.getAttribute(STATE_MODE_RESOURCES)))
{
if (!pubviewset)
{
pubview = params.getBoolean("pubview");
item.setPubview(pubview);
}
}
}
String access_mode = params.getString("access_mode" + index);
if(access_mode != null)
{
item.setAccess(access_mode);
if(AccessMode.GROUPED.toString().equals(access_mode))
{
String[] access_groups = params.getStrings("access_groups" + index);
for(int gr = 0; gr < access_groups.length; gr++)
{
item.addGroup(access_groups[gr]);
}
}
}
int noti = NotificationService.NOTI_NONE;
// %%STATE_MODE_RESOURCES%%
if (RESOURCES_MODE_DROPBOX.equalsIgnoreCase((String) state.getAttribute(STATE_MODE_RESOURCES)))
{
// set noti to none if in dropbox mode
noti = NotificationService.NOTI_NONE;
}
else
{
// read the notification options
String notification = params.getString("notify" + index);
if ("r".equals(notification))
{
noti = NotificationService.NOTI_REQUIRED;
}
else if ("o".equals(notification))
{
noti = NotificationService.NOTI_OPTIONAL;
}
}
item.setNotification(noti);
List metadataGroups = (List) state.getAttribute(STATE_METADATA_GROUPS);
if(metadataGroups != null && ! metadataGroups.isEmpty())
{
Iterator groupIt = metadataGroups.iterator();
while(groupIt.hasNext())
{
MetadataGroup group = (MetadataGroup) groupIt.next();
if(item.isGroupShowing(group.getName()))
{
Iterator propIt = group.iterator();
while(propIt.hasNext())
{
ResourcesMetadata prop = (ResourcesMetadata) propIt.next();
String propname = prop.getFullname();
if(ResourcesMetadata.WIDGET_DATE.equals(prop.getWidget()) || ResourcesMetadata.WIDGET_DATETIME.equals(prop.getWidget()) || ResourcesMetadata.WIDGET_TIME.equals(prop.getWidget()))
{
int year = 0;
int month = 0;
int day = 0;
int hour = 0;
int minute = 0;
int second = 0;
int millisecond = 0;
String ampm = "";
if(prop.getWidget().equals(ResourcesMetadata.WIDGET_DATE) ||
prop.getWidget().equals(ResourcesMetadata.WIDGET_DATETIME))
{
year = params.getInt(propname + "_" + index + "_year", year);
month = params.getInt(propname + "_" + index + "_month", month);
day = params.getInt(propname + "_" + index + "_day", day);
}
if(prop.getWidget().equals(ResourcesMetadata.WIDGET_TIME) ||
prop.getWidget().equals(ResourcesMetadata.WIDGET_DATETIME))
{
hour = params.getInt(propname + "_" + index + "_hour", hour);
minute = params.getInt(propname + "_" + index + "_minute", minute);
second = params.getInt(propname + "_" + index + "_second", second);
millisecond = params.getInt(propname + "_" + index + "_millisecond", millisecond);
ampm = params.getString(propname + "_" + index + "_ampm").trim();
if("pm".equalsIgnoreCase(ampm))
{
if(hour < 12)
{
hour += 12;
}
}
else if(hour == 12)
{
hour = 0;
}
}
if(hour > 23)
{
hour = hour % 24;
day++;
}
Time value = TimeService.newTimeLocal(year, month, day, hour, minute, second, millisecond);
item.setMetadataItem(propname,value);
}
else
{
String value = params.getString(propname + "_" + index);
if(value != null)
{
item.setMetadataItem(propname, value);
}
}
}
}
}
}
item.markAsBlank(blank_entry);
return item_alerts;
}
/**
* Retrieve values for one or more items from create context. Create context contains up to ten items at a time
* all of the same type (folder, file, text document, structured-artifact, etc). This method retrieves the data
* apppropriate to the type and updates the values of the EditItem objects stored as the STATE_STACK_CREATE_ITEMS
* attribute in state. If the third parameter is "true", missing/incorrect user inputs will generate error messages
* and attach flags to the input elements.
* @param state
* @param params
* @param markMissing Should this method generate error messages and add flags for missing/incorrect user inputs?
*/
protected static void captureMultipleValues(SessionState state, ParameterParser params, boolean markMissing)
{
Map current_stack_frame = peekAtStack(state);
Integer number = (Integer) current_stack_frame.get(STATE_STACK_CREATE_NUMBER);
if(number == null)
{
number = (Integer) state.getAttribute(STATE_CREATE_NUMBER);
current_stack_frame.put(STATE_STACK_CREATE_NUMBER, number);
}
if(number == null)
{
number = new Integer(1);
current_stack_frame.put(STATE_STACK_CREATE_NUMBER, number);
}
List new_items = (List) current_stack_frame.get(STATE_STACK_CREATE_ITEMS);
if(new_items == null)
{
String defaultCopyrightStatus = (String) state.getAttribute(DEFAULT_COPYRIGHT);
if(defaultCopyrightStatus == null || defaultCopyrightStatus.trim().equals(""))
{
defaultCopyrightStatus = ServerConfigurationService.getString("default.copyright");
state.setAttribute(DEFAULT_COPYRIGHT, defaultCopyrightStatus);
}
String itemType = (String) current_stack_frame.get(STATE_STACK_CREATE_TYPE);
if(itemType == null || itemType.trim().equals(""))
{
itemType = (String) state.getAttribute(STATE_CREATE_TYPE);
if(itemType == null || itemType.trim().equals(""))
{
itemType = TYPE_UPLOAD;
}
current_stack_frame.put(STATE_STACK_CREATE_TYPE, itemType);
}
new_items = new Vector();
for(int i = 0; i < CREATE_MAX_ITEMS; i++)
{
EditItem item = new EditItem(itemType);
item.setCopyrightStatus(defaultCopyrightStatus);
new_items.add(item);
}
current_stack_frame.put(STATE_STACK_CREATE_ITEMS, new_items);
}
Set alerts = (Set) state.getAttribute(STATE_CREATE_ALERTS);
if(alerts == null)
{
alerts = new HashSet();
state.setAttribute(STATE_CREATE_ALERTS, alerts);
}
int actualCount = 0;
Set first_item_alerts = null;
String max_file_size_mb = (String) state.getAttribute(STATE_FILE_UPLOAD_MAX_SIZE);
int max_bytes = 1096 * 1096;
try
{
max_bytes = Integer.parseInt(max_file_size_mb) * 1096 * 1096;
}
catch(Exception e)
{
// if unable to parse an integer from the value
// in the properties file, use 1 MB as a default
max_file_size_mb = "1";
max_bytes = 1096 * 1096;
}
/*
// params.getContentLength() returns m_req.getContentLength()
if(params.getContentLength() > max_bytes)
{
alerts.add(rb.getString("size") + " " + max_file_size_mb + "MB " + rb.getString("exceeded2"));
state.setAttribute(STATE_CREATE_ALERTS, alerts);
return;
}
*/
for(int i = 0; i < number.intValue(); i++)
{
EditItem item = (EditItem) new_items.get(i);
Set item_alerts = captureValues(item, i, state, params, markMissing);
if(i == 0)
{
first_item_alerts = item_alerts;
}
else if(item.isBlank())
{
item.clearMissing();
}
if(! item.isBlank())
{
alerts.addAll(item_alerts);
actualCount ++;
}
}
if(actualCount > 0)
{
EditItem item = (EditItem) new_items.get(0);
if(item.isBlank())
{
item.clearMissing();
}
}
else if(markMissing)
{
alerts.addAll(first_item_alerts);
}
state.setAttribute(STATE_CREATE_ALERTS, alerts);
current_stack_frame.put(STATE_STACK_CREATE_ACTUAL_COUNT, Integer.toString(actualCount));
} // captureMultipleValues
protected static void capturePropertyValues(ParameterParser params, EditItem item, List properties)
{
// use the item's properties if they're not supplied
if(properties == null)
{
properties = item.getProperties();
}
// if max cardinality > 1, value is a list (Iterate over members of list)
// else value is an object, not a list
// if type is nested, object is a Map (iterate over name-value pairs for the properties of the nested object)
// else object is type to store value, usually a string or a date/time
Iterator it = properties.iterator();
while(it.hasNext())
{
ResourcesMetadata prop = (ResourcesMetadata) it.next();
String propname = prop.getDottedname();
if(ResourcesMetadata.WIDGET_NESTED.equals(prop.getWidget()))
{
// do nothing
}
else if(ResourcesMetadata.WIDGET_BOOLEAN.equals(prop.getWidget()))
{
String value = params.getString(propname);
if(value == null || Boolean.FALSE.toString().equals(value))
{
prop.setValue(0, Boolean.FALSE.toString());
}
else
{
prop.setValue(0, Boolean.TRUE.toString());
}
}
else if(ResourcesMetadata.WIDGET_DATE.equals(prop.getWidget()) || ResourcesMetadata.WIDGET_DATETIME.equals(prop.getWidget()) || ResourcesMetadata.WIDGET_TIME.equals(prop.getWidget()))
{
int year = 0;
int month = 0;
int day = 0;
int hour = 0;
int minute = 0;
int second = 0;
int millisecond = 0;
String ampm = "";
if(prop.getWidget().equals(ResourcesMetadata.WIDGET_DATE) ||
prop.getWidget().equals(ResourcesMetadata.WIDGET_DATETIME))
{
year = params.getInt(propname + "_year", year);
month = params.getInt(propname + "_month", month);
day = params.getInt(propname + "_day", day);
}
if(prop.getWidget().equals(ResourcesMetadata.WIDGET_TIME) ||
prop.getWidget().equals(ResourcesMetadata.WIDGET_DATETIME))
{
hour = params.getInt(propname + "_hour", hour);
minute = params.getInt(propname + "_minute", minute);
second = params.getInt(propname + "_second", second);
millisecond = params.getInt(propname + "_millisecond", millisecond);
ampm = params.getString(propname + "_ampm");
if("pm".equalsIgnoreCase(ampm))
{
if(hour < 12)
{
hour += 12;
}
}
else if(hour == 12)
{
hour = 0;
}
}
if(hour > 23)
{
hour = hour % 24;
day++;
}
Time value = TimeService.newTimeLocal(year, month, day, hour, minute, second, millisecond);
prop.setValue(0, value);
}
else if(ResourcesMetadata.WIDGET_ANYURI.equals(prop.getWidget()))
{
String value = params.getString(propname);
if(value != null && ! value.trim().equals(""))
{
Reference ref = EntityManager.newReference(ContentHostingService.getReference(value));
prop.setValue(0, ref);
}
}
else
{
String value = params.getString(propname);
if(value != null)
{
prop.setValue(0, value);
}
}
}
} // capturePropertyValues
/**
* Modify the properties
*/
public static void doSavechanges ( RunData data)
{
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
ParameterParser params = data.getParameters ();
String flow = params.getString("flow").trim();
if(flow == null || "cancel".equals(flow))
{
doCancel(data);
return;
}
// get values from form and update STATE_STACK_EDIT_ITEM attribute in state
captureValues(state, params);
Map current_stack_frame = peekAtStack(state);
EditItem item = (EditItem) current_stack_frame.get(STATE_STACK_EDIT_ITEM);
if(flow.equals("showMetadata"))
{
doShow_metadata(data);
return;
}
else if(flow.equals("hideMetadata"))
{
doHide_metadata(data);
return;
}
else if(flow.equals("intentChanged"))
{
doToggle_intent(data);
return;
}
else if(flow.equals("addInstance"))
{
String field = params.getString("field");
addInstance(field, item.getProperties());
ResourcesMetadata form = item.getForm();
List flatList = form.getFlatList();
item.setProperties(flatList);
return;
}
else if(flow.equals("linkResource"))
{
// captureMultipleValues(state, params, false);
createLink(data, state);
//Map new_stack_frame = pushOnStack(state);
//new_stack_frame.put(ResourcesAction.STATE_RESOURCES_HELPER_MODE, ResourcesAction.MODE_ATTACHMENT_SELECT);
state.setAttribute(ResourcesAction.STATE_RESOURCES_HELPER_MODE, ResourcesAction.MODE_ATTACHMENT_SELECT);
return;
}
Set alerts = (Set) state.getAttribute(STATE_EDIT_ALERTS);
if(item.isStructuredArtifact())
{
SchemaBean bean = (SchemaBean) current_stack_frame.get(STATE_STACK_STRUCT_OBJ_SCHEMA);
SaveArtifactAttempt attempt = new SaveArtifactAttempt(item, bean.getSchema());
validateStructuredArtifact(attempt);
Iterator errorIt = attempt.getErrors().iterator();
while(errorIt.hasNext())
{
ValidationError error = (ValidationError) errorIt.next();
alerts.add(error.getDefaultMessage());
}
}
if(alerts.isEmpty())
{
// populate the property list
try
{
// get an edit
ContentCollectionEdit cedit = null;
ContentResourceEdit redit = null;
GroupAwareEdit gedit = null;
ResourcePropertiesEdit pedit = null;
if(item.isFolder())
{
cedit = ContentHostingService.editCollection(item.getId());
gedit = cedit;
pedit = cedit.getPropertiesEdit();
}
else
{
redit = ContentHostingService.editResource(item.getId());
gedit = redit;
pedit = redit.getPropertiesEdit();
}
try
{
if((AccessMode.INHERITED.toString().equals(item.getAccess()) || AccessMode.SITE.toString().equals(item.getAccess())) && AccessMode.GROUPED == gedit.getAccess())
{
gedit.clearGroupAccess();
}
else if(gedit.getAccess() == AccessMode.GROUPED && item.getGroups().isEmpty())
{
gedit.clearGroupAccess();
}
else if(!item.getGroups().isEmpty())
{
Collection groupRefs = new Vector();
Iterator it = item.getGroups().iterator();
while(it.hasNext())
{
Group group = (Group) it.next();
groupRefs.add(group.getReference());
}
gedit.setGroupAccess(groupRefs);
}
}
catch(InconsistentException e)
{
// TODO: Should this be reported to user??
logger.error("ResourcesAction.doSavechanges ***** InconsistentException changing groups ***** " + e.getMessage());
}
if(item.isFolder())
{
}
else
{
if(item.isUrl())
{
redit.setContent(item.getFilename().getBytes());
}
else if(item.isStructuredArtifact())
{
redit.setContentType(item.getMimeType());
redit.setContent(item.getContent());
}
else if(item.contentHasChanged())
{
redit.setContentType(item.getMimeType());
redit.setContent(item.getContent());
}
else if(item.contentTypeHasChanged())
{
redit.setContentType(item.getMimeType());
}
BasicRightsAssignment rightsObj = item.getRights();
rightsObj.addResourceProperties(pedit);
String copyright = StringUtil.trimToNull(params.getString ("copyright"));
String newcopyright = StringUtil.trimToNull(params.getCleanString (NEW_COPYRIGHT));
String copyrightAlert = StringUtil.trimToNull(params.getString("copyrightAlert"));
if (copyright != null)
{
if (state.getAttribute(COPYRIGHT_NEW_COPYRIGHT) != null && copyright.equals(state.getAttribute(COPYRIGHT_NEW_COPYRIGHT)))
{
if (newcopyright != null)
{
pedit.addProperty (ResourceProperties.PROP_COPYRIGHT, newcopyright);
}
else
{
alerts.add(rb.getString("specifycp2"));
// addAlert(state, rb.getString("specifycp2"));
}
}
else if (state.getAttribute(COPYRIGHT_SELF_COPYRIGHT) != null && copyright.equals (state.getAttribute(COPYRIGHT_SELF_COPYRIGHT)))
{
String mycopyright = (String) state.getAttribute (STATE_MY_COPYRIGHT);
pedit.addProperty (ResourceProperties.PROP_COPYRIGHT, mycopyright);
}
pedit.addProperty(ResourceProperties.PROP_COPYRIGHT_CHOICE, copyright);
}
if (copyrightAlert != null)
{
pedit.addProperty (ResourceProperties.PROP_COPYRIGHT_ALERT, copyrightAlert);
}
else
{
pedit.removeProperty (ResourceProperties.PROP_COPYRIGHT_ALERT);
}
}
if (!(item.isFolder() && (item.getId().equals ((String) state.getAttribute (STATE_HOME_COLLECTION_ID)))))
{
pedit.addProperty (ResourceProperties.PROP_DISPLAY_NAME, item.getName());
} // the home collection's title is not modificable
pedit.addProperty (ResourceProperties.PROP_DESCRIPTION, item.getDescription());
// deal with quota (collections only)
if ((cedit != null) && item.canSetQuota())
{
if (item.hasQuota())
{
// set the quota
pedit.addProperty(ResourceProperties.PROP_COLLECTION_BODY_QUOTA, item.getQuota());
}
else
{
// clear the quota
pedit.removeProperty(ResourceProperties.PROP_COLLECTION_BODY_QUOTA);
}
}
List metadataGroups = (List) state.getAttribute(STATE_METADATA_GROUPS);
state.setAttribute(STATE_EDIT_ALERTS, alerts);
saveMetadata(pedit, metadataGroups, item);
alerts = (Set) state.getAttribute(STATE_EDIT_ALERTS);
// commit the change
if (cedit != null)
{
ContentHostingService.commitCollection(cedit);
}
else
{
ContentHostingService.commitResource(redit, item.getNotification());
}
current_stack_frame.put(STATE_STACK_EDIT_INTENT, INTENT_REVISE_FILE);
Boolean preventPublicDisplay = (Boolean) state.getAttribute(STATE_PREVENT_PUBLIC_DISPLAY);
if(preventPublicDisplay == null)
{
preventPublicDisplay = Boolean.FALSE;
state.setAttribute(STATE_PREVENT_PUBLIC_DISPLAY, preventPublicDisplay);
}
if(preventPublicDisplay.equals(Boolean.FALSE))
{
if (! RESOURCES_MODE_DROPBOX.equalsIgnoreCase((String) state.getAttribute(STATE_MODE_RESOURCES)))
{
if (!item.isPubviewset())
{
ContentHostingService.setPubView(item.getId(), item.isPubview());
}
}
}
// need to refresh collection containing current edit item make changes show up
String containerId = ContentHostingService.getContainingCollectionId(item.getId());
Map expandedCollections = (Map) state.getAttribute(STATE_EXPANDED_COLLECTIONS);
Object old = expandedCollections.remove(containerId);
if (old != null)
{
try
{
ContentCollection container = ContentHostingService.getCollection(containerId);
expandedCollections.put(containerId, container);
}
catch (Throwable ignore){}
}
}
catch (TypeException e)
{
alerts.add(rb.getString("typeex") + " " + item.getId());
// addAlert(state," " + rb.getString("typeex") + " " + item.getId());
}
catch (IdUnusedException e)
{
alerts.add(RESOURCE_NOT_EXIST_STRING);
// addAlert(state,RESOURCE_NOT_EXIST_STRING);
}
catch (PermissionException e)
{
alerts.add(rb.getString("notpermis10") + " " + item.getId());
// addAlert(state, rb.getString("notpermis10") + " " + item.getId() + ". " );
}
catch (InUseException e)
{
alerts.add(rb.getString("someone") + " " + item.getId());
// addAlert(state, rb.getString("someone") + " " + item.getId() + ". ");
}
catch (ServerOverloadException e)
{
alerts.add(rb.getString("failed"));
}
catch (OverQuotaException e)
{
alerts.add(rb.getString("changing1") + " " + item.getId() + " " + rb.getString("changing2"));
// addAlert(state, rb.getString("changing1") + " " + item.getId() + " " + rb.getString("changing2"));
}
catch(RuntimeException e)
{
logger.error("ResourcesAction.doSavechanges ***** Unknown Exception ***** " + e.getMessage());
logger.error("ResourcesAction.doSavechanges ***** Unknown Exception ***** ", e);
alerts.add(rb.getString("failed"));
}
} // if - else
if(alerts.isEmpty())
{
// modify properties sucessful
String mode = (String) state.getAttribute(STATE_MODE);
popFromStack(state);
resetCurrentMode(state);
} //if-else
else
{
Iterator alertIt = alerts.iterator();
while(alertIt.hasNext())
{
String alert = (String) alertIt.next();
addAlert(state, alert);
}
alerts.clear();
state.setAttribute(STATE_EDIT_ALERTS, alerts);
// state.setAttribute(STATE_CREATE_MISSING_ITEM, missing);
}
} // doSavechanges
/**
* @param pedit
* @param metadataGroups
* @param metadata
*/
private static void saveMetadata(ResourcePropertiesEdit pedit, List metadataGroups, EditItem item)
{
if(metadataGroups != null && !metadataGroups.isEmpty())
{
MetadataGroup group = null;
Iterator it = metadataGroups.iterator();
while(it.hasNext())
{
group = (MetadataGroup) it.next();
Iterator props = group.iterator();
while(props.hasNext())
{
ResourcesMetadata prop = (ResourcesMetadata) props.next();
if(ResourcesMetadata.WIDGET_DATETIME.equals(prop.getWidget()) || ResourcesMetadata.WIDGET_DATE.equals(prop.getWidget()) || ResourcesMetadata.WIDGET_TIME.equals(prop.getWidget()))
{
Time val = (Time)item.getMetadata().get(prop.getFullname());
if(val != null)
{
pedit.addProperty(prop.getFullname(), val.toString());
}
}
else
{
String val = (String) item.getMetadata().get(prop.getFullname());
pedit.addProperty(prop.getFullname(), val);
}
}
}
}
}
/**
* @param data
*/
protected static void doToggle_intent(RunData data)
{
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
ParameterParser params = data.getParameters ();
String intent = params.getString("intent");
Map current_stack_frame = peekAtStack(state);
current_stack_frame.put(STATE_STACK_EDIT_INTENT, intent);
} // doToggle_intent
/**
* @param data
*/
public static void doHideOtherSites(RunData data)
{
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
state.setAttribute(STATE_SHOW_OTHER_SITES, Boolean.FALSE.toString());
//get the ParameterParser from RunData
ParameterParser params = data.getParameters ();
// save the current selections
Set selectedSet = new TreeSet();
String[] selectedItems = params.getStrings("selectedMembers");
if(selectedItems != null)
{
selectedSet.addAll(Arrays.asList(selectedItems));
}
state.setAttribute(STATE_LIST_SELECTIONS, selectedSet);
}
/**
* @param data
*/
public static void doShowOtherSites(RunData data)
{
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
//get the ParameterParser from RunData
ParameterParser params = data.getParameters ();
// save the current selections
Set selectedSet = new TreeSet();
String[] selectedItems = params.getStrings("selectedMembers");
if(selectedItems != null)
{
selectedSet.addAll(Arrays.asList(selectedItems));
}
state.setAttribute(STATE_LIST_SELECTIONS, selectedSet);
state.setAttribute(STATE_SHOW_OTHER_SITES, Boolean.TRUE.toString());
}
/**
* @param data
*/
public static void doHide_metadata(RunData data)
{
ParameterParser params = data.getParameters ();
String name = params.getString("metadataGroup");
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
List metadataGroups = (List) state.getAttribute(STATE_METADATA_GROUPS);
if(metadataGroups != null && ! metadataGroups.isEmpty())
{
boolean found = false;
MetadataGroup group = null;
Iterator it = metadataGroups.iterator();
while(!found && it.hasNext())
{
group = (MetadataGroup) it.next();
found = (name.equals(Validator.escapeUrl(group.getName())) || name.equals(group.getName()));
}
if(found)
{
group.setShowing(false);
}
}
} // doHide_metadata
/**
* @param data
*/
public static void doShow_metadata(RunData data)
{
ParameterParser params = data.getParameters ();
String name = params.getString("metadataGroup");
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
List metadataGroups = (List) state.getAttribute(STATE_METADATA_GROUPS);
if(metadataGroups != null && ! metadataGroups.isEmpty())
{
boolean found = false;
MetadataGroup group = null;
Iterator it = metadataGroups.iterator();
while(!found && it.hasNext())
{
group = (MetadataGroup) it.next();
found = (name.equals(Validator.escapeUrl(group.getName())) || name.equals(group.getName()));
}
if(found)
{
group.setShowing(true);
}
}
} // doShow_metadata
/**
* Sort based on the given property
*/
public static void doSort ( RunData data)
{
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
//get the ParameterParser from RunData
ParameterParser params = data.getParameters ();
// save the current selections
Set selectedSet = new TreeSet();
String[] selectedItems = data.getParameters ().getStrings ("selectedMembers");
if(selectedItems != null)
{
selectedSet.addAll(Arrays.asList(selectedItems));
}
state.setAttribute(STATE_LIST_SELECTIONS, selectedSet);
String criteria = params.getString ("criteria");
if (criteria.equals ("title"))
{
criteria = ResourceProperties.PROP_DISPLAY_NAME;
}
else if (criteria.equals ("size"))
{
criteria = ResourceProperties.PROP_CONTENT_LENGTH;
}
else if (criteria.equals ("created by"))
{
criteria = ResourceProperties.PROP_CREATOR;
}
else if (criteria.equals ("last modified"))
{
criteria = ResourceProperties.PROP_MODIFIED_DATE;
}
// current sorting sequence
String asc = NULL_STRING;
if (!criteria.equals (state.getAttribute (STATE_SORT_BY)))
{
state.setAttribute (STATE_SORT_BY, criteria);
asc = Boolean.TRUE.toString();
state.setAttribute (STATE_SORT_ASC, asc);
}
else
{
// current sorting sequence
asc = (String) state.getAttribute (STATE_SORT_ASC);
//toggle between the ascending and descending sequence
if (asc.equals (Boolean.TRUE.toString()))
{
asc = Boolean.FALSE.toString();
}
else
{
asc = Boolean.TRUE.toString();
}
state.setAttribute (STATE_SORT_ASC, asc);
}
if (state.getAttribute(STATE_MESSAGE) == null)
{
// sort sucessful
// state.setAttribute (STATE_MODE, MODE_LIST);
} // if-else
} // doSort
/**
* set the state name to be "deletecofirm" if any item has been selected for deleting
*/
public void doDeleteconfirm ( RunData data)
{
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
Set deleteIdSet = new TreeSet();
// cancel copy if there is one in progress
if(! Boolean.FALSE.toString().equals(state.getAttribute (STATE_COPY_FLAG)))
{
initCopyContext(state);
}
// cancel move if there is one in progress
if(! Boolean.FALSE.toString().equals(state.getAttribute (STATE_MOVE_FLAG)))
{
initMoveContext(state);
}
String[] deleteIds = data.getParameters ().getStrings ("selectedMembers");
if (deleteIds == null)
{
// there is no resource selected, show the alert message to the user
addAlert(state, rb.getString("choosefile3"));
}
else
{
deleteIdSet.addAll(Arrays.asList(deleteIds));
List deleteItems = new Vector();
List notDeleteItems = new Vector();
List nonEmptyFolders = new Vector();
List roots = (List) state.getAttribute(STATE_COLLECTION_ROOTS);
Iterator rootIt = roots.iterator();
while(rootIt.hasNext())
{
BrowseItem root = (BrowseItem) rootIt.next();
List members = root.getMembers();
Iterator memberIt = members.iterator();
while(memberIt.hasNext())
{
BrowseItem member = (BrowseItem) memberIt.next();
if(deleteIdSet.contains(member.getId()))
{
if(member.isFolder())
{
if(ContentHostingService.allowRemoveCollection(member.getId()))
{
deleteItems.add(member);
if(! member.isEmpty())
{
nonEmptyFolders.add(member);
}
}
else
{
notDeleteItems.add(member);
}
}
else if(ContentHostingService.allowRemoveResource(member.getId()))
{
deleteItems.add(member);
}
else
{
notDeleteItems.add(member);
}
}
}
}
if(! notDeleteItems.isEmpty())
{
String notDeleteNames = "";
boolean first_item = true;
Iterator notIt = notDeleteItems.iterator();
while(notIt.hasNext())
{
BrowseItem item = (BrowseItem) notIt.next();
if(first_item)
{
notDeleteNames = item.getName();
first_item = false;
}
else if(notIt.hasNext())
{
notDeleteNames += ", " + item.getName();
}
else
{
notDeleteNames += " and " + item.getName();
}
}
addAlert(state, rb.getString("notpermis14") + notDeleteNames);
}
/*
//htripath-SAK-1712 - Set new collectionId as resources are not deleted under 'more' requirement.
if(state.getAttribute(STATE_MESSAGE) == null){
String newCollectionId=ContentHostingService.getContainingCollectionId(currentId);
state.setAttribute(STATE_COLLECTION_ID, newCollectionId);
}
*/
// delete item
state.setAttribute (STATE_DELETE_ITEMS, deleteItems);
state.setAttribute (STATE_DELETE_ITEMS_NOT_EMPTY, nonEmptyFolders);
} // if-else
if (state.getAttribute(STATE_MESSAGE) == null)
{
state.setAttribute (STATE_MODE, MODE_DELETE_CONFIRM);
state.setAttribute(STATE_LIST_SELECTIONS, deleteIdSet);
}
} // doDeleteconfirm
/**
* set the state name to be "cut" if any item has been selected for cutting
*/
public void doCut ( RunData data)
{
// get the state object
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
String[] cutItems = data.getParameters ().getStrings ("selectedMembers");
if (cutItems == null)
{
// there is no resource selected, show the alert message to the user
addAlert(state, rb.getString("choosefile5"));
state.setAttribute (STATE_MODE, MODE_LIST);
}
else
{
Vector cutIdsVector = new Vector ();
String nonCutIds = NULL_STRING;
String cutId = NULL_STRING;
for (int i = 0; i < cutItems.length; i++)
{
cutId = cutItems[i];
try
{
ResourceProperties properties = ContentHostingService.getProperties (cutId);
if (properties.getProperty (ResourceProperties.PROP_IS_COLLECTION).equals (Boolean.TRUE.toString()))
{
String alert = (String) state.getAttribute(STATE_MESSAGE);
if (alert == null || ((alert != null) && (alert.indexOf(RESOURCE_INVALID_OPERATION_ON_COLLECTION_STRING) == -1)))
{
addAlert(state, RESOURCE_INVALID_OPERATION_ON_COLLECTION_STRING);
}
}
else
{
if (ContentHostingService.allowRemoveResource (cutId))
{
cutIdsVector.add (cutId);
}
else
{
nonCutIds = nonCutIds + " " + properties.getProperty (ResourceProperties.PROP_DISPLAY_NAME) + "; ";
}
}
}
catch (PermissionException e)
{
addAlert(state, rb.getString("notpermis15"));
}
catch (IdUnusedException e)
{
addAlert(state,RESOURCE_NOT_EXIST_STRING);
} // try-catch
}
if (state.getAttribute(STATE_MESSAGE) == null)
{
if (nonCutIds.length ()>0)
{
addAlert(state, rb.getString("notpermis16") +" " + nonCutIds);
}
if (cutIdsVector.size ()>0)
{
state.setAttribute (STATE_CUT_FLAG, Boolean.TRUE.toString());
if (((String) state.getAttribute (STATE_SELECT_ALL_FLAG)).equals (Boolean.TRUE.toString()))
{
state.setAttribute (STATE_SELECT_ALL_FLAG, Boolean.FALSE.toString());
}
Vector copiedIds = (Vector) state.getAttribute (STATE_COPIED_IDS);
for (int i = 0; i < cutIdsVector.size (); i++)
{
String currentId = (String) cutIdsVector.elementAt (i);
if ( copiedIds.contains (currentId))
{
copiedIds.remove (currentId);
}
}
if (copiedIds.size ()==0)
{
state.setAttribute (STATE_COPY_FLAG, Boolean.FALSE.toString());
}
state.setAttribute (STATE_COPIED_IDS, copiedIds);
state.setAttribute (STATE_CUT_IDS, cutIdsVector);
}
}
} // if-else
} // doCut
/**
* set the state name to be "copy" if any item has been selected for copying
*/
public void doCopy ( RunData data )
{
// get the state object
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
// cancel copy if there is one in progress
if(! Boolean.FALSE.toString().equals(state.getAttribute (STATE_COPY_FLAG)))
{
initCopyContext(state);
}
// cancel move if there is one in progress
if(! Boolean.FALSE.toString().equals(state.getAttribute (STATE_MOVE_FLAG)))
{
initMoveContext(state);
}
Vector copyItemsVector = new Vector ();
String[] copyItems = data.getParameters ().getStrings ("selectedMembers");
if (copyItems == null)
{
// there is no resource selected, show the alert message to the user
addAlert(state, rb.getString("choosefile6"));
state.setAttribute (STATE_MODE, MODE_LIST);
}
else
{
String copyId = NULL_STRING;
for (int i = 0; i < copyItems.length; i++)
{
copyId = copyItems[i];
try
{
ResourceProperties properties = ContentHostingService.getProperties (copyId);
/*
if (properties.getProperty (ResourceProperties.PROP_IS_COLLECTION).equals (Boolean.TRUE.toString()))
{
String alert = (String) state.getAttribute(STATE_MESSAGE);
if (alert == null || ((alert != null) && (alert.indexOf(RESOURCE_INVALID_OPERATION_ON_COLLECTION_STRING) == -1)))
{
addAlert(state, RESOURCE_INVALID_OPERATION_ON_COLLECTION_STRING);
}
}
*/
}
catch (PermissionException e)
{
addAlert(state, rb.getString("notpermis15"));
}
catch (IdUnusedException e)
{
addAlert(state,RESOURCE_NOT_EXIST_STRING);
} // try-catch
}
if (state.getAttribute(STATE_MESSAGE) == null)
{
state.setAttribute (STATE_COPY_FLAG, Boolean.TRUE.toString());
copyItemsVector.addAll(Arrays.asList(copyItems));
ContentHostingService.eliminateDuplicates(copyItemsVector);
state.setAttribute (STATE_COPIED_IDS, copyItemsVector);
} // if-else
} // if-else
} // doCopy
/**
* Handle user's selection of items to be moved.
*/
public void doMove ( RunData data )
{
// get the state object
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
List moveItemsVector = new Vector();
// cancel copy if there is one in progress
if(! Boolean.FALSE.toString().equals(state.getAttribute (STATE_COPY_FLAG)))
{
initCopyContext(state);
}
// cancel move if there is one in progress
if(! Boolean.FALSE.toString().equals(state.getAttribute (STATE_MOVE_FLAG)))
{
initMoveContext(state);
}
state.setAttribute(STATE_LIST_SELECTIONS, new TreeSet());
String[] moveItems = data.getParameters ().getStrings ("selectedMembers");
if (moveItems == null)
{
// there is no resource selected, show the alert message to the user
addAlert(state, rb.getString("choosefile6"));
state.setAttribute (STATE_MODE, MODE_LIST);
}
else
{
String moveId = NULL_STRING;
for (int i = 0; i < moveItems.length; i++)
{
moveId = moveItems[i];
try
{
ResourceProperties properties = ContentHostingService.getProperties (moveId);
/*
if (properties.getProperty (ResourceProperties.PROP_IS_COLLECTION).equals (Boolean.TRUE.toString()))
{
String alert = (String) state.getAttribute(STATE_MESSAGE);
if (alert == null || ((alert != null) && (alert.indexOf(RESOURCE_INVALID_OPERATION_ON_COLLECTION_STRING) == -1)))
{
addAlert(state, RESOURCE_INVALID_OPERATION_ON_COLLECTION_STRING);
}
}
*/
}
catch (PermissionException e)
{
addAlert(state, rb.getString("notpermis15"));
}
catch (IdUnusedException e)
{
addAlert(state,RESOURCE_NOT_EXIST_STRING);
} // try-catch
}
if (state.getAttribute(STATE_MESSAGE) == null)
{
state.setAttribute (STATE_MOVE_FLAG, Boolean.TRUE.toString());
moveItemsVector.addAll(Arrays.asList(moveItems));
ContentHostingService.eliminateDuplicates(moveItemsVector);
state.setAttribute (STATE_MOVED_IDS, moveItemsVector);
} // if-else
} // if-else
} // doMove
/**
* If copy-flag is set to false, erase the copied-id's list and set copied flags to false
* in all the browse items. If copied-id's list is empty, set copy-flag to false and set
* copied flags to false in all the browse items. If copy-flag is set to true and copied-id's
* list is not empty, update the copied flags of all browse items so copied flags for the
* copied items are set to true and all others are set to false.
*/
protected void setCopyFlags(SessionState state)
{
String copyFlag = (String) state.getAttribute(STATE_COPY_FLAG);
List copyItemsVector = (List) state.getAttribute(STATE_COPIED_IDS);
if(copyFlag == null)
{
copyFlag = Boolean.FALSE.toString();
state.setAttribute(STATE_COPY_FLAG, copyFlag);
}
if(copyFlag.equals(Boolean.TRUE.toString()))
{
if(copyItemsVector == null)
{
copyItemsVector = new Vector();
state.setAttribute(STATE_COPIED_IDS, copyItemsVector);
}
if(copyItemsVector.isEmpty())
{
state.setAttribute(STATE_COPY_FLAG, Boolean.FALSE.toString());
}
}
else
{
copyItemsVector = new Vector();
state.setAttribute(STATE_COPIED_IDS, copyItemsVector);
}
List roots = (List) state.getAttribute(STATE_COLLECTION_ROOTS);
Iterator rootIt = roots.iterator();
while(rootIt.hasNext())
{
BrowseItem root = (BrowseItem) rootIt.next();
boolean root_copied = copyItemsVector.contains(root.getId());
root.setCopied(root_copied);
List members = root.getMembers();
Iterator memberIt = members.iterator();
while(memberIt.hasNext())
{
BrowseItem member = (BrowseItem) memberIt.next();
boolean member_copied = copyItemsVector.contains(member.getId());
member.setCopied(member_copied);
}
}
// check -- jim
state.setAttribute(STATE_COLLECTION_ROOTS, roots);
} // setCopyFlags
/**
* Expand all the collection resources.
*/
static public void doExpandall ( RunData data)
{
// get the state object
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
//get the ParameterParser from RunData
ParameterParser params = data.getParameters ();
// save the current selections
Set selectedSet = new TreeSet();
String[] selectedItems = params.getStrings("selectedMembers");
if(selectedItems != null)
{
selectedSet.addAll(Arrays.asList(selectedItems));
}
state.setAttribute(STATE_LIST_SELECTIONS, selectedSet);
// expansion actually occurs in getBrowseItems method.
state.setAttribute(STATE_EXPAND_ALL_FLAG, Boolean.TRUE.toString());
state.setAttribute(STATE_NEED_TO_EXPAND_ALL, Boolean.TRUE.toString());
} // doExpandall
/**
* Unexpand all the collection resources
*/
public static void doUnexpandall ( RunData data)
{
// get the state object
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
//get the ParameterParser from RunData
ParameterParser params = data.getParameters ();
// save the current selections
Set selectedSet = new TreeSet();
String[] selectedItems = params.getStrings ("selectedMembers");
if(selectedItems != null)
{
selectedSet.addAll(Arrays.asList(selectedItems));
}
state.setAttribute(STATE_LIST_SELECTIONS, selectedSet);
state.setAttribute(STATE_EXPANDED_COLLECTIONS, new HashMap());
state.setAttribute(STATE_EXPAND_ALL_FLAG, Boolean.FALSE.toString());
} // doUnexpandall
/**
* Populate the state object, if needed - override to do something!
*/
protected void initState(SessionState state, VelocityPortlet portlet, JetspeedRunData data)
{
super.initState(state, portlet, data);
if(state.getAttribute(STATE_INITIALIZED) == null)
{
initCopyContext(state);
initMoveContext(state);
}
initStateAttributes(state, portlet);
} // initState
/**
* Remove the state variables used internally, on the way out.
*/
static private void cleanupState(SessionState state)
{
state.removeAttribute(STATE_FROM_TEXT);
state.removeAttribute(STATE_HAS_ATTACHMENT_BEFORE);
state.removeAttribute(STATE_ATTACH_SHOW_DROPBOXES);
state.removeAttribute(STATE_ATTACH_COLLECTION_ID);
state.removeAttribute(COPYRIGHT_FAIRUSE_URL);
state.removeAttribute(COPYRIGHT_NEW_COPYRIGHT);
state.removeAttribute(COPYRIGHT_SELF_COPYRIGHT);
state.removeAttribute(COPYRIGHT_TYPES);
state.removeAttribute(DEFAULT_COPYRIGHT_ALERT);
state.removeAttribute(DEFAULT_COPYRIGHT);
state.removeAttribute(STATE_EXPANDED_COLLECTIONS);
state.removeAttribute(STATE_FILE_UPLOAD_MAX_SIZE);
state.removeAttribute(NEW_COPYRIGHT_INPUT);
state.removeAttribute(STATE_COLLECTION_ID);
state.removeAttribute(STATE_COLLECTION_PATH);
state.removeAttribute(STATE_CONTENT_SERVICE);
state.removeAttribute(STATE_CONTENT_TYPE_IMAGE_SERVICE);
//state.removeAttribute(STATE_STACK_EDIT_INTENT);
state.removeAttribute(STATE_EXPAND_ALL_FLAG);
state.removeAttribute(STATE_HELPER_NEW_ITEMS);
state.removeAttribute(STATE_HELPER_CHANGED);
state.removeAttribute(STATE_HOME_COLLECTION_DISPLAY_NAME);
state.removeAttribute(STATE_HOME_COLLECTION_ID);
state.removeAttribute(STATE_LIST_SELECTIONS);
state.removeAttribute(STATE_MY_COPYRIGHT);
state.removeAttribute(STATE_NAVIGATION_ROOT);
state.removeAttribute(STATE_PASTE_ALLOWED_FLAG);
state.removeAttribute(STATE_SELECT_ALL_FLAG);
state.removeAttribute(STATE_SHOW_ALL_SITES);
state.removeAttribute(STATE_SITE_TITLE);
state.removeAttribute(STATE_SORT_ASC);
state.removeAttribute(STATE_SORT_BY);
state.removeAttribute(STATE_STACK_STRUCTOBJ_TYPE);
state.removeAttribute(STATE_STACK_STRUCTOBJ_TYPE_READONLY);
state.removeAttribute(STATE_INITIALIZED);
state.removeAttribute(VelocityPortletPaneledAction.STATE_HELPER);
} // cleanupState
public static void initStateAttributes(SessionState state, VelocityPortlet portlet)
{
if (state.getAttribute (STATE_INITIALIZED) != null) return;
if (state.getAttribute(STATE_FILE_UPLOAD_MAX_SIZE) == null)
{
state.setAttribute(STATE_FILE_UPLOAD_MAX_SIZE, ServerConfigurationService.getString("content.upload.max", "1"));
}
PortletConfig config = portlet.getPortletConfig();
try
{
Integer size = new Integer(config.getInitParameter(PARAM_PAGESIZE));
if(size == null || size.intValue() < 1)
{
size = new Integer(DEFAULT_PAGE_SIZE);
}
state.setAttribute(STATE_PAGESIZE, size);
}
catch(Exception any)
{
state.setAttribute(STATE_PAGESIZE, new Integer(DEFAULT_PAGE_SIZE));
}
// state.setAttribute(STATE_TOP_PAGE_MESSAGE, "");
state.setAttribute (STATE_CONTENT_SERVICE, ContentHostingService.getInstance());
state.setAttribute (STATE_CONTENT_TYPE_IMAGE_SERVICE, ContentTypeImageService.getInstance());
TimeBreakdown timeBreakdown = (TimeService.newTime()).breakdownLocal ();
String mycopyright = COPYRIGHT_SYMBOL + " " + timeBreakdown.getYear () +", " + UserDirectoryService.getCurrentUser().getDisplayName () + ". All Rights Reserved. ";
state.setAttribute (STATE_MY_COPYRIGHT, mycopyright);
if(state.getAttribute(STATE_MODE) == null)
{
state.setAttribute (STATE_MODE, MODE_LIST);
state.setAttribute (STATE_FROM, NULL_STRING);
}
state.setAttribute (STATE_SORT_BY, ResourceProperties.PROP_DISPLAY_NAME);
state.setAttribute (STATE_SORT_ASC, Boolean.TRUE.toString());
state.setAttribute (STATE_SELECT_ALL_FLAG, Boolean.FALSE.toString());
state.setAttribute (STATE_EXPAND_ALL_FLAG, Boolean.FALSE.toString());
state.setAttribute(STATE_LIST_SELECTIONS, new TreeSet());
state.setAttribute (STATE_COLLECTION_PATH, new Vector ());
// %%STATE_MODE_RESOURCES%%
// In helper mode, calling tool should set attribute STATE_MODE_RESOURCES
String resources_mode = (String) state.getAttribute(STATE_MODE_RESOURCES);
if(resources_mode == null)
{
// get resources mode from tool registry
resources_mode = portlet.getPortletConfig().getInitParameter("resources_mode");
if(resources_mode != null)
{
state.setAttribute(STATE_MODE_RESOURCES, resources_mode);
}
}
boolean show_other_sites = false;
if(RESOURCES_MODE_HELPER.equals(resources_mode))
{
show_other_sites = ServerConfigurationService.getBoolean("resources.show_all_collections.helper", SHOW_ALL_SITES_IN_FILE_PICKER);
}
else if(RESOURCES_MODE_DROPBOX.equals(resources_mode))
{
show_other_sites = ServerConfigurationService.getBoolean("resources.show_all_collections.dropbox", SHOW_ALL_SITES_IN_DROPBOX);
}
else
{
show_other_sites = ServerConfigurationService.getBoolean("resources.show_all_collections.tool", SHOW_ALL_SITES_IN_RESOURCES);
}
/** This attribute indicates whether "Other Sites" twiggle should show */
state.setAttribute(STATE_SHOW_ALL_SITES, Boolean.toString(show_other_sites));
/** This attribute indicates whether "Other Sites" twiggle should be open */
state.setAttribute(STATE_SHOW_OTHER_SITES, Boolean.FALSE.toString());
// set the home collection to the parameter, if present, or the default if not
String home = StringUtil.trimToNull(portlet.getPortletConfig().getInitParameter("home"));
state.setAttribute (STATE_HOME_COLLECTION_DISPLAY_NAME, home);
if ((home == null) || (home.length() == 0))
{
// no home set, see if we are in dropbox mode
if (RESOURCES_MODE_DROPBOX.equalsIgnoreCase(resources_mode))
{
home = ContentHostingService.getDropboxCollection();
// if it came back null, we will pretend not to be in dropbox mode
if (home != null)
{
state.setAttribute(STATE_HOME_COLLECTION_DISPLAY_NAME, ContentHostingService.getDropboxDisplayName());
// create/update the collection of folders in the dropbox
ContentHostingService.createDropboxCollection();
}
}
// if we still don't have a home,
if ((home == null) || (home.length() == 0))
{
home = ContentHostingService.getSiteCollection(ToolManager.getCurrentPlacement().getContext());
// TODO: what's the 'name' of the context? -ggolden
// we'll need this to create the home collection if needed
state.setAttribute (STATE_HOME_COLLECTION_DISPLAY_NAME, ToolManager.getCurrentPlacement().getContext()
/*SiteService.getSiteDisplay(ToolManager.getCurrentPlacement().getContext()) */);
}
}
state.setAttribute (STATE_HOME_COLLECTION_ID, home);
state.setAttribute (STATE_COLLECTION_ID, home);
state.setAttribute (STATE_NAVIGATION_ROOT, home);
HomeFactory factory = (HomeFactory) ComponentManager.get("homeFactory");
if(factory != null)
{
Map homes = factory.getHomes(StructuredArtifactHomeInterface.class);
if(! homes.isEmpty())
{
state.setAttribute(STATE_SHOW_FORM_ITEMS, Boolean.TRUE.toString());
}
}
// state.setAttribute (STATE_COLLECTION_ID, state.getAttribute (STATE_HOME_COLLECTION_ID));
if (state.getAttribute(STATE_SITE_TITLE) == null)
{
String title = "";
try
{
title = ((Site) SiteService.getSite(ToolManager.getCurrentPlacement().getContext())).getTitle();
}
catch (IdUnusedException e)
{ // ignore
}
state.setAttribute(STATE_SITE_TITLE, title);
}
HashMap expandedCollections = new HashMap();
//expandedCollections.add (state.getAttribute (STATE_HOME_COLLECTION_ID));
state.setAttribute(STATE_EXPANDED_COLLECTIONS, expandedCollections);
if(state.getAttribute(STATE_USING_CREATIVE_COMMONS) == null)
{
String usingCreativeCommons = ServerConfigurationService.getString("copyright.use_creative_commons");
if( usingCreativeCommons != null && usingCreativeCommons.equalsIgnoreCase(Boolean.TRUE.toString()))
{
state.setAttribute(STATE_USING_CREATIVE_COMMONS, Boolean.TRUE.toString());
}
else
{
state.setAttribute(STATE_USING_CREATIVE_COMMONS, Boolean.FALSE.toString());
}
}
if (state.getAttribute(COPYRIGHT_TYPES) == null)
{
if (ServerConfigurationService.getStrings("copyrighttype") != null)
{
state.setAttribute(COPYRIGHT_TYPES, new ArrayList(Arrays.asList(ServerConfigurationService.getStrings("copyrighttype"))));
}
}
if (state.getAttribute(DEFAULT_COPYRIGHT) == null)
{
if (ServerConfigurationService.getString("default.copyright") != null)
{
state.setAttribute(DEFAULT_COPYRIGHT, ServerConfigurationService.getString("default.copyright"));
}
}
if (state.getAttribute(DEFAULT_COPYRIGHT_ALERT) == null)
{
if (ServerConfigurationService.getString("default.copyright.alert") != null)
{
state.setAttribute(DEFAULT_COPYRIGHT_ALERT, ServerConfigurationService.getString("default.copyright.alert"));
}
}
if (state.getAttribute(NEW_COPYRIGHT_INPUT) == null)
{
if (ServerConfigurationService.getString("newcopyrightinput") != null)
{
state.setAttribute(NEW_COPYRIGHT_INPUT, ServerConfigurationService.getString("newcopyrightinput"));
}
}
if (state.getAttribute(COPYRIGHT_FAIRUSE_URL) == null)
{
if (ServerConfigurationService.getString("fairuse.url") != null)
{
state.setAttribute(COPYRIGHT_FAIRUSE_URL, ServerConfigurationService.getString("fairuse.url"));
}
}
if (state.getAttribute(COPYRIGHT_SELF_COPYRIGHT) == null)
{
if (ServerConfigurationService.getString("copyrighttype.own") != null)
{
state.setAttribute(COPYRIGHT_SELF_COPYRIGHT, ServerConfigurationService.getString("copyrighttype.own"));
}
}
if (state.getAttribute(COPYRIGHT_NEW_COPYRIGHT) == null)
{
if (ServerConfigurationService.getString("copyrighttype.new") != null)
{
state.setAttribute(COPYRIGHT_NEW_COPYRIGHT, ServerConfigurationService.getString("copyrighttype.new"));
}
}
// get resources mode from tool registry
String optional_properties = portlet.getPortletConfig().getInitParameter("optional_properties");
if(optional_properties != null && "true".equalsIgnoreCase(optional_properties))
{
initMetadataContext(state);
}
state.setAttribute(STATE_PREVENT_PUBLIC_DISPLAY, Boolean.FALSE);
String[] siteTypes = ServerConfigurationService.getStrings("prevent.public.resources");
if(siteTypes != null)
{
Site site;
try
{
site = SiteService.getSite(ToolManager.getCurrentPlacement().getContext());
for(int i = 0; i < siteTypes.length; i++)
{
if ((StringUtil.trimToNull(siteTypes[i])).equals(site.getType()))
{
state.setAttribute(STATE_PREVENT_PUBLIC_DISPLAY, Boolean.TRUE);
}
}
}
catch (IdUnusedException e)
{
// allow public display
}
catch(NullPointerException e)
{
// allow public display
}
}
state.setAttribute (STATE_INITIALIZED, Boolean.TRUE.toString());
}
/**
* Setup our observer to be watching for change events for the collection
*/
private void updateObservation(SessionState state, String peid)
{
// ContentObservingCourier observer = (ContentObservingCourier) state.getAttribute(STATE_OBSERVER);
//
// // the delivery location for this tool
// String deliveryId = clientWindowId(state, peid);
// observer.setDeliveryId(deliveryId);
}
/**
* Add additional resource pattern to the observer
*@param pattern The pattern value to be added
*@param state The state object
*/
private static void addObservingPattern(String pattern, SessionState state)
{
// // get the observer and add the pattern
// ContentObservingCourier o = (ContentObservingCourier) state.getAttribute(STATE_OBSERVER);
// o.addResourcePattern(ContentHostingService.getReference(pattern));
//
// // add it back to state
// state.setAttribute(STATE_OBSERVER, o);
} // addObservingPattern
/**
* Remove a resource pattern from the observer
*@param pattern The pattern value to be removed
*@param state The state object
*/
private static void removeObservingPattern(String pattern, SessionState state)
{
// // get the observer and remove the pattern
// ContentObservingCourier o = (ContentObservingCourier) state.getAttribute(STATE_OBSERVER);
// o.removeResourcePattern(ContentHostingService.getReference(pattern));
//
// // add it back to state
// state.setAttribute(STATE_OBSERVER, o);
} // removeObservingPattern
/**
* initialize the copy context
*/
private static void initCopyContext (SessionState state)
{
state.setAttribute (STATE_COPIED_IDS, new Vector ());
state.setAttribute (STATE_COPY_FLAG, Boolean.FALSE.toString());
} // initCopyContent
/**
* initialize the copy context
*/
private static void initMoveContext (SessionState state)
{
state.setAttribute (STATE_MOVED_IDS, new Vector ());
state.setAttribute (STATE_MOVE_FLAG, Boolean.FALSE.toString());
} // initCopyContent
/**
* initialize the cut context
*/
private void initCutContext (SessionState state)
{
state.setAttribute (STATE_CUT_IDS, new Vector ());
state.setAttribute (STATE_CUT_FLAG, Boolean.FALSE.toString());
} // initCutContent
/**
* find out whether there is a duplicate item in testVector
* @param testVector The Vector to be tested on
* @param testSize The integer of the test range
* @return The index value of the duplicate ite
*/
private int repeatedName (Vector testVector, int testSize)
{
for (int i=1; i <= testSize; i++)
{
String currentName = (String) testVector.get (i);
for (int j=i+1; j <= testSize; j++)
{
String comparedTitle = (String) testVector.get (j);
if (comparedTitle.length()>0 && currentName.length()>0 && comparedTitle.equals (currentName))
{
return j;
}
}
}
return 0;
} // repeatedName
/**
* Is the id already exist in the current resource?
* @param testVector The Vector to be tested on
* @param testSize The integer of the test range
* @parma isCollection Looking for collection or not
* @return The index value of the exist id
*/
private int foundInResource (Vector testVector, int testSize, String collectionId, boolean isCollection)
{
try
{
ContentCollection c = ContentHostingService.getCollection(collectionId);
Iterator membersIterator = c.getMemberResources().iterator();
while (membersIterator.hasNext())
{
ResourceProperties p = ((Entity) membersIterator.next()).getProperties();
String displayName = p.getProperty(ResourceProperties.PROP_DISPLAY_NAME);
if (displayName != null)
{
String collectionOrResource = p.getProperty(ResourceProperties.PROP_IS_COLLECTION);
for (int i=1; i <= testSize; i++)
{
String testName = (String) testVector.get(i);
if ((testName != null) && (displayName.equals (testName))
&& ((isCollection && collectionOrResource.equals (Boolean.TRUE.toString()))
|| (!isCollection && collectionOrResource.equals(Boolean.FALSE.toString()))))
{
return i;
}
} // for
}
}
}
catch (IdUnusedException e){}
catch (TypeException e){}
catch (PermissionException e){}
return 0;
} // foundInResource
/**
* empty String Vector object with the size sepecified
* @param size The Vector object size -1
* @return The Vector object consists of null Strings
*/
private static Vector emptyVector (int size)
{
Vector v = new Vector ();
for (int i=0; i <= size; i++)
{
v.add (i, "");
}
return v;
} // emptyVector
/**
* Setup for customization
**/
public String buildOptionsPanelContext( VelocityPortlet portlet,
Context context,
RunData data,
SessionState state)
{
context.put("tlang",rb);
String home = (String) state.getAttribute(STATE_HOME_COLLECTION_ID);
Reference ref = EntityManager.newReference(ContentHostingService.getReference(home));
String siteId = ref.getContext();
context.put("form-submit", BUTTON + "doConfigure_update");
context.put("form-cancel", BUTTON + "doCancel_options");
context.put("description", "Setting options for Resources in worksite "
+ SiteService.getSiteDisplay(siteId));
// pick the "-customize" template based on the standard template name
String template = (String)getContext(data).get("template");
return template + "-customize";
} // buildOptionsPanelContext
/**
* Handle the configure context's update button
*/
public void doConfigure_update(RunData data, Context context)
{
// access the portlet element id to find our state
String peid = ((JetspeedRunData)data).getJs_peid();
SessionState state = ((JetspeedRunData)data).getPortletSessionState(peid);
// we are done with customization... back to the main (browse) mode
state.setAttribute(STATE_MODE, MODE_LIST);
// commit the change
// saveOptions();
cancelOptions();
} // doConfigure_update
/**
* doCancel_options called for form input tags type="submit" named="eventSubmit_doCancel"
* cancel the options process
*/
public void doCancel_options(RunData data, Context context)
{
// access the portlet element id to find our state
String peid = ((JetspeedRunData)data).getJs_peid();
SessionState state = ((JetspeedRunData)data).getPortletSessionState(peid);
// cancel the options
cancelOptions();
// we are done with customization... back to the main (MODE_LIST) mode
state.setAttribute(STATE_MODE, MODE_LIST);
} // doCancel_options
/**
* Add the collection id into the expanded collection list
* @throws PermissionException
* @throws TypeException
* @throws IdUnusedException
*/
public static void doExpand_collection(RunData data) throws IdUnusedException, TypeException, PermissionException
{
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
HashMap currentMap = (HashMap) state.getAttribute(STATE_EXPANDED_COLLECTIONS);
//get the ParameterParser from RunData
ParameterParser params = data.getParameters ();
// save the current selections
Set selectedSet = new TreeSet();
String[] selectedItems = params.getStrings ("selectedMembers");
if(selectedItems != null)
{
selectedSet.addAll(Arrays.asList(selectedItems));
}
state.setAttribute(STATE_LIST_SELECTIONS, selectedSet);
String id = params.getString("collectionId");
currentMap.put (id,ContentHostingService.getCollection (id));
state.setAttribute(STATE_EXPANDED_COLLECTIONS, currentMap);
// add this folder id into the set to be event-observed
addObservingPattern(id, state);
} // doExpand_collection
/**
* Remove the collection id from the expanded collection list
*/
static public void doCollapse_collection(RunData data)
{
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
HashMap currentMap = (HashMap) state.getAttribute(STATE_EXPANDED_COLLECTIONS);
//get the ParameterParser from RunData
ParameterParser params = data.getParameters ();
String collectionId = params.getString("collectionId");
// save the current selections
Set selectedSet = new TreeSet();
String[] selectedItems = data.getParameters ().getStrings ("selectedMembers");
if(selectedItems != null)
{
selectedSet.addAll(Arrays.asList(selectedItems));
}
state.setAttribute(STATE_LIST_SELECTIONS, selectedSet);
HashMap newSet = new HashMap();
Iterator l = currentMap.keySet().iterator ();
while (l.hasNext ())
{
// remove the collection id and all of the subcollections
// Resource collection = (Resource) l.next();
// String id = (String) collection.getId();
String id = (String) l.next();
if (id.indexOf (collectionId)==-1)
{
// newSet.put(id,collection);
newSet.put(id,currentMap.get(id));
}
}
state.setAttribute(STATE_EXPANDED_COLLECTIONS, newSet);
// remove this folder id into the set to be event-observed
removeObservingPattern(collectionId, state);
} // doCollapse_collection
/**
* @param state
* @param homeCollectionId
* @param currentCollectionId
* @return
*/
public static List getCollectionPath(SessionState state)
{
org.sakaiproject.content.api.ContentHostingService contentService = (org.sakaiproject.content.api.ContentHostingService) state.getAttribute (STATE_CONTENT_SERVICE);
// make sure the channedId is set
String currentCollectionId = (String) state.getAttribute (STATE_COLLECTION_ID);
if(! isStackEmpty(state))
{
Map current_stack_frame = peekAtStack(state);
String createCollectionId = (String) current_stack_frame.get(STATE_STACK_CREATE_COLLECTION_ID);
if(createCollectionId == null)
{
createCollectionId = (String) state.getAttribute(STATE_CREATE_COLLECTION_ID);
}
if(createCollectionId != null)
{
currentCollectionId = createCollectionId;
}
else
{
String editCollectionId = (String) current_stack_frame.get(STATE_EDIT_COLLECTION_ID);
if(editCollectionId == null)
{
editCollectionId = (String) state.getAttribute(STATE_EDIT_COLLECTION_ID);
}
if(editCollectionId != null)
{
currentCollectionId = editCollectionId;
}
}
}
String homeCollectionId = (String) state.getAttribute(STATE_HOME_COLLECTION_ID);
String navRoot = (String) state.getAttribute(STATE_NAVIGATION_ROOT);
LinkedList collectionPath = new LinkedList();
String previousCollectionId = "";
Vector pathitems = new Vector();
while(currentCollectionId != null && ! currentCollectionId.equals(navRoot) && ! currentCollectionId.equals(previousCollectionId))
{
pathitems.add(currentCollectionId);
previousCollectionId = currentCollectionId;
currentCollectionId = contentService.getContainingCollectionId(currentCollectionId);
}
pathitems.add(navRoot);
if(!navRoot.equals(homeCollectionId))
{
pathitems.add(homeCollectionId);
}
Iterator items = pathitems.iterator();
while(items.hasNext())
{
String id = (String) items.next();
try
{
ResourceProperties props = contentService.getProperties(id);
String name = props.getPropertyFormatted(ResourceProperties.PROP_DISPLAY_NAME);
PathItem item = new PathItem(id, name);
boolean canRead = contentService.allowGetCollection(id) || contentService.allowGetResource(id);
item.setCanRead(canRead);
String url = contentService.getUrl(id);
item.setUrl(url);
item.setLast(collectionPath.isEmpty());
if(id.equals(homeCollectionId))
{
item.setRoot(homeCollectionId);
}
else
{
item.setRoot(navRoot);
}
try
{
boolean isFolder = props.getBooleanProperty(ResourceProperties.PROP_IS_COLLECTION);
item.setIsFolder(isFolder);
}
catch (EntityPropertyNotDefinedException e1)
{
}
catch (EntityPropertyTypeException e1)
{
}
collectionPath.addFirst(item);
}
catch (PermissionException e)
{
}
catch (IdUnusedException e)
{
}
}
return collectionPath;
}
/**
* Get the items in this folder that should be seen.
* @param collectionId - String version of
* @param expandedCollections - Hash of collection resources
* @param sortedBy - pass through to ContentHostingComparator
* @param sortedAsc - pass through to ContentHostingComparator
* @param parent - The folder containing this item
* @param isLocal - true if navigation root and home collection id of site are the same, false otherwise
* @param state - The session state
* @return a List of BrowseItem objects
*/
protected static List getBrowseItems(String collectionId, HashMap expandedCollections, Set highlightedItems, String sortedBy, String sortedAsc, BrowseItem parent, boolean isLocal, SessionState state)
{
boolean need_to_expand_all = Boolean.TRUE.toString().equals((String)state.getAttribute(STATE_NEED_TO_EXPAND_ALL));
List newItems = new LinkedList();
try
{
// find the ContentHosting service
org.sakaiproject.content.api.ContentHostingService contentService = (org.sakaiproject.content.api.ContentHostingService) state.getAttribute (STATE_CONTENT_SERVICE);
// get the collection
// try using existing resource first
ContentCollection collection = null;
// get the collection
if (expandedCollections.containsKey(collectionId))
{
collection = (ContentCollection) expandedCollections.get(collectionId);
}
else
{
collection = ContentHostingService.getCollection(collectionId);
if(need_to_expand_all)
{
expandedCollections.put(collectionId, collection);
state.setAttribute(STATE_EXPANDED_COLLECTIONS, expandedCollections);
}
}
String dummyId = collectionId.trim();
if(dummyId.endsWith(Entity.SEPARATOR))
{
dummyId += "dummy";
}
else
{
dummyId += Entity.SEPARATOR + "dummy";
}
boolean canRead = false;
boolean canDelete = false;
boolean canRevise = false;
boolean canAddFolder = false;
boolean canAddItem = false;
boolean canUpdate = false;
int depth = 0;
if(parent == null || ! parent.canRead())
{
canRead = contentService.allowGetCollection(collectionId);
}
else
{
canRead = parent.canRead();
}
if(parent == null || ! parent.canDelete())
{
canDelete = contentService.allowRemoveResource(collectionId);
}
else
{
canDelete = parent.canDelete();
}
if(parent == null || ! parent.canRevise())
{
canRevise = contentService.allowUpdateResource(collectionId);
}
else
{
canRevise = parent.canRevise();
}
if(parent == null || ! parent.canAddFolder())
{
canAddFolder = contentService.allowAddCollection(dummyId);
}
else
{
canAddFolder = parent.canAddFolder();
}
if(parent == null || ! parent.canAddItem())
{
canAddItem = contentService.allowAddResource(dummyId);
}
else
{
canAddItem = parent.canAddItem();
}
if(parent == null || ! parent.canUpdate())
{
canUpdate = AuthzGroupService.allowUpdate(collectionId);
}
else
{
canUpdate = parent.canUpdate();
}
if(parent != null)
{
depth = parent.getDepth() + 1;
}
if(canAddItem)
{
state.setAttribute(STATE_PASTE_ALLOWED_FLAG, Boolean.TRUE.toString());
}
boolean hasDeletableChildren = canDelete;
boolean hasCopyableChildren = canRead;
String homeCollectionId = (String) state.getAttribute(STATE_HOME_COLLECTION_ID);
ResourceProperties cProperties = collection.getProperties();
String folderName = cProperties.getProperty(ResourceProperties.PROP_DISPLAY_NAME);
if(collectionId.equals(homeCollectionId))
{
folderName = (String) state.getAttribute(STATE_HOME_COLLECTION_DISPLAY_NAME);
}
BrowseItem folder = new BrowseItem(collectionId, folderName, "folder");
if(parent == null)
{
folder.setRoot(collectionId);
}
else
{
folder.setRoot(parent.getRoot());
}
BasicRightsAssignment rightsObj = new BasicRightsAssignment(folder.getItemNum(), cProperties);
folder.setRights(rightsObj);
AccessMode access = collection.getAccess();
if(access == null || AccessMode.SITE.equals(access))
{
folder.setAccess(AccessMode.INHERITED.toString());
}
else
{
folder.setAccess(access.toString());
}
AccessMode inherited_access = collection.getInheritedAccess();
if(inherited_access == null || AccessMode.SITE.equals(inherited_access))
{
folder.setInheritedAccess(AccessMode.INHERITED.toString());
}
else
{
folder.setInheritedAccess(inherited_access.toString());
}
Collection access_groups = collection.getGroupObjects();
if(access_groups == null)
{
access_groups = new Vector();
}
Collection inherited_access_groups = collection.getInheritedGroupObjects();
if(inherited_access_groups == null)
{
inherited_access_groups = new Vector();
}
folder.setInheritedGroups(access_groups);
if(highlightedItems == null || highlightedItems.isEmpty())
{
// do nothing
}
else if(parent != null && parent.isHighlighted())
{
folder.setInheritsHighlight(true);
folder.setHighlighted(true);
}
else if(highlightedItems.contains(collectionId))
{
folder.setHighlighted(true);
folder.setInheritsHighlight(false);
}
String containerId = contentService.getContainingCollectionId (collectionId);
folder.setContainer(containerId);
folder.setCanRead(canRead);
folder.setCanRevise(canRevise);
folder.setCanAddItem(canAddItem);
folder.setCanAddFolder(canAddFolder);
folder.setCanDelete(canDelete);
folder.setCanUpdate(canUpdate);
try
{
Time createdTime = cProperties.getTimeProperty(ResourceProperties.PROP_CREATION_DATE);
String createdTimeString = createdTime.toStringLocalShortDate();
folder.setCreatedTime(createdTimeString);
}
catch(Exception e)
{
String createdTimeString = cProperties.getProperty(ResourceProperties.PROP_CREATION_DATE);
folder.setCreatedTime(createdTimeString);
}
try
{
String createdBy = getUserProperty(cProperties, ResourceProperties.PROP_CREATOR).getDisplayName();
folder.setCreatedBy(createdBy);
}
catch(Exception e)
{
String createdBy = cProperties.getProperty(ResourceProperties.PROP_CREATOR);
folder.setCreatedBy(createdBy);
}
try
{
Time modifiedTime = cProperties.getTimeProperty(ResourceProperties.PROP_MODIFIED_DATE);
String modifiedTimeString = modifiedTime.toStringLocalShortDate();
folder.setModifiedTime(modifiedTimeString);
}
catch(Exception e)
{
String modifiedTimeString = cProperties.getProperty(ResourceProperties.PROP_MODIFIED_DATE);
folder.setModifiedTime(modifiedTimeString);
}
try
{
String modifiedBy = getUserProperty(cProperties, ResourceProperties.PROP_MODIFIED_BY).getDisplayName();
folder.setModifiedBy(modifiedBy);
}
catch(Exception e)
{
String modifiedBy = cProperties.getProperty(ResourceProperties.PROP_MODIFIED_BY);
folder.setModifiedBy(modifiedBy);
}
String url = contentService.getUrl(collectionId);
folder.setUrl(url);
try
{
int collection_size = contentService.getCollectionSize(collectionId);
folder.setIsEmpty(collection_size < 1);
folder.setIsTooBig(collection_size > EXPANDABLE_FOLDER_SIZE_LIMIT);
}
catch(RuntimeException e)
{
folder.setIsEmpty(true);
folder.setIsTooBig(false);
}
folder.setDepth(depth);
newItems.add(folder);
if(need_to_expand_all || expandedCollections.containsKey (collectionId))
{
// Get the collection members from the 'new' collection
List newMembers = collection.getMemberResources ();
Collections.sort (newMembers, ContentHostingService.newContentHostingComparator (sortedBy, Boolean.valueOf (sortedAsc).booleanValue ()));
// loop thru the (possibly) new members and add to the list
Iterator it = newMembers.iterator();
while(it.hasNext())
{
ContentEntity resource = (ContentEntity) it.next();
ResourceProperties props = resource.getProperties();
String itemId = resource.getId();
if(resource.isCollection())
{
List offspring = getBrowseItems(itemId, expandedCollections, highlightedItems, sortedBy, sortedAsc, folder, isLocal, state);
if(! offspring.isEmpty())
{
BrowseItem child = (BrowseItem) offspring.get(0);
hasDeletableChildren = hasDeletableChildren || child.hasDeletableChildren();
hasCopyableChildren = hasCopyableChildren || child.hasCopyableChildren();
}
// add all the items in the subfolder to newItems
newItems.addAll(offspring);
}
else
{
String itemType = ((ContentResource)resource).getContentType();
String itemName = props.getProperty(ResourceProperties.PROP_DISPLAY_NAME);
BrowseItem newItem = new BrowseItem(itemId, itemName, itemType);
BasicRightsAssignment rightsObj2 = new BasicRightsAssignment(newItem.getItemNum(), props);
newItem.setRights(rightsObj2);
AccessMode access_mode = ((GroupAwareEntity) resource).getAccess();
if(access_mode == null)
{
newItem.setAccess(AccessMode.SITE.toString());
}
else
{
newItem.setAccess(access_mode.toString());
}
Collection groups = ((GroupAwareEntity) resource).getGroupObjects();
if(groups == null)
{
groups = new Vector();
}
Collection inheritedGroups = ((GroupAwareEntity) resource).getInheritedGroupObjects();
if(inheritedGroups == null)
{
inheritedGroups = new Vector();
}
newItem.setGroups(groups);
newItem.setInheritedGroups(inheritedGroups);
newItem.setContainer(collectionId);
newItem.setRoot(folder.getRoot());
newItem.setCanDelete(canDelete);
newItem.setCanRevise(canRevise);
newItem.setCanRead(canRead);
newItem.setCanCopy(canRead);
newItem.setCanAddItem(canAddItem); // true means this user can add an item in the folder containing this item (used for "duplicate")
if(highlightedItems == null || highlightedItems.isEmpty())
{
// do nothing
}
else if(folder.isHighlighted())
{
newItem.setInheritsHighlight(true);
newItem.setHighlighted(true);
}
else if(highlightedItems.contains(itemId))
{
newItem.setHighlighted(true);
newItem.setInheritsHighlight(false);
}
try
{
Time createdTime = props.getTimeProperty(ResourceProperties.PROP_CREATION_DATE);
String createdTimeString = createdTime.toStringLocalShortDate();
newItem.setCreatedTime(createdTimeString);
}
catch(Exception e)
{
String createdTimeString = props.getProperty(ResourceProperties.PROP_CREATION_DATE);
newItem.setCreatedTime(createdTimeString);
}
try
{
String createdBy = getUserProperty(props, ResourceProperties.PROP_CREATOR).getDisplayName();
newItem.setCreatedBy(createdBy);
}
catch(Exception e)
{
String createdBy = props.getProperty(ResourceProperties.PROP_CREATOR);
newItem.setCreatedBy(createdBy);
}
try
{
Time modifiedTime = props.getTimeProperty(ResourceProperties.PROP_MODIFIED_DATE);
String modifiedTimeString = modifiedTime.toStringLocalShortDate();
newItem.setModifiedTime(modifiedTimeString);
}
catch(Exception e)
{
String modifiedTimeString = props.getProperty(ResourceProperties.PROP_MODIFIED_DATE);
newItem.setModifiedTime(modifiedTimeString);
}
try
{
String modifiedBy = getUserProperty(props, ResourceProperties.PROP_MODIFIED_BY).getDisplayName();
newItem.setModifiedBy(modifiedBy);
}
catch(Exception e)
{
String modifiedBy = props.getProperty(ResourceProperties.PROP_MODIFIED_BY);
newItem.setModifiedBy(modifiedBy);
}
String size = props.getPropertyFormatted(ResourceProperties.PROP_CONTENT_LENGTH);
newItem.setSize(size);
String target = Validator.getResourceTarget(props.getProperty(ResourceProperties.PROP_CONTENT_TYPE));
newItem.setTarget(target);
String newUrl = contentService.getUrl(itemId);
newItem.setUrl(newUrl);
try
{
boolean copyrightAlert = props.getBooleanProperty(ResourceProperties.PROP_COPYRIGHT_ALERT);
newItem.setCopyrightAlert(copyrightAlert);
}
catch(Exception e)
{}
newItem.setDepth(depth + 1);
if (checkItemFilter((ContentResource)resource, newItem, state))
{
newItems.add(newItem);
}
}
}
}
folder.seDeletableChildren(hasDeletableChildren);
folder.setCopyableChildren(hasCopyableChildren);
// return newItems;
}
catch (IdUnusedException ignore)
{
// this condition indicates a site that does not have a resources collection (mercury?)
}
catch (TypeException e)
{
addAlert(state, "TypeException.");
}
catch (PermissionException e)
{
// ignore -- we'll just skip this collection since user lacks permission to access it.
//addAlert(state, "PermissionException");
}
return newItems;
} // getBrowseItems
protected static boolean checkItemFilter(ContentResource resource, BrowseItem newItem, SessionState state)
{
ContentResourceFilter filter = (ContentResourceFilter)state.getAttribute(STATE_ATTACH_FILTER);
if (filter != null)
{
if (newItem != null)
{
newItem.setCanSelect(filter.allowSelect(resource));
}
return filter.allowView(resource);
}
else if (newItem != null)
{
newItem.setCanSelect(true);
}
return true;
}
protected static boolean checkSelctItemFilter(ContentResource resource, SessionState state)
{
ContentResourceFilter filter = (ContentResourceFilter)state.getAttribute(STATE_ATTACH_FILTER);
if (filter != null)
{
return filter.allowSelect(resource);
}
return true;
}
/**
* set the state name to be "copy" if any item has been selected for copying
*/
public void doCopyitem ( RunData data )
{
// get the state object
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
String itemId = data.getParameters ().getString ("itemId");
if (itemId == null)
{
// there is no resource selected, show the alert message to the user
addAlert(state, rb.getString("choosefile6"));
state.setAttribute (STATE_MODE, MODE_LIST);
}
else
{
try
{
ResourceProperties properties = ContentHostingService.getProperties (itemId);
/*
if (properties.getProperty (ResourceProperties.PROP_IS_COLLECTION).equals (Boolean.TRUE.toString()))
{
String alert = (String) state.getAttribute(STATE_MESSAGE);
if (alert == null || ((alert != null) && (alert.indexOf(RESOURCE_INVALID_OPERATION_ON_COLLECTION_STRING) == -1)))
{
addAlert(state, RESOURCE_INVALID_OPERATION_ON_COLLECTION_STRING);
}
}
*/
}
catch (PermissionException e)
{
addAlert(state, rb.getString("notpermis15"));
}
catch (IdUnusedException e)
{
addAlert(state,RESOURCE_NOT_EXIST_STRING);
} // try-catch
if (state.getAttribute(STATE_MESSAGE) == null)
{
state.setAttribute (STATE_COPY_FLAG, Boolean.TRUE.toString());
state.setAttribute (STATE_COPIED_ID, itemId);
} // if-else
} // if-else
} // doCopyitem
/**
* Paste the previously copied item(s)
*/
public static void doPasteitems ( RunData data)
{
ParameterParser params = data.getParameters ();
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
List items = (List) state.getAttribute(STATE_COPIED_IDS);
String collectionId = params.getString ("collectionId");
Iterator itemIter = items.iterator();
while (itemIter.hasNext())
{
// get the copied item to be pasted
String itemId = (String) itemIter.next();
String originalDisplayName = NULL_STRING;
try
{
String id = ContentHostingService.copyIntoFolder(itemId, collectionId);
String mode = (String) state.getAttribute(STATE_MODE);
if(MODE_HELPER.equals(mode))
{
String helper_mode = (String) state.getAttribute(STATE_RESOURCES_HELPER_MODE);
if(helper_mode != null && MODE_ATTACHMENT_NEW_ITEM.equals(helper_mode))
{
// add to the attachments vector
List attachments = EntityManager.newReferenceList();
Reference ref = EntityManager.newReference(ContentHostingService.getReference(id));
attachments.add(ref);
cleanupState(state);
state.setAttribute(STATE_ATTACHMENTS, attachments);
}
else
{
if(state.getAttribute(STATE_ATTACH_LINKS) == null)
{
attachItem(id, state);
}
else
{
attachLink(id, state);
}
}
}
}
catch (PermissionException e)
{
addAlert(state, rb.getString("notpermis8") + " " + originalDisplayName + ". ");
}
catch (IdUnusedException e)
{
addAlert(state,RESOURCE_NOT_EXIST_STRING);
}
catch (InUseException e)
{
addAlert(state, rb.getString("someone") + " " + originalDisplayName);
}
catch (TypeException e)
{
addAlert(state, rb.getString("pasteitem") + " " + originalDisplayName + " " + rb.getString("mismatch"));
}
catch(IdUsedException e)
{
addAlert(state, rb.getString("toomany"));
}
catch(IdLengthException e)
{
addAlert(state, rb.getString("toolong") + " " + e.getMessage());
}
catch(IdUniquenessException e)
{
addAlert(state, "Could not add this item to this folder");
}
catch(ServerOverloadException e)
{
addAlert(state, rb.getString("failed"));
}
catch(InconsistentException e)
{
addAlert(state, rb.getString("recursive") + " " + itemId);
}
catch (OverQuotaException e)
{
addAlert(state, rb.getString("overquota"));
} // try-catch
catch(RuntimeException e)
{
logger.error("ResourcesAction.doPasteitems ***** Unknown Exception ***** " + e.getMessage());
addAlert(state, rb.getString("failed"));
}
if (state.getAttribute(STATE_MESSAGE) == null)
{
// delete sucessful
String mode = (String) state.getAttribute(STATE_MODE);
if(MODE_HELPER.equals(mode))
{
state.setAttribute(STATE_RESOURCES_HELPER_MODE, MODE_ATTACHMENT_SELECT);
}
else
{
state.setAttribute (STATE_MODE, MODE_LIST);
}
// try to expand the collection
HashMap expandedCollections = (HashMap) state.getAttribute(STATE_EXPANDED_COLLECTIONS);
if(! expandedCollections.containsKey(collectionId))
{
org.sakaiproject.content.api.ContentHostingService contentService = (org.sakaiproject.content.api.ContentHostingService) state.getAttribute (STATE_CONTENT_SERVICE);
try
{
ContentCollection coll = contentService.getCollection(collectionId);
expandedCollections.put(collectionId, coll);
}
catch(Exception ignore){}
}
// reset the copy flag
if (((String)state.getAttribute (STATE_COPY_FLAG)).equals (Boolean.TRUE.toString()))
{
state.setAttribute (STATE_COPY_FLAG, Boolean.FALSE.toString());
}
}
}
} // doPasteitems
/**
* Paste the item(s) selected to be moved
*/
public static void doMoveitems ( RunData data)
{
ParameterParser params = data.getParameters ();
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
// cancel copy if there is one in progress
if(! Boolean.FALSE.toString().equals(state.getAttribute (STATE_COPY_FLAG)))
{
initCopyContext(state);
}
List items = (List) state.getAttribute(STATE_MOVED_IDS);
String collectionId = params.getString ("collectionId");
Iterator itemIter = items.iterator();
while (itemIter.hasNext())
{
// get the copied item to be pasted
String itemId = (String) itemIter.next();
String originalDisplayName = NULL_STRING;
try
{
/*
ResourceProperties properties = ContentHostingService.getProperties (itemId);
originalDisplayName = properties.getPropertyFormatted (ResourceProperties.PROP_DISPLAY_NAME);
// copy, cut and paste not operated on collections
if (properties.getProperty (ResourceProperties.PROP_IS_COLLECTION).equals (Boolean.TRUE.toString()))
{
String alert = (String) state.getAttribute(STATE_MESSAGE);
if (alert == null || ((alert != null) && (alert.indexOf(RESOURCE_INVALID_OPERATION_ON_COLLECTION_STRING) == -1)))
{
addAlert(state, RESOURCE_INVALID_OPERATION_ON_COLLECTION_STRING);
}
}
else
*/
{
ContentHostingService.moveIntoFolder(itemId, collectionId);
} // if-else
}
catch (PermissionException e)
{
addAlert(state, rb.getString("notpermis8") + " " + originalDisplayName + ". ");
}
catch (IdUnusedException e)
{
addAlert(state,RESOURCE_NOT_EXIST_STRING);
}
catch (InUseException e)
{
addAlert(state, rb.getString("someone") + " " + originalDisplayName);
}
catch (TypeException e)
{
addAlert(state, rb.getString("pasteitem") + " " + originalDisplayName + " " + rb.getString("mismatch"));
}
catch (InconsistentException e)
{
addAlert(state, rb.getString("recursive") + " " + itemId);
}
catch(IdUsedException e)
{
addAlert(state, rb.getString("toomany"));
}
catch(ServerOverloadException e)
{
addAlert(state, rb.getString("failed"));
}
catch (OverQuotaException e)
{
addAlert(state, rb.getString("overquota"));
} // try-catch
catch(RuntimeException e)
{
logger.error("ResourcesAction.doMoveitems ***** Unknown Exception ***** " + e.getMessage());
addAlert(state, rb.getString("failed"));
}
if (state.getAttribute(STATE_MESSAGE) == null)
{
// delete sucessful
String mode = (String) state.getAttribute(STATE_MODE);
if(MODE_HELPER.equals(mode))
{
state.setAttribute(STATE_RESOURCES_HELPER_MODE, MODE_ATTACHMENT_SELECT);
}
else
{
state.setAttribute (STATE_MODE, MODE_LIST);
}
// try to expand the collection
HashMap expandedCollections = (HashMap) state.getAttribute(STATE_EXPANDED_COLLECTIONS);
if(! expandedCollections.containsKey(collectionId))
{
org.sakaiproject.content.api.ContentHostingService contentService = (org.sakaiproject.content.api.ContentHostingService) state.getAttribute (STATE_CONTENT_SERVICE);
try
{
ContentCollection coll = contentService.getCollection(collectionId);
expandedCollections.put(collectionId, coll);
}
catch(Exception ignore){}
}
// reset the copy flag
if (((String)state.getAttribute (STATE_MOVE_FLAG)).equals (Boolean.TRUE.toString()))
{
state.setAttribute (STATE_MOVE_FLAG, Boolean.FALSE.toString());
}
}
}
} // doMoveitems
/**
* Paste the previously copied item(s)
*/
public static void doPasteitem ( RunData data)
{
ParameterParser params = data.getParameters ();
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
// get the copied item to be pasted
String itemId = params.getString("itemId");
String collectionId = params.getString ("collectionId");
String originalDisplayName = NULL_STRING;
try
{
ResourceProperties properties = ContentHostingService.getProperties (itemId);
originalDisplayName = properties.getPropertyFormatted (ResourceProperties.PROP_DISPLAY_NAME);
// copy, cut and paste not operated on collections
if (properties.getProperty (ResourceProperties.PROP_IS_COLLECTION).equals (Boolean.TRUE.toString()))
{
String alert = (String) state.getAttribute(STATE_MESSAGE);
if (alert == null || ((alert != null) && (alert.indexOf(RESOURCE_INVALID_OPERATION_ON_COLLECTION_STRING) == -1)))
{
addAlert(state, RESOURCE_INVALID_OPERATION_ON_COLLECTION_STRING);
}
}
else
{
// paste the resource
ContentResource resource = ContentHostingService.getResource (itemId);
ResourceProperties p = ContentHostingService.getProperties(itemId);
String displayName = DUPLICATE_STRING + p.getProperty(ResourceProperties.PROP_DISPLAY_NAME);
String newItemId = ContentHostingService.copyIntoFolder(itemId, collectionId);
ContentResourceEdit copy = ContentHostingService.editResource(newItemId);
ResourcePropertiesEdit pedit = copy.getPropertiesEdit();
pedit.addProperty(ResourceProperties.PROP_DISPLAY_NAME, displayName);
ContentHostingService.commitResource(copy, NotificationService.NOTI_NONE);
} // if-else
}
catch (PermissionException e)
{
addAlert(state, rb.getString("notpermis8") + " " + originalDisplayName + ". ");
}
catch (IdUnusedException e)
{
addAlert(state,RESOURCE_NOT_EXIST_STRING);
}
catch (IdUsedException e)
{
addAlert(state, rb.getString("notaddreso") + " " + originalDisplayName + " " + rb.getString("used2"));
}
catch(IdLengthException e)
{
addAlert(state, rb.getString("toolong") + " " + e.getMessage());
}
catch(IdUniquenessException e)
{
addAlert(state, "Could not add this item to this folder");
}
catch (InconsistentException ee)
{
addAlert(state, RESOURCE_INVALID_TITLE_STRING);
}
catch(InUseException e)
{
addAlert(state, rb.getString("someone") + " " + originalDisplayName + ". ");
}
catch(OverQuotaException e)
{
addAlert(state, rb.getString("overquota"));
}
catch(ServerOverloadException e)
{
// this represents temporary unavailability of server's filesystem
// for server configured to save resource body in filesystem
addAlert(state, rb.getString("failed"));
}
catch (TypeException e)
{
addAlert(state, rb.getString("pasteitem") + " " + originalDisplayName + " " + rb.getString("mismatch"));
} // try-catch
if (state.getAttribute(STATE_MESSAGE) == null)
{
// delete sucessful
String mode = (String) state.getAttribute(STATE_MODE);
if(MODE_HELPER.equals(mode))
{
state.setAttribute(STATE_RESOURCES_HELPER_MODE, MODE_ATTACHMENT_SELECT);
}
else
{
state.setAttribute (STATE_MODE, MODE_LIST);
}
// try to expand the collection
HashMap expandedCollections = (HashMap) state.getAttribute(STATE_EXPANDED_COLLECTIONS);
if(! expandedCollections.containsKey(collectionId))
{
org.sakaiproject.content.api.ContentHostingService contentService = (org.sakaiproject.content.api.ContentHostingService) state.getAttribute (STATE_CONTENT_SERVICE);
try
{
ContentCollection coll = contentService.getCollection(collectionId);
expandedCollections.put(collectionId, coll);
}
catch(Exception ignore){}
}
// reset the copy flag
if (((String)state.getAttribute (STATE_COPY_FLAG)).equals (Boolean.TRUE.toString()))
{
state.setAttribute (STATE_COPY_FLAG, Boolean.FALSE.toString());
}
}
} // doPasteitem
/**
* Fire up the permissions editor for the current folder's permissions
*/
public void doFolder_permissions(RunData data, Context context)
{
SessionState state = ((JetspeedRunData)data).getPortletSessionState(((JetspeedRunData)data).getJs_peid());
ParameterParser params = data.getParameters();
// cancel copy if there is one in progress
if(! Boolean.FALSE.toString().equals(state.getAttribute (STATE_COPY_FLAG)))
{
initCopyContext(state);
}
// cancel move if there is one in progress
if(! Boolean.FALSE.toString().equals(state.getAttribute (STATE_MOVE_FLAG)))
{
initMoveContext(state);
}
// get the current collection id and the related site
String collectionId = params.getString("collectionId"); //(String) state.getAttribute (STATE_COLLECTION_ID);
String title = "";
try
{
title = ContentHostingService.getProperties(collectionId).getProperty(ResourceProperties.PROP_DISPLAY_NAME);
}
catch (PermissionException e)
{
addAlert(state, rb.getString("notread"));
}
catch (IdUnusedException e)
{
addAlert(state, rb.getString("notfindfol"));
}
// the folder to edit
Reference ref = EntityManager.newReference(ContentHostingService.getReference(collectionId));
state.setAttribute(PermissionsHelper.TARGET_REF, ref.getReference());
// use the folder's context (as a site) for roles
String siteRef = SiteService.siteReference(ref.getContext());
state.setAttribute(PermissionsHelper.ROLES_REF, siteRef);
// ... with this description
state.setAttribute(PermissionsHelper.DESCRIPTION, rb.getString("setpermis") + " " + title);
// ... showing only locks that are prpefixed with this
state.setAttribute(PermissionsHelper.PREFIX, "content.");
// get into helper mode with this helper tool
startHelper(data.getRequest(), "sakai.permissions.helper");
} // doFolder_permissions
/**
* Fire up the permissions editor for the tool's permissions
*/
public void doPermissions(RunData data, Context context)
{
SessionState state = ((JetspeedRunData)data).getPortletSessionState(((JetspeedRunData)data).getJs_peid());
// cancel copy if there is one in progress
if(! Boolean.FALSE.toString().equals(state.getAttribute (STATE_COPY_FLAG)))
{
initCopyContext(state);
}
// cancel move if there is one in progress
if(! Boolean.FALSE.toString().equals(state.getAttribute (STATE_MOVE_FLAG)))
{
initMoveContext(state);
}
// should we save here?
state.setAttribute(STATE_LIST_SELECTIONS, new TreeSet());
// get the current home collection id and the related site
String collectionId = (String) state.getAttribute (STATE_HOME_COLLECTION_ID);
Reference ref = EntityManager.newReference(ContentHostingService.getReference(collectionId));
String siteRef = SiteService.siteReference(ref.getContext());
// setup for editing the permissions of the site for this tool, using the roles of this site, too
state.setAttribute(PermissionsHelper.TARGET_REF, siteRef);
// ... with this description
state.setAttribute(PermissionsHelper.DESCRIPTION, rb.getString("setpermis1")
+ SiteService.getSiteDisplay(ref.getContext()));
// ... showing only locks that are prpefixed with this
state.setAttribute(PermissionsHelper.PREFIX, "content.");
// get into helper mode with this helper tool
startHelper(data.getRequest(), "sakai.permissions.helper");
} // doPermissions
/**
* is notification enabled?
*/
protected boolean notificationEnabled(SessionState state)
{
return true;
} // notificationEnabled
/**
* Processes the HTML document that is coming back from the browser
* (from the formatted text editing widget).
* @param state Used to pass in any user-visible alerts or errors when processing the text
* @param strFromBrowser The string from the browser
* @return The formatted text
*/
private String processHtmlDocumentFromBrowser(SessionState state, String strFromBrowser)
{
StringBuffer alertMsg = new StringBuffer();
String text = FormattedText.processHtmlDocument(strFromBrowser, alertMsg);
if (alertMsg.length() > 0) addAlert(state, alertMsg.toString());
return text;
}
/**
*
* Whether a resource item can be replaced
* @param p The ResourceProperties object for the resource item
* @return true If it can be replaced; false otherwise
*/
private static boolean replaceable(ResourceProperties p)
{
boolean rv = true;
if (p.getPropertyFormatted (ResourceProperties.PROP_IS_COLLECTION).equals (Boolean.TRUE.toString()))
{
rv = false;
}
else if (p.getProperty (ResourceProperties.PROP_CONTENT_TYPE).equals (ResourceProperties.TYPE_URL))
{
rv = false;
}
String displayName = p.getPropertyFormatted (ResourceProperties.PROP_DISPLAY_NAME);
if (displayName.indexOf(SHORTCUT_STRING) != -1)
{
rv = false;
}
return rv;
} // replaceable
/**
*
* put copyright info into context
*/
private static void copyrightChoicesIntoContext(SessionState state, Context context)
{
boolean usingCreativeCommons = state.getAttribute(STATE_USING_CREATIVE_COMMONS) != null && state.getAttribute(STATE_USING_CREATIVE_COMMONS).equals(Boolean.TRUE.toString());
if(usingCreativeCommons)
{
String ccOwnershipLabel = "Who created this resource?";
List ccOwnershipList = new Vector();
ccOwnershipList.add("-- Select --");
ccOwnershipList.add("I created this resource");
ccOwnershipList.add("Someone else created this resource");
String ccMyGrantLabel = "Terms of use";
List ccMyGrantOptions = new Vector();
ccMyGrantOptions.add("-- Select --");
ccMyGrantOptions.add("Use my copyright");
ccMyGrantOptions.add("Use Creative Commons License");
ccMyGrantOptions.add("Use Public Domain Dedication");
String ccCommercialLabel = "Allow commercial use?";
List ccCommercialList = new Vector();
ccCommercialList.add("Yes");
ccCommercialList.add("No");
String ccModificationLabel = "Allow Modifications?";
List ccModificationList = new Vector();
ccModificationList.add("Yes");
ccModificationList.add("Yes, share alike");
ccModificationList.add("No");
String ccOtherGrantLabel = "Terms of use";
List ccOtherGrantList = new Vector();
ccOtherGrantList.add("Subject to fair-use exception");
ccOtherGrantList.add("Public domain (created before copyright law applied)");
ccOtherGrantList.add("Public domain (copyright has expired)");
ccOtherGrantList.add("Public domain (government document not subject to copyright)");
String ccRightsYear = "Year";
String ccRightsOwner = "Copyright owner";
String ccAcknowledgeLabel = "Require users to acknowledge author's rights before access?";
List ccAcknowledgeList = new Vector();
ccAcknowledgeList.add("Yes");
ccAcknowledgeList.add("No");
String ccInfoUrl = "";
int year = TimeService.newTime().breakdownLocal().getYear();
String username = UserDirectoryService.getCurrentUser().getDisplayName();
context.put("usingCreativeCommons", Boolean.TRUE);
context.put("ccOwnershipLabel", ccOwnershipLabel);
context.put("ccOwnershipList", ccOwnershipList);
context.put("ccMyGrantLabel", ccMyGrantLabel);
context.put("ccMyGrantOptions", ccMyGrantOptions);
context.put("ccCommercialLabel", ccCommercialLabel);
context.put("ccCommercialList", ccCommercialList);
context.put("ccModificationLabel", ccModificationLabel);
context.put("ccModificationList", ccModificationList);
context.put("ccOtherGrantLabel", ccOtherGrantLabel);
context.put("ccOtherGrantList", ccOtherGrantList);
context.put("ccRightsYear", ccRightsYear);
context.put("ccRightsOwner", ccRightsOwner);
context.put("ccAcknowledgeLabel", ccAcknowledgeLabel);
context.put("ccAcknowledgeList", ccAcknowledgeList);
context.put("ccInfoUrl", ccInfoUrl);
context.put("ccThisYear", Integer.toString(year));
context.put("ccThisUser", username);
}
else
{
//copyright
if (state.getAttribute(COPYRIGHT_FAIRUSE_URL) != null)
{
context.put("fairuseurl", state.getAttribute(COPYRIGHT_FAIRUSE_URL));
}
if (state.getAttribute(NEW_COPYRIGHT_INPUT) != null)
{
context.put("newcopyrightinput", state.getAttribute(NEW_COPYRIGHT_INPUT));
}
if (state.getAttribute(COPYRIGHT_TYPES) != null)
{
List copyrightTypes = (List) state.getAttribute(COPYRIGHT_TYPES);
context.put("copyrightTypes", copyrightTypes);
context.put("copyrightTypesSize", new Integer(copyrightTypes.size() - 1));
context.put("USE_THIS_COPYRIGHT", copyrightTypes.get(copyrightTypes.size() - 1));
}
}
Boolean preventPublicDisplay = (Boolean) state.getAttribute(STATE_PREVENT_PUBLIC_DISPLAY);
if(preventPublicDisplay == null)
{
preventPublicDisplay = Boolean.FALSE;
state.setAttribute(STATE_PREVENT_PUBLIC_DISPLAY, preventPublicDisplay);
}
context.put("preventPublicDisplay", preventPublicDisplay);
} // copyrightChoicesIntoContext
/**
* Add variables and constants to the velocity context to render an editor
* for inputing and modifying optional metadata properties about a resource.
*/
private static void metadataGroupsIntoContext(SessionState state, Context context)
{
context.put("STRING", ResourcesMetadata.WIDGET_STRING);
context.put("TEXTAREA", ResourcesMetadata.WIDGET_TEXTAREA);
context.put("BOOLEAN", ResourcesMetadata.WIDGET_BOOLEAN);
context.put("INTEGER", ResourcesMetadata.WIDGET_INTEGER);
context.put("DOUBLE", ResourcesMetadata.WIDGET_DOUBLE);
context.put("DATE", ResourcesMetadata.WIDGET_DATE);
context.put("TIME", ResourcesMetadata.WIDGET_TIME);
context.put("DATETIME", ResourcesMetadata.WIDGET_DATETIME);
context.put("ANYURI", ResourcesMetadata.WIDGET_ANYURI);
context.put("WYSIWYG", ResourcesMetadata.WIDGET_WYSIWYG);
context.put("today", TimeService.newTime());
List metadataGroups = (List) state.getAttribute(STATE_METADATA_GROUPS);
if(metadataGroups != null && !metadataGroups.isEmpty())
{
context.put("metadataGroups", metadataGroups);
}
} // metadataGroupsIntoContext
/**
* initialize the metadata context
*/
private static void initMetadataContext(SessionState state)
{
// define MetadataSets map
List metadataGroups = (List) state.getAttribute(STATE_METADATA_GROUPS);
if(metadataGroups == null)
{
metadataGroups = new Vector();
state.setAttribute(STATE_METADATA_GROUPS, metadataGroups);
}
// define DublinCore
if( !metadataGroups.contains(new MetadataGroup(rb.getString("opt_props"))) )
{
MetadataGroup dc = new MetadataGroup( rb.getString("opt_props") );
// dc.add(ResourcesMetadata.PROPERTY_DC_TITLE);
// dc.add(ResourcesMetadata.PROPERTY_DC_DESCRIPTION);
dc.add(ResourcesMetadata.PROPERTY_DC_ALTERNATIVE);
dc.add(ResourcesMetadata.PROPERTY_DC_CREATOR);
dc.add(ResourcesMetadata.PROPERTY_DC_PUBLISHER);
dc.add(ResourcesMetadata.PROPERTY_DC_SUBJECT);
dc.add(ResourcesMetadata.PROPERTY_DC_CREATED);
dc.add(ResourcesMetadata.PROPERTY_DC_ISSUED);
// dc.add(ResourcesMetadata.PROPERTY_DC_MODIFIED);
// dc.add(ResourcesMetadata.PROPERTY_DC_TABLEOFCONTENTS);
dc.add(ResourcesMetadata.PROPERTY_DC_ABSTRACT);
dc.add(ResourcesMetadata.PROPERTY_DC_CONTRIBUTOR);
// dc.add(ResourcesMetadata.PROPERTY_DC_TYPE);
// dc.add(ResourcesMetadata.PROPERTY_DC_FORMAT);
// dc.add(ResourcesMetadata.PROPERTY_DC_IDENTIFIER);
// dc.add(ResourcesMetadata.PROPERTY_DC_SOURCE);
// dc.add(ResourcesMetadata.PROPERTY_DC_LANGUAGE);
// dc.add(ResourcesMetadata.PROPERTY_DC_COVERAGE);
// dc.add(ResourcesMetadata.PROPERTY_DC_RIGHTS);
dc.add(ResourcesMetadata.PROPERTY_DC_AUDIENCE);
dc.add(ResourcesMetadata.PROPERTY_DC_EDULEVEL);
metadataGroups.add(dc);
state.setAttribute(STATE_METADATA_GROUPS, metadataGroups);
}
/*
// define DublinCore
if(!metadataGroups.contains(new MetadataGroup("Test of Datatypes")))
{
MetadataGroup dc = new MetadataGroup("Test of Datatypes");
dc.add(ResourcesMetadata.PROPERTY_DC_TITLE);
dc.add(ResourcesMetadata.PROPERTY_DC_DESCRIPTION);
dc.add(ResourcesMetadata.PROPERTY_DC_ANYURI);
dc.add(ResourcesMetadata.PROPERTY_DC_DOUBLE);
dc.add(ResourcesMetadata.PROPERTY_DC_DATETIME);
dc.add(ResourcesMetadata.PROPERTY_DC_TIME);
dc.add(ResourcesMetadata.PROPERTY_DC_DATE);
dc.add(ResourcesMetadata.PROPERTY_DC_BOOLEAN);
dc.add(ResourcesMetadata.PROPERTY_DC_INTEGER);
metadataGroups.add(dc);
state.setAttribute(STATE_METADATA_GROUPS, metadataGroups);
}
*/
}
/**
* Internal class that encapsulates all information about a resource that is needed in the browse mode
*/
public static class BrowseItem
{
protected static Integer seqnum = new Integer(0);
private String m_itemnum;
// attributes of all resources
protected String m_name;
protected String m_id;
protected String m_type;
protected boolean m_canRead;
protected boolean m_canRevise;
protected boolean m_canDelete;
protected boolean m_canCopy;
protected boolean m_isCopied;
protected boolean m_canAddItem;
protected boolean m_canAddFolder;
protected boolean m_canSelect;
protected List m_members;
protected boolean m_isEmpty;
protected boolean m_isHighlighted;
protected boolean m_inheritsHighlight;
protected String m_createdBy;
protected String m_createdTime;
protected String m_modifiedBy;
protected String m_modifiedTime;
protected String m_size;
protected String m_target;
protected String m_container;
protected String m_root;
protected int m_depth;
protected boolean m_hasDeletableChildren;
protected boolean m_hasCopyableChildren;
protected boolean m_copyrightAlert;
protected String m_url;
protected boolean m_isLocal;
protected boolean m_isAttached;
private boolean m_isMoved;
private boolean m_canUpdate;
private boolean m_toobig;
protected String m_access;
protected String m_inheritedAccess;
protected List m_groups;
protected List m_inheritedGroups;
protected BasicRightsAssignment m_rights;
/**
* @param id
* @param name
* @param type
*/
public BrowseItem(String id, String name, String type)
{
m_name = name;
m_id = id;
m_type = type;
Integer snum;
synchronized(seqnum)
{
snum = seqnum;
seqnum = new Integer((seqnum.intValue() + 1) % 10000);
}
m_itemnum = "Item00000000".substring(0,10 - snum.toString().length()) + snum.toString();
// set defaults
m_rights = new BasicRightsAssignment(m_itemnum, false);
m_members = new LinkedList();
m_canRead = false;
m_canRevise = false;
m_canDelete = false;
m_canCopy = false;
m_isEmpty = true;
m_toobig = false;
m_isCopied = false;
m_isMoved = false;
m_isAttached = false;
m_canSelect = true; // default is true.
m_hasDeletableChildren = false;
m_hasCopyableChildren = false;
m_createdBy = "";
m_modifiedBy = "";
// m_createdTime = TimeService.newTime().toStringLocalDate();
// m_modifiedTime = TimeService.newTime().toStringLocalDate();
m_size = "";
m_depth = 0;
m_copyrightAlert = false;
m_url = "";
m_target = "";
m_root = "";
m_isHighlighted = false;
m_inheritsHighlight = false;
m_canAddItem = false;
m_canAddFolder = false;
m_canUpdate = false;
m_access = AccessMode.INHERITED.toString();
m_groups = new Vector();
}
public String getItemNum()
{
return m_itemnum;
}
public void setIsTooBig(boolean toobig)
{
m_toobig = toobig;
}
public boolean isTooBig()
{
return m_toobig;
}
/**
* @param name
*/
public void setName(String name)
{
m_name = name;
}
/**
* @param root
*/
public void setRoot(String root)
{
m_root = root;
}
/**
* @return
*/
public String getRoot()
{
return m_root;
}
/**
* @return
*/
public List getMembers()
{
List rv = new LinkedList();
if(m_members != null)
{
rv.addAll(m_members);
}
return rv;
}
/**
* @param members
*/
public void addMembers(Collection members)
{
if(m_members == null)
{
m_members = new LinkedList();
}
m_members.addAll(members);
}
/**
* @return
*/
public boolean canAddItem()
{
return m_canAddItem;
}
/**
* @return
*/
public boolean canDelete()
{
return m_canDelete;
}
/**
* @return
*/
public boolean canRead()
{
return m_canRead;
}
public boolean canSelect() {
return m_canSelect;
}
/**
* @return
*/
public boolean canRevise()
{
return m_canRevise;
}
/**
* @return
*/
public String getId()
{
return m_id;
}
/**
* @return
*/
public String getName()
{
return m_name;
}
/**
* @return
*/
public int getDepth()
{
return m_depth;
}
/**
* @param depth
*/
public void setDepth(int depth)
{
m_depth = depth;
}
/**
* @param canCreate
*/
public void setCanAddItem(boolean canAddItem)
{
m_canAddItem = canAddItem;
}
/**
* @param canDelete
*/
public void setCanDelete(boolean canDelete)
{
m_canDelete = canDelete;
}
/**
* @param canRead
*/
public void setCanRead(boolean canRead)
{
m_canRead = canRead;
}
public void setCanSelect(boolean canSelect) {
m_canSelect = canSelect;
}
/**
* @param canRevise
*/
public void setCanRevise(boolean canRevise)
{
m_canRevise = canRevise;
}
/**
* @return
*/
public boolean isFolder()
{
return TYPE_FOLDER.equals(m_type);
}
/**
* @return
*/
public String getType()
{
return m_type;
}
/**
* @return
*/
public boolean canAddFolder()
{
return m_canAddFolder;
}
/**
* @param b
*/
public void setCanAddFolder(boolean canAddFolder)
{
m_canAddFolder = canAddFolder;
}
/**
* @return
*/
public boolean canCopy()
{
return m_canCopy;
}
/**
* @param canCopy
*/
public void setCanCopy(boolean canCopy)
{
m_canCopy = canCopy;
}
/**
* @return
*/
public boolean hasCopyrightAlert()
{
return m_copyrightAlert;
}
/**
* @param copyrightAlert
*/
public void setCopyrightAlert(boolean copyrightAlert)
{
m_copyrightAlert = copyrightAlert;
}
/**
* @return
*/
public String getUrl()
{
return m_url;
}
/**
* @param url
*/
public void setUrl(String url)
{
m_url = url;
}
/**
* @return
*/
public boolean isCopied()
{
return m_isCopied;
}
/**
* @param isCopied
*/
public void setCopied(boolean isCopied)
{
m_isCopied = isCopied;
}
/**
* @return
*/
public boolean isMoved()
{
return m_isMoved;
}
/**
* @param isCopied
*/
public void setMoved(boolean isMoved)
{
m_isMoved = isMoved;
}
/**
* @return
*/
public String getCreatedBy()
{
return m_createdBy;
}
/**
* @return
*/
public String getCreatedTime()
{
return m_createdTime;
}
/**
* @return
*/
public String getModifiedBy()
{
return m_modifiedBy;
}
/**
* @return
*/
public String getModifiedTime()
{
return m_modifiedTime;
}
/**
* @return
*/
public String getSize()
{
if(m_size == null)
{
m_size = "";
}
return m_size;
}
/**
* @param creator
*/
public void setCreatedBy(String creator)
{
m_createdBy = creator;
}
/**
* @param time
*/
public void setCreatedTime(String time)
{
m_createdTime = time;
}
/**
* @param modifier
*/
public void setModifiedBy(String modifier)
{
m_modifiedBy = modifier;
}
/**
* @param time
*/
public void setModifiedTime(String time)
{
m_modifiedTime = time;
}
/**
* @param size
*/
public void setSize(String size)
{
m_size = size;
}
/**
* @return
*/
public String getTarget()
{
return m_target;
}
/**
* @param target
*/
public void setTarget(String target)
{
m_target = target;
}
/**
* @return
*/
public boolean isEmpty()
{
return m_isEmpty;
}
/**
* @param isEmpty
*/
public void setIsEmpty(boolean isEmpty)
{
m_isEmpty = isEmpty;
}
/**
* @return
*/
public String getContainer()
{
return m_container;
}
/**
* @param container
*/
public void setContainer(String container)
{
m_container = container;
}
public void setIsLocal(boolean isLocal)
{
m_isLocal = isLocal;
}
public boolean isLocal()
{
return m_isLocal;
}
/**
* @return Returns the isAttached.
*/
public boolean isAttached()
{
return m_isAttached;
}
/**
* @param isAttached The isAttached to set.
*/
public void setAttached(boolean isAttached)
{
this.m_isAttached = isAttached;
}
/**
* @return Returns the hasCopyableChildren.
*/
public boolean hasCopyableChildren()
{
return m_hasCopyableChildren;
}
/**
* @param hasCopyableChildren The hasCopyableChildren to set.
*/
public void setCopyableChildren(boolean hasCopyableChildren)
{
this.m_hasCopyableChildren = hasCopyableChildren;
}
/**
* @return Returns the hasDeletableChildren.
*/
public boolean hasDeletableChildren()
{
return m_hasDeletableChildren;
}
/**
* @param hasDeletableChildren The hasDeletableChildren to set.
*/
public void seDeletableChildren(boolean hasDeletableChildren)
{
this.m_hasDeletableChildren = hasDeletableChildren;
}
/**
* @return Returns the canUpdate.
*/
public boolean canUpdate()
{
return m_canUpdate;
}
/**
* @param canUpdate The canUpdate to set.
*/
public void setCanUpdate(boolean canUpdate)
{
m_canUpdate = canUpdate;
}
public void setHighlighted(boolean isHighlighted)
{
m_isHighlighted = isHighlighted;
}
public boolean isHighlighted()
{
return m_isHighlighted;
}
public void setInheritsHighlight(boolean inheritsHighlight)
{
m_inheritsHighlight = inheritsHighlight;
}
public boolean inheritsHighlighted()
{
return m_inheritsHighlight;
}
/**
* Access the access mode for this item.
* @return The access mode.
*/
public String getAccess()
{
return m_access;
}
/**
* Access the access mode for this item.
* @return The access mode.
*/
public String getInheritedAccess()
{
return m_inheritedAccess;
}
public String getEntityAccess()
{
String rv = AccessMode.INHERITED.toString();
boolean sameGroups = true;
if(AccessMode.GROUPED.toString().equals(m_access))
{
Iterator it = getGroups().iterator();
while(sameGroups && it.hasNext())
{
Group g = (Group) it.next();
sameGroups = inheritsGroup(g.getReference());
}
it = getInheritedGroups().iterator();
while(sameGroups && it.hasNext())
{
Group g = (Group) it.next();
sameGroups = hasGroup(g.getReference());
}
if(!sameGroups)
{
rv = AccessMode.GROUPED.toString();
}
}
return rv;
}
/**
* Set the access mode for this item.
* @param access
*/
public void setAccess(String access)
{
m_access = access;
}
/**
* Set the access mode for this item.
* @param access
*/
public void setInheritedAccess(String access)
{
m_inheritedAccess = access;
}
/**
* Access a list of Group objects that can access this item.
* @return Returns the groups.
*/
public List getGroups()
{
if(m_groups == null)
{
m_groups = new Vector();
}
return m_groups;
}
/**
* Access a list of Group objects that can access this item.
* @return Returns the groups.
*/
public List getInheritedGroups()
{
if(m_inheritedGroups == null)
{
m_inheritedGroups = new Vector();
}
return m_inheritedGroups;
}
/**
* Determine whether a group has access to this item.
* @param groupRef The internal reference string that uniquely identifies the group.
* @return true if the group has access, false otherwise.
*/
public boolean hasGroup(String groupRef)
{
if(m_groups == null)
{
m_groups = new Vector();
}
boolean found = false;
Iterator it = m_groups.iterator();
while(it.hasNext() && !found)
{
Group gr = (Group) it.next();
found = gr.getReference().equals(groupRef);
}
return found;
}
/**
* Determine whether a group has access to this item.
* @param groupRef The internal reference string that uniquely identifies the group.
* @return true if the group has access, false otherwise.
*/
public boolean inheritsGroup(String groupRef)
{
if(m_inheritedGroups == null)
{
m_inheritedGroups = new Vector();
}
boolean found = false;
Iterator it = m_inheritedGroups.iterator();
while(it.hasNext() && !found)
{
Group gr = (Group) it.next();
found = gr.getReference().equals(groupRef);
}
return found;
}
/**
* Replace the current list of groups with this list of Group objects representing the groups that have access to this item.
* @param groups The groups to set.
*/
public void setGroups(Collection groups)
{
if(groups == null)
{
return;
}
if(m_groups == null)
{
m_groups = new Vector();
}
m_groups.clear();
Iterator it = groups.iterator();
while(it.hasNext())
{
Object obj = it.next();
if(obj instanceof Group)
{
m_groups.add(obj);
}
else if(obj instanceof String)
{
addGroup((String) obj);
}
}
}
/**
* Replace the current list of groups with this list of Group objects representing the groups that have access to this item.
* @param groups The groups to set.
*/
public void setInheritedGroups(Collection groups)
{
if(groups == null)
{
return;
}
if(m_inheritedGroups == null)
{
m_inheritedGroups = new Vector();
}
m_inheritedGroups.clear();
Iterator it = groups.iterator();
while(it.hasNext())
{
Object obj = it.next();
if(obj instanceof Group)
{
m_inheritedGroups.add(obj);
}
else if(obj instanceof String)
{
addInheritedGroup((String) obj);
}
}
}
/**
* Add a string reference identifying a Group to the list of groups that have access to this item.
* @param groupRef
*/
public void addGroup(String groupId)
{
if(m_groups == null)
{
m_groups = new Vector();
}
if(m_container == null)
{
if(m_id == null)
{
m_container = ContentHostingService.getSiteCollection(ToolManager.getCurrentPlacement().getContext());
}
else
{
m_container = ContentHostingService.getContainingCollectionId(m_id);
}
if(m_container == null || m_container.trim() == "")
{
m_container = ContentHostingService.getSiteCollection(ToolManager.getCurrentPlacement().getContext());
}
}
boolean found = false;
Collection groups = ContentHostingService.getGroupsWithReadAccess(m_container);
Iterator it = groups.iterator();
while( it.hasNext() && !found )
{
Group group = (Group) it.next();
if(group.getId().equals(groupId))
{
if(! hasGroup(group.getReference()))
{
m_groups.add(group);
}
found = true;
}
}
}
/**
* Add a string reference identifying a Group to the list of groups that have access to this item.
* @param groupRef
*/
public void addInheritedGroup(String groupId)
{
if(m_inheritedGroups == null)
{
m_inheritedGroups = new Vector();
}
if(m_container == null)
{
if(m_id == null)
{
m_container = ContentHostingService.getSiteCollection(ToolManager.getCurrentPlacement().getContext());
}
else
{
m_container = ContentHostingService.getContainingCollectionId(m_id);
}
if(m_container == null || m_container.trim() == "")
{
m_container = ContentHostingService.getSiteCollection(ToolManager.getCurrentPlacement().getContext());
}
}
boolean found = false;
Collection groups = ContentHostingService.getGroupsWithReadAccess(m_container);
Iterator it = groups.iterator();
while( it.hasNext() && !found )
{
Group group = (Group) it.next();
if(group.getId().equals(groupId))
{
if(! hasGroup(group.getReference()))
{
m_inheritedGroups.add(group);
}
found = true;
}
}
}
/**
* Remove all groups from the item.
*/
public void clearGroups()
{
if(this.m_groups == null)
{
m_groups = new Vector();
}
m_groups.clear();
}
/**
* Remove all inherited groups from the item.
*/
public void clearInheritedGroups()
{
if(m_inheritedGroups == null)
{
m_inheritedGroups = new Vector();
}
m_inheritedGroups.clear();
}
/**
* @return Returns the rights.
*/
public BasicRightsAssignment getRights()
{
return m_rights;
}
/**
* @param rights The rights to set.
*/
public void setRights(BasicRightsAssignment rights)
{
this.m_rights = rights;
}
} // inner class BrowseItem
/**
* Inner class encapsulates information about resources (folders and items) for editing
*/
public static class EditItem
extends BrowseItem
{
protected String m_copyrightStatus;
protected String m_copyrightInfo;
// protected boolean m_copyrightAlert;
protected boolean m_pubview;
protected boolean m_pubviewset;
protected String m_filename;
protected byte[] m_content;
protected String m_encoding;
protected String m_mimetype;
protected String m_description;
protected Map m_metadata;
protected boolean m_hasQuota;
protected boolean m_canSetQuota;
protected String m_quota;
protected boolean m_isUrl;
protected boolean m_contentHasChanged;
protected boolean m_contentTypeHasChanged;
protected int m_notification;
protected String m_formtype;
protected String m_rootname;
protected Map m_structuredArtifact;
protected List m_properties;
protected Set m_metadataGroupsShowing;
protected Set m_missingInformation;
protected boolean m_hasBeenAdded;
protected ResourcesMetadata m_form;
protected boolean m_isBlank;
protected String m_instruction;
protected String m_ccRightsownership;
protected String m_ccLicense;
protected String m_ccCommercial;
protected String m_ccModification;
protected String m_ccRightsOwner;
protected String m_ccRightsYear;
/**
* @param id
* @param name
* @param type
*/
public EditItem(String id, String name, String type)
{
super(id, name, type);
m_filename = "";
m_contentHasChanged = false;
m_contentTypeHasChanged = false;
m_metadata = new Hashtable();
m_structuredArtifact = new Hashtable();
m_metadataGroupsShowing = new HashSet();
m_mimetype = type;
m_content = null;
m_encoding = "UTF-8";
m_notification = NotificationService.NOTI_NONE;
m_hasQuota = false;
m_canSetQuota = false;
m_formtype = "";
m_rootname = "";
m_missingInformation = new HashSet();
m_hasBeenAdded = false;
m_properties = new Vector();
m_isBlank = true;
m_instruction = "";
m_pubview = false;
m_pubviewset = false;
m_ccRightsownership = "";
m_ccLicense = "";
// m_copyrightStatus = ServerConfigurationService.getString("default.copyright");
}
public void setRightsowner(String ccRightsOwner)
{
m_ccRightsOwner = ccRightsOwner;
}
public String getRightsowner()
{
return m_ccRightsOwner;
}
public void setRightstyear(String ccRightsYear)
{
m_ccRightsYear = ccRightsYear;
}
public String getRightsyear()
{
return m_ccRightsYear;
}
public void setAllowModifications(String ccModification)
{
m_ccModification = ccModification;
}
public String getAllowModifications()
{
return m_ccModification;
}
public void setAllowCommercial(String ccCommercial)
{
m_ccCommercial = ccCommercial;
}
public String getAllowCommercial()
{
return m_ccCommercial;
}
/**
*
* @param license
*/
public void setLicense(String license)
{
m_ccLicense = license;
}
/**
*
* @return
*/
public String getLicense()
{
return m_ccLicense;
}
/**
* Record a value for instructions to be displayed to the user in the editor (for Form Items).
* @param instruction The value of the instructions.
*/
public void setInstruction(String instruction)
{
if(instruction == null)
{
instruction = "";
}
m_instruction = instruction.trim();
}
/**
* Access instructions to be displayed to the user in the editor (for Form Items).
* @return The instructions.
*/
public String getInstruction()
{
return m_instruction;
}
/**
* Set the character encoding type that will be used when converting content body between strings and byte arrays.
* Default is "UTF-8".
* @param encoding A valid name for a character set encoding scheme (@see java.lang.Charset)
*/
public void setEncoding(String encoding)
{
m_encoding = encoding;
}
/**
* Get the character encoding type that is used when converting content body between strings and byte arrays.
* Default is "UTF-8".
* @return The name of the character set encoding scheme (@see java.lang.Charset)
*/
public String getEncoding()
{
return m_encoding;
}
/**
* Set marker indicating whether current item is a blank entry
* @param isBlank
*/
public void markAsBlank(boolean isBlank)
{
m_isBlank = isBlank;
}
/**
* Access marker indicating whether current item is a blank entry
* @return true if current entry is blank, false otherwise
*/
public boolean isBlank()
{
return m_isBlank;
}
/**
* Change the root ResourcesMetadata object that defines the form for a Structured Artifact.
* @param form
*/
public void setForm(ResourcesMetadata form)
{
m_form = form;
}
/**
* Access the root ResourcesMetadata object that defines the form for a Structured Artifact.
* @return the form.
*/
public ResourcesMetadata getForm()
{
return m_form;
}
/**
* @param properties
*/
public void setProperties(List properties)
{
m_properties = properties;
}
public List getProperties()
{
return m_properties;
}
/**
* Replace current values of Structured Artifact with new values.
* @param map The new values.
*/
public void setValues(Map map)
{
m_structuredArtifact = map;
}
/**
* Access the entire set of values stored in the Structured Artifact
* @return The set of values.
*/
public Map getValues()
{
return m_structuredArtifact;
}
/**
* @param id
* @param name
* @param type
*/
public EditItem(String type)
{
this(null, "", type);
}
/**
* @param id
*/
public void setId(String id)
{
m_id = id;
}
/**
* Show the indicated metadata group for the item
* @param group
*/
public void showMetadataGroup(String group)
{
m_metadataGroupsShowing.add(group);
}
/**
* Hide the indicated metadata group for the item
* @param group
*/
public void hideMetadataGroup(String group)
{
m_metadataGroupsShowing.remove(group);
m_metadataGroupsShowing.remove(Validator.escapeUrl(group));
}
/**
* Query whether the indicated metadata group is showing for the item
* @param group
* @return true if the metadata group is showing, false otherwise
*/
public boolean isGroupShowing(String group)
{
return m_metadataGroupsShowing.contains(group) || m_metadataGroupsShowing.contains(Validator.escapeUrl(group));
}
/**
* @return
*/
public boolean isFileUpload()
{
return !isFolder() && !isUrl() && !isHtml() && !isPlaintext() && !isStructuredArtifact();
}
/**
* @param type
*/
public void setType(String type)
{
m_type = type;
}
/**
* @param mimetype
*/
public void setMimeType(String mimetype)
{
m_mimetype = mimetype;
}
public String getRightsownership()
{
return m_ccRightsownership;
}
public void setRightsownership(String owner)
{
m_ccRightsownership = owner;
}
/**
* @return
*/
public String getMimeType()
{
return m_mimetype;
}
public String getMimeCategory()
{
if(this.m_mimetype == null || this.m_mimetype.equals(""))
{
return "";
}
int index = this.m_mimetype.indexOf("/");
if(index < 0)
{
return this.m_mimetype;
}
return this.m_mimetype.substring(0, index);
}
public String getMimeSubtype()
{
if(this.m_mimetype == null || this.m_mimetype.equals(""))
{
return "";
}
int index = this.m_mimetype.indexOf("/");
if(index < 0 || index + 1 == this.m_mimetype.length())
{
return "";
}
return this.m_mimetype.substring(index + 1);
}
/**
* @param formtype
*/
public void setFormtype(String formtype)
{
m_formtype = formtype;
}
/**
* @return
*/
public String getFormtype()
{
return m_formtype;
}
/**
* @return Returns the copyrightInfo.
*/
public String getCopyrightInfo() {
return m_copyrightInfo;
}
/**
* @param copyrightInfo The copyrightInfo to set.
*/
public void setCopyrightInfo(String copyrightInfo) {
m_copyrightInfo = copyrightInfo;
}
/**
* @return Returns the copyrightStatus.
*/
public String getCopyrightStatus() {
return m_copyrightStatus;
}
/**
* @param copyrightStatus The copyrightStatus to set.
*/
public void setCopyrightStatus(String copyrightStatus) {
m_copyrightStatus = copyrightStatus;
}
/**
* @return Returns the description.
*/
public String getDescription() {
return m_description;
}
/**
* @param description The description to set.
*/
public void setDescription(String description) {
m_description = description;
}
/**
* @return Returns the filename.
*/
public String getFilename() {
return m_filename;
}
/**
* @param filename The filename to set.
*/
public void setFilename(String filename) {
m_filename = filename;
}
/**
* @return Returns the metadata.
*/
public Map getMetadata() {
return m_metadata;
}
/**
* @param metadata The metadata to set.
*/
public void setMetadata(Map metadata) {
m_metadata = metadata;
}
/**
* @param name
* @param value
*/
public void setMetadataItem(String name, Object value)
{
m_metadata.put(name, value);
}
/**
* @return Returns the pubview.
*/
public boolean isPubview() {
return m_pubview;
}
/**
* @param pubview The pubview to set.
*/
public void setPubview(boolean pubview) {
m_pubview = pubview;
}
/**
* @return Returns the pubviewset.
*/
public boolean isPubviewset() {
return m_pubviewset;
}
/**
* @param pubviewset The pubviewset to set.
*/
public void setPubviewset(boolean pubviewset) {
m_pubviewset = pubviewset;
}
/**
* @return Returns the content.
*/
public byte[] getContent() {
return m_content;
}
/**
* @return Returns the content as a String.
*/
public String getContentstring()
{
String rv = "";
if(m_content != null && m_content.length > 0)
{
try
{
rv = new String( m_content, m_encoding );
}
catch(UnsupportedEncodingException e)
{
rv = new String( m_content );
}
}
return rv;
}
/**
* @param content The content to set.
*/
public void setContent(byte[] content) {
m_content = content;
}
/**
* @param content The content to set.
*/
public void setContent(String content) {
try
{
m_content = content.getBytes(m_encoding);
}
catch(UnsupportedEncodingException e)
{
m_content = content.getBytes();
}
}
/**
* @return Returns the canSetQuota.
*/
public boolean canSetQuota() {
return m_canSetQuota;
}
/**
* @param canSetQuota The canSetQuota to set.
*/
public void setCanSetQuota(boolean canSetQuota) {
m_canSetQuota = canSetQuota;
}
/**
* @return Returns the hasQuota.
*/
public boolean hasQuota() {
return m_hasQuota;
}
/**
* @param hasQuota The hasQuota to set.
*/
public void setHasQuota(boolean hasQuota) {
m_hasQuota = hasQuota;
}
/**
* @return Returns the quota.
*/
public String getQuota() {
return m_quota;
}
/**
* @param quota The quota to set.
*/
public void setQuota(String quota) {
m_quota = quota;
}
/**
* @return true if content-type of item indicates it represents a URL, false otherwise
*/
public boolean isUrl()
{
return TYPE_URL.equals(m_type) || ResourceProperties.TYPE_URL.equals(m_mimetype);
}
/**
* @return true if content-type of item indicates it represents a URL, false otherwise
*/
public boolean isStructuredArtifact()
{
return TYPE_FORM.equals(m_type);
}
/**
* @return true if content-type of item is "text/text" (plain text), false otherwise
*/
public boolean isPlaintext()
{
return MIME_TYPE_DOCUMENT_PLAINTEXT.equals(m_mimetype) || MIME_TYPE_DOCUMENT_PLAINTEXT.equals(m_type);
}
/**
* @return true if content-type of item is "text/html" (an html document), false otherwise
*/
public boolean isHtml()
{
return MIME_TYPE_DOCUMENT_HTML.equals(m_mimetype) || MIME_TYPE_DOCUMENT_HTML.equals(m_type);
}
public boolean contentHasChanged()
{
return m_contentHasChanged;
}
public void setContentHasChanged(boolean changed)
{
m_contentHasChanged = changed;
}
public boolean contentTypeHasChanged()
{
return m_contentTypeHasChanged;
}
public void setContentTypeHasChanged(boolean changed)
{
m_contentTypeHasChanged = changed;
}
public void setNotification(int notification)
{
m_notification = notification;
}
public int getNotification()
{
return m_notification;
}
/**
* @return Returns the artifact.
*/
public Map getStructuredArtifact()
{
return m_structuredArtifact;
}
/**
* @param artifact The artifact to set.
*/
public void setStructuredArtifact(Map artifact)
{
this.m_structuredArtifact = artifact;
}
/**
* @param name
* @param value
*/
public void setValue(String name, Object value)
{
setValue(name, 0, value);
}
/**
* @param name
* @param index
* @param value
*/
public void setValue(String name, int index, Object value)
{
List list = getList(name);
try
{
list.set(index, value);
}
catch(ArrayIndexOutOfBoundsException e)
{
list.add(value);
}
m_structuredArtifact.put(name, list);
}
/**
* Access a value of a structured artifact field of type String.
* @param name The name of the field to access.
* @return the value, or null if the named field is null or not a String.
*/
public String getString(String name)
{
if(m_structuredArtifact == null)
{
m_structuredArtifact = new Hashtable();
}
Object value = m_structuredArtifact.get(name);
String rv = "";
if(value == null)
{
// do nothing
}
else if(value instanceof String)
{
rv = (String) value;
}
else
{
rv = value.toString();
}
return rv;
}
public Object getValue(String name, int index)
{
List list = getList(name);
Object rv = null;
try
{
rv = list.get(index);
}
catch(ArrayIndexOutOfBoundsException e)
{
// return null
}
return rv;
}
public Object getPropertyValue(String name)
{
return getPropertyValue(name, 0);
}
/**
* Access a particular value in a Structured Artifact, as identified by the parameter "name". This
* implementation of the method assumes that the name is a series of String identifiers delimited
* by the ResourcesAction.ResourcesMetadata.DOT String.
* @param name The delimited identifier for the item.
* @return The value identified by the name, or null if the name does not identify a valid item.
*/
public Object getPropertyValue(String name, int index)
{
String[] names = name.split(ResourcesMetadata.DOT);
Object rv = null;
if(m_properties == null)
{
m_properties = new Vector();
}
Iterator it = m_properties.iterator();
while(rv == null && it.hasNext())
{
ResourcesMetadata prop = (ResourcesMetadata) it.next();
if(name.equals(prop.getDottedname()))
{
rv = prop.getValue(index);
}
}
return rv;
}
public void setPropertyValue(String name, Object value)
{
setPropertyValue(name, 0, value);
}
/**
* Access a particular value in a Structured Artifact, as identified by the parameter "name". This
* implementation of the method assumes that the name is a series of String identifiers delimited
* by the ResourcesAction.ResourcesMetadata.DOT String.
* @param name The delimited identifier for the item.
* @return The value identified by the name, or null if the name does not identify a valid item.
*/
public void setPropertyValue(String name, int index, Object value)
{
if(m_properties == null)
{
m_properties = new Vector();
}
boolean found = false;
Iterator it = m_properties.iterator();
while(!found && it.hasNext())
{
ResourcesMetadata prop = (ResourcesMetadata) it.next();
if(name.equals(prop.getDottedname()))
{
found = true;
prop.setValue(index, value);
}
}
}
/**
* Access a particular value in a Structured Artifact, as identified by the parameter "name". This
* implementation of the method assumes that the name is a series of String identifiers delimited
* by the ResourcesAction.ResourcesMetadata.DOT String.
* @param name The delimited identifier for the item.
* @return The value identified by the name, or null if the name does not identify a valid item.
*/
public Object getValue(String name)
{
String[] names = name.split(ResourcesMetadata.DOT);
Object rv = m_structuredArtifact;
if(rv != null && (rv instanceof Map) && ((Map) rv).isEmpty())
{
rv = null;
}
for(int i = 1; rv != null && i < names.length; i++)
{
if(rv instanceof Map)
{
rv = ((Map) rv).get(names[i]);
}
else
{
rv = null;
}
}
return rv;
}
/**
* Access a list of values associated with a named property of a structured artifact.
* @param name The name of the property.
* @return The list of values associated with that name, or an empty list if the property is not defined.
*/
public List getList(String name)
{
if(m_structuredArtifact == null)
{
m_structuredArtifact = new Hashtable();
}
Object value = m_structuredArtifact.get(name);
List rv = new Vector();
if(value == null)
{
m_structuredArtifact.put(name, rv);
}
else if(value instanceof Collection)
{
rv.addAll((Collection)value);
}
else
{
rv.add(value);
}
return rv;
}
/**
* @return
*/
/*
public Element exportStructuredArtifact(List properties)
{
return null;
}
*/
/**
* @return Returns the name of the root of a structured artifact definition.
*/
public String getRootname()
{
return m_rootname;
}
/**
* @param rootname The name to be assigned for the root of a structured artifact.
*/
public void setRootname(String rootname)
{
m_rootname = rootname;
}
/**
* Add a property name to the list of properties missing from the input.
* @param propname The name of the property.
*/
public void setMissing(String propname)
{
m_missingInformation.add(propname);
}
/**
* Query whether a particular property is missing
* @param propname The name of the property
* @return The value "true" if the property is missing, "false" otherwise.
*/
public boolean isMissing(String propname)
{
return m_missingInformation.contains(propname) || m_missingInformation.contains(Validator.escapeUrl(propname));
}
/**
* Empty the list of missing properties.
*/
public void clearMissing()
{
m_missingInformation.clear();
}
public void setAdded(boolean added)
{
m_hasBeenAdded = added;
}
public boolean hasBeenAdded()
{
return m_hasBeenAdded;
}
} // inner class EditItem
/**
* Inner class encapsulates information about folders (and final item?) in a collection path (a.k.a. breadcrumb)
*/
public static class PathItem
{
protected String m_url;
protected String m_name;
protected String m_id;
protected boolean m_canRead;
protected boolean m_isFolder;
protected boolean m_isLast;
protected String m_root;
protected boolean m_isLocal;
public PathItem(String id, String name)
{
m_id = id;
m_name = name;
m_canRead = false;
m_isFolder = false;
m_isLast = false;
m_url = "";
m_isLocal = true;
}
/**
* @return
*/
public boolean canRead()
{
return m_canRead;
}
/**
* @return
*/
public String getId()
{
return m_id;
}
/**
* @return
*/
public boolean isFolder()
{
return m_isFolder;
}
/**
* @return
*/
public boolean isLast()
{
return m_isLast;
}
/**
* @return
*/
public String getName()
{
return m_name;
}
/**
* @param canRead
*/
public void setCanRead(boolean canRead)
{
m_canRead = canRead;
}
/**
* @param id
*/
public void setId(String id)
{
m_id = id;
}
/**
* @param isFolder
*/
public void setIsFolder(boolean isFolder)
{
m_isFolder = isFolder;
}
/**
* @param isLast
*/
public void setLast(boolean isLast)
{
m_isLast = isLast;
}
/**
* @param name
*/
public void setName(String name)
{
m_name = name;
}
/**
* @return
*/
public String getUrl()
{
return m_url;
}
/**
* @param url
*/
public void setUrl(String url)
{
m_url = url;
}
/**
* @param root
*/
public void setRoot(String root)
{
m_root = root;
}
/**
* @return
*/
public String getRoot()
{
return m_root;
}
public void setIsLocal(boolean isLocal)
{
m_isLocal = isLocal;
}
public boolean isLocal()
{
return m_isLocal;
}
} // inner class PathItem
/**
*
* inner class encapsulates information about groups of metadata tags (such as DC, LOM, etc.)
*
*/
public static class MetadataGroup
extends Vector
{
/**
*
*/
private static final long serialVersionUID = -821054142728929236L;
protected String m_name;
protected boolean m_isShowing;
/**
* @param name
*/
public MetadataGroup(String name)
{
super();
m_name = name;
m_isShowing = false;
}
/**
* @return
*/
public boolean isShowing()
{
return m_isShowing;
}
/**
* @param isShowing
*/
public void setShowing(boolean isShowing)
{
m_isShowing = isShowing;
}
/**
* @return
*/
public String getName()
{
return m_name;
}
/**
* @param name
*/
public void setName(String name)
{
m_name = name;
}
/* (non-Javadoc)
* @see java.lang.Object#equals(java.lang.Object)
* needed to determine List.contains()
*/
public boolean equals(Object obj)
{
MetadataGroup mg = (MetadataGroup) obj;
boolean rv = (obj != null) && (m_name.equals(mg));
return rv;
}
}
public static class AttachItem
{
protected String m_id;
protected String m_displayName;
protected String m_accessUrl;
protected String m_collectionId;
protected String m_contentType;
/**
* @param id
* @param displayName
* @param collectionId
* @param accessUrl
*/
public AttachItem(String id, String displayName, String collectionId, String accessUrl)
{
m_id = id;
m_displayName = displayName;
m_collectionId = collectionId;
m_accessUrl = accessUrl;
}
/**
* @return Returns the accessUrl.
*/
public String getAccessUrl()
{
return m_accessUrl;
}
/**
* @param accessUrl The accessUrl to set.
*/
public void setAccessUrl(String accessUrl)
{
m_accessUrl = accessUrl;
}
/**
* @return Returns the collectionId.
*/
public String getCollectionId()
{
return m_collectionId;
}
/**
* @param collectionId The collectionId to set.
*/
public void setCollectionId(String collectionId)
{
m_collectionId = collectionId;
}
/**
* @return Returns the id.
*/
public String getId()
{
return m_id;
}
/**
* @param id The id to set.
*/
public void setId(String id)
{
m_id = id;
}
/**
* @return Returns the name.
*/
public String getDisplayName()
{
String displayName = m_displayName;
if(displayName == null || displayName.trim().equals(""))
{
displayName = isolateName(m_id);
}
return displayName;
}
/**
* @param name The name to set.
*/
public void setDisplayName(String name)
{
m_displayName = name;
}
/**
* @return Returns the contentType.
*/
public String getContentType()
{
return m_contentType;
}
/**
* @param contentType
*/
public void setContentType(String contentType)
{
this.m_contentType = contentType;
}
} // Inner class AttachItem
public static class ElementCarrier
{
protected Element element;
protected String parent;
public ElementCarrier(Element element, String parent)
{
this.element = element;
this.parent = parent;
}
public Element getElement()
{
return element;
}
public void setElement(Element element)
{
this.element = element;
}
public String getParent()
{
return parent;
}
public void setParent(String parent)
{
this.parent = parent;
}
}
public static class SaveArtifactAttempt
{
protected EditItem item;
protected List errors;
protected SchemaNode schema;
public SaveArtifactAttempt(EditItem item, SchemaNode schema)
{
this.item = item;
this.schema = schema;
}
/**
* @return Returns the errors.
*/
public List getErrors()
{
return errors;
}
/**
* @param errors The errors to set.
*/
public void setErrors(List errors)
{
this.errors = errors;
}
/**
* @return Returns the item.
*/
public EditItem getItem()
{
return item;
}
/**
* @param item The item to set.
*/
public void setItem(EditItem item)
{
this.item = item;
}
/**
* @return Returns the schema.
*/
public SchemaNode getSchema()
{
return schema;
}
/**
* @param schema The schema to set.
*/
public void setSchema(SchemaNode schema)
{
this.schema = schema;
}
}
/**
* Develop a list of all the site collections that there are to page.
* Sort them as appropriate, and apply search criteria.
*/
protected static List readAllResources(SessionState state)
{
List other_sites = new Vector();
String collectionId = (String) state.getAttribute (STATE_ATTACH_COLLECTION_ID);
if(collectionId == null)
{
collectionId = (String) state.getAttribute (STATE_COLLECTION_ID);
}
HashMap expandedCollections = (HashMap) state.getAttribute(STATE_EXPANDED_COLLECTIONS);
// set the sort values
String sortedBy = (String) state.getAttribute (STATE_SORT_BY);
String sortedAsc = (String) state.getAttribute (STATE_SORT_ASC);
Boolean showRemove = (Boolean) state.getAttribute(STATE_SHOW_REMOVE_ACTION);
boolean showRemoveAction = showRemove != null && showRemove.booleanValue();
Boolean showMove = (Boolean) state.getAttribute(STATE_SHOW_MOVE_ACTION);
boolean showMoveAction = showMove != null && showMove.booleanValue();
Boolean showCopy = (Boolean) state.getAttribute(STATE_SHOW_COPY_ACTION);
boolean showCopyAction = showCopy != null && showCopy.booleanValue();
Set highlightedItems = (Set) state.getAttribute(STATE_HIGHLIGHTED_ITEMS);
// add user's personal workspace
User user = UserDirectoryService.getCurrentUser();
String userId = user.getId();
String userName = user.getDisplayName();
String wsId = SiteService.getUserSiteId(userId);
String wsCollectionId = ContentHostingService.getSiteCollection(wsId);
if(! collectionId.equals(wsCollectionId))
{
List members = getBrowseItems(wsCollectionId, expandedCollections, highlightedItems, sortedBy, sortedAsc, (BrowseItem) null, false, state);
if(members != null && members.size() > 0)
{
BrowseItem root = (BrowseItem) members.remove(0);
showRemoveAction = showRemoveAction || root.hasDeletableChildren();
showMoveAction = showMoveAction || root.hasDeletableChildren();
showCopyAction = showCopyAction || root.hasCopyableChildren();
root.addMembers(members);
root.setName(userName + " " + rb.getString("gen.wsreso"));
other_sites.add(root);
}
}
// add all other sites user has access to
/*
* NOTE: This does not (and should not) get all sites for admin.
* Getting all sites for admin is too big a request and
* would result in too big a display to render in html.
*/
Map othersites = ContentHostingService.getCollectionMap();
Iterator siteIt = othersites.keySet().iterator();
SortedSet sort = new TreeSet();
while(siteIt.hasNext())
{
String collId = (String) siteIt.next();
String displayName = (String) othersites.get(collId);
sort.add(displayName + DELIM + collId);
}
Iterator sortIt = sort.iterator();
while(sortIt.hasNext())
{
String item = (String) sortIt.next();
String displayName = item.substring(0, item.lastIndexOf(DELIM));
String collId = item.substring(item.lastIndexOf(DELIM) + 1);
if(! collectionId.equals(collId) && ! wsCollectionId.equals(collId))
{
List members = getBrowseItems(collId, expandedCollections, highlightedItems, sortedBy, sortedAsc, (BrowseItem) null, false, state);
if(members != null && members.size() > 0)
{
BrowseItem root = (BrowseItem) members.remove(0);
root.addMembers(members);
root.setName(displayName);
other_sites.add(root);
}
}
}
return other_sites;
}
/**
* Prepare the current page of site collections to display.
* @return List of BrowseItem objects to display on this page.
*/
protected static List prepPage(SessionState state)
{
List rv = new Vector();
// access the page size
int pageSize = ((Integer) state.getAttribute(STATE_PAGESIZE)).intValue();
// cleanup prior prep
state.removeAttribute(STATE_NUM_MESSAGES);
// are we going next or prev, first or last page?
boolean goNextPage = state.getAttribute(STATE_GO_NEXT_PAGE) != null;
boolean goPrevPage = state.getAttribute(STATE_GO_PREV_PAGE) != null;
boolean goFirstPage = state.getAttribute(STATE_GO_FIRST_PAGE) != null;
boolean goLastPage = state.getAttribute(STATE_GO_LAST_PAGE) != null;
state.removeAttribute(STATE_GO_NEXT_PAGE);
state.removeAttribute(STATE_GO_PREV_PAGE);
state.removeAttribute(STATE_GO_FIRST_PAGE);
state.removeAttribute(STATE_GO_LAST_PAGE);
// are we going next or prev message?
boolean goNext = state.getAttribute(STATE_GO_NEXT) != null;
boolean goPrev = state.getAttribute(STATE_GO_PREV) != null;
state.removeAttribute(STATE_GO_NEXT);
state.removeAttribute(STATE_GO_PREV);
// read all channel messages
List allMessages = readAllResources(state);
if (allMessages == null)
{
return rv;
}
String messageIdAtTheTopOfThePage = null;
Object topMsgId = state.getAttribute(STATE_TOP_PAGE_MESSAGE);
if(topMsgId == null)
{
// do nothing
}
else if(topMsgId instanceof Integer)
{
messageIdAtTheTopOfThePage = ((Integer) topMsgId).toString();
}
else if(topMsgId instanceof String)
{
messageIdAtTheTopOfThePage = (String) topMsgId;
}
// if we have no prev page and do have a top message, then we will stay "pinned" to the top
boolean pinToTop = ( (messageIdAtTheTopOfThePage != null)
&& (state.getAttribute(STATE_PREV_PAGE_EXISTS) == null)
&& !goNextPage && !goPrevPage && !goNext && !goPrev && !goFirstPage && !goLastPage);
// if we have no next page and do have a top message, then we will stay "pinned" to the bottom
boolean pinToBottom = ( (messageIdAtTheTopOfThePage != null)
&& (state.getAttribute(STATE_NEXT_PAGE_EXISTS) == null)
&& !goNextPage && !goPrevPage && !goNext && !goPrev && !goFirstPage && !goLastPage);
// how many messages, total
int numMessages = allMessages.size();
if (numMessages == 0)
{
return rv;
}
// save the number of messges
state.setAttribute(STATE_NUM_MESSAGES, new Integer(numMessages));
// find the position of the message that is the top first on the page
int posStart = 0;
if (messageIdAtTheTopOfThePage != null)
{
// find the next page
posStart = findResourceInList(allMessages, messageIdAtTheTopOfThePage);
// if missing, start at the top
if (posStart == -1)
{
posStart = 0;
}
}
// if going to the next page, adjust
if (goNextPage)
{
posStart += pageSize;
}
// if going to the prev page, adjust
else if (goPrevPage)
{
posStart -= pageSize;
if (posStart < 0) posStart = 0;
}
// if going to the first page, adjust
else if (goFirstPage)
{
posStart = 0;
}
// if going to the last page, adjust
else if (goLastPage)
{
posStart = numMessages - pageSize;
if (posStart < 0) posStart = 0;
}
// pinning
if (pinToTop)
{
posStart = 0;
}
else if (pinToBottom)
{
posStart = numMessages - pageSize;
if (posStart < 0) posStart = 0;
}
// get the last page fully displayed
if (posStart + pageSize > numMessages)
{
posStart = numMessages - pageSize;
if (posStart < 0) posStart = 0;
}
// compute the end to a page size, adjusted for the number of messages available
int posEnd = posStart + (pageSize-1);
if (posEnd >= numMessages) posEnd = numMessages-1;
int numMessagesOnThisPage = (posEnd - posStart) + 1;
// select the messages on this page
for (int i = posStart; i <= posEnd; i++)
{
rv.add(allMessages.get(i));
}
// save which message is at the top of the page
BrowseItem itemAtTheTopOfThePage = (BrowseItem) allMessages.get(posStart);
state.setAttribute(STATE_TOP_PAGE_MESSAGE, itemAtTheTopOfThePage.getId());
state.setAttribute(STATE_TOP_MESSAGE_INDEX, new Integer(posStart));
// which message starts the next page (if any)
int next = posStart + pageSize;
if (next < numMessages)
{
state.setAttribute(STATE_NEXT_PAGE_EXISTS, "");
}
else
{
state.removeAttribute(STATE_NEXT_PAGE_EXISTS);
}
// which message ends the prior page (if any)
int prev = posStart - 1;
if (prev >= 0)
{
state.setAttribute(STATE_PREV_PAGE_EXISTS, "");
}
else
{
state.removeAttribute(STATE_PREV_PAGE_EXISTS);
}
if (state.getAttribute(STATE_VIEW_ID) != null)
{
int viewPos = findResourceInList(allMessages, (String) state.getAttribute(STATE_VIEW_ID));
// are we moving to the next message
if (goNext)
{
// advance
viewPos++;
if (viewPos >= numMessages) viewPos = numMessages-1;
}
// are we moving to the prev message
if (goPrev)
{
// retreat
viewPos--;
if (viewPos < 0) viewPos = 0;
}
// update the view message
state.setAttribute(STATE_VIEW_ID, ((BrowseItem) allMessages.get(viewPos)).getId());
// if the view message is no longer on the current page, adjust the page
// Note: next time through this will get processed
if (viewPos < posStart)
{
state.setAttribute(STATE_GO_PREV_PAGE, "");
}
else if (viewPos > posEnd)
{
state.setAttribute(STATE_GO_NEXT_PAGE, "");
}
if (viewPos > 0)
{
state.setAttribute(STATE_PREV_EXISTS,"");
}
else
{
state.removeAttribute(STATE_PREV_EXISTS);
}
if (viewPos < numMessages-1)
{
state.setAttribute(STATE_NEXT_EXISTS,"");
}
else
{
state.removeAttribute(STATE_NEXT_EXISTS);
}
}
return rv;
} // prepPage
/**
* Find the resource with this id in the list.
* @param messages The list of messages.
* @param id The message id.
* @return The index position in the list of the message with this id, or -1 if not found.
*/
protected static int findResourceInList(List resources, String id)
{
for (int i = 0; i < resources.size(); i++)
{
// if this is the one, return this index
if (((BrowseItem) (resources.get(i))).getId().equals(id)) return i;
}
// not found
return -1;
} // findResourceInList
protected static User getUserProperty(ResourceProperties props, String name)
{
String id = props.getProperty(name);
if (id != null)
{
try
{
return UserDirectoryService.getUser(id);
}
catch (UserNotDefinedException e)
{
}
}
return null;
}
/**
* Find the resource name of a given resource id or filepath.
*
* @param id
* The resource id.
* @return the resource name.
*/
protected static String isolateName(String id)
{
if (id == null) return null;
if (id.length() == 0) return null;
// take after the last resource path separator, not counting one at the very end if there
boolean lastIsSeparator = id.charAt(id.length() - 1) == '/';
return id.substring(id.lastIndexOf('/', id.length() - 2) + 1, (lastIsSeparator ? id.length() - 1 : id.length()));
} // isolateName
} // ResourcesAction
| public void doHandlepaste ( RunData data)
{
ParameterParser params = data.getParameters ();
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
// get the cut items to be pasted
Vector pasteCutItems = (Vector) state.getAttribute (STATE_CUT_IDS);
// get the copied items to be pasted
Vector pasteCopiedItems = (Vector) state.getAttribute (STATE_COPIED_IDS);
String collectionId = params.getString ("collectionId");
String originalDisplayName = NULL_STRING;
// handle cut and paste
if (((String) state.getAttribute (STATE_CUT_FLAG)).equals (Boolean.TRUE.toString()))
{
for (int i = 0; i < pasteCutItems.size (); i++)
{
String currentPasteCutItem = (String) pasteCutItems.get (i);
try
{
ResourceProperties properties = ContentHostingService.getProperties (currentPasteCutItem);
originalDisplayName = properties.getPropertyFormatted (ResourceProperties.PROP_DISPLAY_NAME);
/*
if (Boolean.TRUE.toString().equals(properties.getProperty (ResourceProperties.PROP_IS_COLLECTION)))
{
String alert = (String) state.getAttribute(STATE_MESSAGE);
if (alert == null || ((alert != null) && (alert.indexOf(RESOURCE_INVALID_OPERATION_ON_COLLECTION_STRING) == -1)))
{
addAlert(state, RESOURCE_INVALID_OPERATION_ON_COLLECTION_STRING);
}
}
else
{
*/
// paste the resource
ContentResource resource = ContentHostingService.getResource (currentPasteCutItem);
ResourceProperties p = ContentHostingService.getProperties(currentPasteCutItem);
String id = collectionId + Validator.escapeResourceName(p.getProperty(ResourceProperties.PROP_DISPLAY_NAME));
// cut-paste to the same collection?
boolean cutPasteSameCollection = false;
String displayName = p.getProperty(ResourceProperties.PROP_DISPLAY_NAME);
// till paste successfully or it fails
ResourcePropertiesEdit resourceProperties = ContentHostingService.newResourceProperties ();
// add the properties of the pasted item
Iterator propertyNames = properties.getPropertyNames ();
while ( propertyNames.hasNext ())
{
String propertyName = (String) propertyNames.next ();
if (!properties.isLiveProperty (propertyName))
{
if (propertyName.equals (ResourceProperties.PROP_DISPLAY_NAME)&&(displayName.length ()>0))
{
resourceProperties.addProperty (propertyName, displayName);
}
else
{
resourceProperties.addProperty (propertyName, properties.getProperty (propertyName));
} // if-else
} // if
} // while
try
{
// paste the cutted resource to the new collection - no notification
ContentResource newResource = ContentHostingService.addResource (id, resource.getContentType (), resource.getContent (), resourceProperties, NotificationService.NOTI_NONE);
String uuid = ContentHostingService.getUuid(resource.getId());
ContentHostingService.setUuid(id, uuid);
}
catch (InconsistentException e)
{
addAlert(state,RESOURCE_INVALID_TITLE_STRING);
}
catch (OverQuotaException e)
{
addAlert(state, rb.getString("overquota"));
}
catch (IdInvalidException e)
{
addAlert(state, rb.getString("title") + " " + e.getMessage ());
}
catch(ServerOverloadException e)
{
// this represents temporary unavailability of server's filesystem
// for server configured to save resource body in filesystem
addAlert(state, rb.getString("failed"));
}
catch (IdUsedException e)
{
// cut and paste to the same collection; stop adding new resource
if (id.equals(currentPasteCutItem))
{
cutPasteSameCollection = true;
}
else
{
addAlert(state, rb.getString("notaddreso") + " " + id + rb.getString("used2"));
/*
// pasted to the same folder as before; add "Copy of "/ "copy (n) of" to the id
if (countNumber==1)
{
displayName = DUPLICATE_STRING + p.getProperty(ResourceProperties.PROP_DISPLAY_NAME);
id = collectionId + Validator.escapeResourceName(displayName);
}
else
{
displayName = "Copy (" + countNumber + ") of " + p.getProperty(ResourceProperties.PROP_DISPLAY_NAME);
id = collectionId + Validator.escapeResourceName(displayName);
}
countNumber++;
*/
}
} // try-catch
catch(RuntimeException e)
{
logger.error("ResourcesAction.doHandlepaste ***** Unknown Exception ***** " + e.getMessage());
addAlert(state, rb.getString("failed"));
}
if (!cutPasteSameCollection)
{
// remove the cutted resource
ContentHostingService.removeResource (currentPasteCutItem);
}
// } // if-else
}
catch (InUseException e)
{
addAlert(state, rb.getString("someone") + " " + originalDisplayName + ". ");
}
catch (PermissionException e)
{
addAlert(state, rb.getString("notpermis7") + " " + originalDisplayName + ". ");
}
catch (IdUnusedException e)
{
addAlert(state,RESOURCE_NOT_EXIST_STRING);
}
catch (TypeException e)
{
addAlert(state, rb.getString("pasteitem") + " " + originalDisplayName + " " + rb.getString("mismatch"));
} // try-catch
catch(RuntimeException e)
{
logger.error("ResourcesAction.doHandlepaste ***** Unknown Exception ***** " + e.getMessage());
addAlert(state, rb.getString("failed"));
}
} // for
} // cut
// handling copy and paste
if (Boolean.toString(true).equalsIgnoreCase((String) state.getAttribute (STATE_COPY_FLAG)))
{
for (int i = 0; i < pasteCopiedItems.size (); i++)
{
String currentPasteCopiedItem = (String) pasteCopiedItems.get (i);
try
{
ResourceProperties properties = ContentHostingService.getProperties (currentPasteCopiedItem);
originalDisplayName = properties.getPropertyFormatted (ResourceProperties.PROP_DISPLAY_NAME);
// copy, cut and paste not operated on collections
if (properties.getProperty (ResourceProperties.PROP_IS_COLLECTION).equals (Boolean.TRUE.toString()))
{
String alert = (String) state.getAttribute(STATE_MESSAGE);
if (alert == null || ((alert != null) && (alert.indexOf(RESOURCE_INVALID_OPERATION_ON_COLLECTION_STRING) == -1)))
{
addAlert(state, RESOURCE_INVALID_OPERATION_ON_COLLECTION_STRING);
}
}
else
{
// paste the resource
ContentResource resource = ContentHostingService.getResource (currentPasteCopiedItem);
ResourceProperties p = ContentHostingService.getProperties(currentPasteCopiedItem);
String displayName = DUPLICATE_STRING + p.getProperty(ResourceProperties.PROP_DISPLAY_NAME);
String id = collectionId + Validator.escapeResourceName(displayName);
ResourcePropertiesEdit resourceProperties = ContentHostingService.newResourceProperties ();
// add the properties of the pasted item
Iterator propertyNames = properties.getPropertyNames ();
while ( propertyNames.hasNext ())
{
String propertyName = (String) propertyNames.next ();
if (!properties.isLiveProperty (propertyName))
{
if (propertyName.equals (ResourceProperties.PROP_DISPLAY_NAME)&&(displayName.length ()>0))
{
resourceProperties.addProperty (propertyName, displayName);
}
else
{
resourceProperties.addProperty (propertyName, properties.getProperty (propertyName));
}
}
}
try
{
// paste the copied resource to the new collection
ContentResource newResource = ContentHostingService.addResource (id, resource.getContentType (), resource.getContent (), resourceProperties, NotificationService.NOTI_NONE);
}
catch (InconsistentException e)
{
addAlert(state,RESOURCE_INVALID_TITLE_STRING);
}
catch (IdInvalidException e)
{
addAlert(state,rb.getString("title") + " " + e.getMessage ());
}
catch (OverQuotaException e)
{
addAlert(state, rb.getString("overquota"));
}
catch (ServerOverloadException e)
{
addAlert(state, rb.getString("failed"));
}
catch (IdUsedException e)
{
addAlert(state, rb.getString("notaddreso") + " " + id + rb.getString("used2"));
/*
// copying
// pasted to the same folder as before; add "Copy of " to the id
if (countNumber > 1)
{
displayName = "Copy (" + countNumber + ") of " + p.getProperty(ResourceProperties.PROP_DISPLAY_NAME);
}
else if (countNumber == 1)
{
displayName = "Copy of " + p.getProperty(ResourceProperties.PROP_DISPLAY_NAME);
}
id = collectionId + Validator.escapeResourceName(displayName);
countNumber++;
*/
} // try-catch
catch(RuntimeException e)
{
logger.error("ResourcesAction.doHandlepaste ***** Unknown Exception ***** " + e.getMessage());
addAlert(state, rb.getString("failed"));
}
} // if-else
}
catch (PermissionException e)
{
addAlert(state, rb.getString("notpermis8") + " " + originalDisplayName + ". ");
}
catch (IdUnusedException e)
{
addAlert(state,RESOURCE_NOT_EXIST_STRING);
}
catch (TypeException e)
{
addAlert(state, rb.getString("pasteitem") + " " + originalDisplayName + " " + rb.getString("mismatch"));
} // try-catch
} // for
} // copy
if (state.getAttribute(STATE_MESSAGE) == null)
{
// delete sucessful
state.setAttribute (STATE_MODE, MODE_LIST);
// reset the cut flag
if (((String)state.getAttribute (STATE_CUT_FLAG)).equals (Boolean.TRUE.toString()))
{
state.setAttribute (STATE_CUT_FLAG, Boolean.FALSE.toString());
}
// reset the copy flag
if (Boolean.toString(true).equalsIgnoreCase((String)state.getAttribute (STATE_COPY_FLAG)))
{
state.setAttribute (STATE_COPY_FLAG, Boolean.FALSE.toString());
}
// try to expand the collection
HashMap expandedCollections = (HashMap) state.getAttribute(STATE_EXPANDED_COLLECTIONS);
if(! expandedCollections.containsKey(collectionId))
{
org.sakaiproject.content.api.ContentHostingService contentService = (org.sakaiproject.content.api.ContentHostingService) state.getAttribute (STATE_CONTENT_SERVICE);
try
{
ContentCollection coll = contentService.getCollection(collectionId);
expandedCollections.put(collectionId, coll);
}
catch(Exception ignore){}
}
}
} // doHandlepaste
/**
* Paste the shortcut(s) of previously copied item(s)
*/
public void doHandlepasteshortcut ( RunData data)
{
ParameterParser params = data.getParameters ();
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
// get the items to be pasted
Vector pasteItems = new Vector ();
if (((String) state.getAttribute (STATE_COPY_FLAG)).equals (Boolean.TRUE.toString()))
{
pasteItems = (Vector) ( (Vector) state.getAttribute (STATE_COPIED_IDS)).clone ();
}
if (((String) state.getAttribute (STATE_CUT_FLAG)).equals (Boolean.TRUE.toString()))
{
addAlert(state, rb.getString("choosecp"));
}
if (state.getAttribute(STATE_MESSAGE) == null)
{
String collectionId = params.getString ("collectionId");
String originalDisplayName = NULL_STRING;
for (int i = 0; i < pasteItems.size (); i++)
{
String currentPasteItem = (String) pasteItems.get (i);
try
{
ResourceProperties properties = ContentHostingService.getProperties (currentPasteItem);
originalDisplayName = properties.getPropertyFormatted (ResourceProperties.PROP_DISPLAY_NAME);
if (properties.getProperty (ResourceProperties.PROP_IS_COLLECTION).equals (Boolean.TRUE.toString()))
{
// paste the collection
}
else
{
// paste the resource
ContentResource resource = ContentHostingService.getResource (currentPasteItem);
ResourceProperties p = ContentHostingService.getProperties(currentPasteItem);
String displayName = SHORTCUT_STRING + p.getProperty(ResourceProperties.PROP_DISPLAY_NAME);
String id = collectionId + Validator.escapeResourceName(displayName);
//int countNumber = 2;
ResourcePropertiesEdit resourceProperties = ContentHostingService.newResourceProperties ();
// add the properties of the pasted item
Iterator propertyNames = properties.getPropertyNames ();
while ( propertyNames.hasNext ())
{
String propertyName = (String) propertyNames.next ();
if ((!properties.isLiveProperty (propertyName)) && (!propertyName.equals (ResourceProperties.PROP_DISPLAY_NAME)))
{
resourceProperties.addProperty (propertyName, properties.getProperty (propertyName));
}
}
// %%%%% should be _blank for items that can be displayed in browser, _self for others
// resourceProperties.addProperty (ResourceProperties.PROP_OPEN_NEWWINDOW, "_self");
resourceProperties.addProperty (ResourceProperties.PROP_DISPLAY_NAME, displayName);
try
{
ContentResource referedResource= ContentHostingService.getResource (currentPasteItem);
ContentResource newResource = ContentHostingService.addResource (id, ResourceProperties.TYPE_URL, referedResource.getUrl().getBytes (), resourceProperties, NotificationService.NOTI_NONE);
}
catch (InconsistentException e)
{
addAlert(state, RESOURCE_INVALID_TITLE_STRING);
}
catch (OverQuotaException e)
{
addAlert(state, rb.getString("overquota"));
}
catch (IdInvalidException e)
{
addAlert(state, rb.getString("title") + " " + e.getMessage ());
}
catch (ServerOverloadException e)
{
addAlert(state, rb.getString("failed"));
}
catch (IdUsedException e)
{
addAlert(state, rb.getString("notaddreso") + " " + id + rb.getString("used2"));
/*
// pasted shortcut to the same folder as before; add countNumber to the id
displayName = "Shortcut (" + countNumber + ") to " + p.getProperty(ResourceProperties.PROP_DISPLAY_NAME);
id = collectionId + Validator.escapeResourceName(displayName);
countNumber++;
*/
} // try-catch
catch(RuntimeException e)
{
logger.error("ResourcesAction.doHandlepasteshortcut ***** Unknown Exception ***** " + e.getMessage());
addAlert(state, rb.getString("failed"));
}
} // if-else
}
catch (PermissionException e)
{
addAlert(state, rb.getString("notpermis9") + " " + currentPasteItem.substring (currentPasteItem.lastIndexOf (Entity.SEPARATOR)+1) + ". ");
}
catch (IdUnusedException e)
{
addAlert(state,RESOURCE_NOT_EXIST_STRING);
}
catch (TypeException e)
{
addAlert(state, rb.getString("pasteitem") + " " + currentPasteItem.substring (currentPasteItem.lastIndexOf (Entity.SEPARATOR)+1) + " " + rb.getString("mismatch"));
} // try-catch
} // for
}
if (state.getAttribute(STATE_MESSAGE) == null)
{
if (((String) state.getAttribute (STATE_COPY_FLAG)).equals (Boolean.TRUE.toString()))
{
// reset the copy flag
state.setAttribute (STATE_COPY_FLAG, Boolean.FALSE.toString());
}
// paste shortcut sucessful
state.setAttribute (STATE_MODE, MODE_LIST);
}
} // doHandlepasteshortcut
/**
* Edit the editable collection/resource properties
*/
public static void doEdit ( RunData data )
{
ParameterParser params = data.getParameters ();
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
Map current_stack_frame = pushOnStack(state);
state.setAttribute(STATE_LIST_SELECTIONS, new TreeSet());
// cancel copy if there is one in progress
if(! Boolean.FALSE.toString().equals(state.getAttribute (STATE_COPY_FLAG)))
{
initCopyContext(state);
}
// cancel move if there is one in progress
if(! Boolean.FALSE.toString().equals(state.getAttribute (STATE_MOVE_FLAG)))
{
initMoveContext(state);
}
String id = NULL_STRING;
id = params.getString ("id");
if(id == null || id.length() == 0)
{
// there is no resource selected, show the alert message to the user
addAlert(state, rb.getString("choosefile2"));
return;
}
current_stack_frame.put(STATE_STACK_EDIT_ID, id);
String collectionId = (String) params.getString("collectionId");
if(collectionId == null)
{
collectionId = ContentHostingService.getSiteCollection(ToolManager.getCurrentPlacement().getContext());
state.setAttribute(STATE_HOME_COLLECTION_ID, collectionId);
}
current_stack_frame.put(STATE_STACK_EDIT_COLLECTION_ID, collectionId);
EditItem item = getEditItem(id, collectionId, data);
if (state.getAttribute(STATE_MESSAGE) == null)
{
// got resource and sucessfully populated item with values
// state.setAttribute (STATE_MODE, MODE_EDIT);
state.setAttribute(ResourcesAction.STATE_RESOURCES_HELPER_MODE, ResourcesAction.MODE_ATTACHMENT_EDIT_ITEM_INIT);
state.setAttribute(STATE_EDIT_ALERTS, new HashSet());
current_stack_frame.put(STATE_STACK_EDIT_ITEM, item);
}
else
{
popFromStack(state);
}
} // doEdit
public static EditItem getEditItem(String id, String collectionId, RunData data)
{
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
Stack operations_stack = (Stack) state.getAttribute(STATE_SUSPENDED_OPERATIONS_STACK);
Map current_stack_frame = peekAtStack(state);
EditItem item = null;
// populate an EditItem object with values from the resource and return the EditItem
try
{
ResourceProperties properties = ContentHostingService.getProperties(id);
boolean isCollection = false;
try
{
isCollection = properties.getBooleanProperty(ResourceProperties.PROP_IS_COLLECTION);
}
catch(Exception e)
{
// assume isCollection is false if property is not set
}
ContentEntity entity = null;
String itemType = "";
byte[] content = null;
if(isCollection)
{
itemType = "folder";
entity = ContentHostingService.getCollection(id);
}
else
{
entity = ContentHostingService.getResource(id);
itemType = ((ContentResource) entity).getContentType();
content = ((ContentResource) entity).getContent();
}
String itemName = properties.getProperty(ResourceProperties.PROP_DISPLAY_NAME);
item = new EditItem(id, itemName, itemType);
BasicRightsAssignment rightsObj = new BasicRightsAssignment(item.getItemNum(), properties);
item.setRights(rightsObj);
String encoding = data.getRequest().getCharacterEncoding();
if(encoding != null)
{
item.setEncoding(encoding);
}
String defaultCopyrightStatus = (String) state.getAttribute(DEFAULT_COPYRIGHT);
if(defaultCopyrightStatus == null || defaultCopyrightStatus.trim().equals(""))
{
defaultCopyrightStatus = ServerConfigurationService.getString("default.copyright");
state.setAttribute(DEFAULT_COPYRIGHT, defaultCopyrightStatus);
}
item.setCopyrightStatus(defaultCopyrightStatus);
if(content != null)
{
item.setContent(content);
}
String dummyId = collectionId.trim();
if(dummyId.endsWith(Entity.SEPARATOR))
{
dummyId += "dummy";
}
else
{
dummyId += Entity.SEPARATOR + "dummy";
}
String containerId = ContentHostingService.getContainingCollectionId (id);
item.setContainer(containerId);
boolean canRead = ContentHostingService.allowGetCollection(id);
boolean canAddFolder = ContentHostingService.allowAddCollection(id);
boolean canAddItem = ContentHostingService.allowAddResource(id);
boolean canDelete = ContentHostingService.allowRemoveResource(id);
boolean canRevise = ContentHostingService.allowUpdateResource(id);
item.setCanRead(canRead);
item.setCanRevise(canRevise);
item.setCanAddItem(canAddItem);
item.setCanAddFolder(canAddFolder);
item.setCanDelete(canDelete);
// item.setIsUrl(isUrl);
AccessMode access = ((GroupAwareEntity) entity).getAccess();
if(access == null)
{
item.setAccess(AccessMode.INHERITED.toString());
}
else
{
item.setAccess(access.toString());
}
AccessMode inherited_access = ((GroupAwareEntity) entity).getInheritedAccess();
if(inherited_access == null || inherited_access.equals(AccessMode.SITE))
{
item.setInheritedAccess(AccessMode.INHERITED.toString());
}
else
{
item.setInheritedAccess(inherited_access.toString());
}
List access_groups = new Vector(((GroupAwareEntity) entity).getGroups());
if(access_groups != null)
{
Site site = SiteService.getSite(ToolManager.getCurrentPlacement().getContext());
Iterator it = access_groups.iterator();
while(it.hasNext())
{
String groupRef = (String) it.next();
Group group = site.getGroup(groupRef);
item.addGroup(group.getId());
}
}
List inherited_access_groups = new Vector(((GroupAwareEntity) entity).getInheritedGroups());
if(inherited_access_groups != null)
{
Site site = SiteService.getSite(ToolManager.getCurrentPlacement().getContext());
Iterator it = inherited_access_groups.iterator();
while(it.hasNext())
{
String groupRef = (String) it.next();
Group group = site.getGroup(groupRef);
item.addGroup(group.getId());
}
}
if(item.isUrl())
{
String url = new String(content);
item.setFilename(url);
}
else if(item.isStructuredArtifact())
{
String formtype = properties.getProperty(ResourceProperties.PROP_STRUCTOBJ_TYPE);
current_stack_frame.put(STATE_STACK_STRUCTOBJ_TYPE, formtype);
current_stack_frame.put(STATE_STACK_EDIT_ITEM, item);
setupStructuredObjects(state);
Document doc = Xml.readDocumentFromString(new String(content));
Element root = doc.getDocumentElement();
importStructuredArtifact(root, item.getForm());
List flatList = item.getForm().getFlatList();
item.setProperties(flatList);
}
else if(item.isHtml() || item.isPlaintext() || item.isFileUpload())
{
String filename = properties.getProperty(ResourceProperties.PROP_ORIGINAL_FILENAME);
if(filename == null)
{
// this is a hack to deal with the fact that original filenames were not saved for some time.
if(containerId != null && item.getId().startsWith(containerId) && containerId.length() < item.getId().length())
{
filename = item.getId().substring(containerId.length());
}
}
if(filename == null)
{
item.setFilename(itemName);
}
else
{
item.setFilename(filename);
}
}
String description = properties.getProperty(ResourceProperties.PROP_DESCRIPTION);
item.setDescription(description);
try
{
Time creTime = properties.getTimeProperty(ResourceProperties.PROP_CREATION_DATE);
String createdTime = creTime.toStringLocalShortDate() + " " + creTime.toStringLocalShort();
item.setCreatedTime(createdTime);
}
catch(Exception e)
{
String createdTime = properties.getProperty(ResourceProperties.PROP_CREATION_DATE);
item.setCreatedTime(createdTime);
}
try
{
String createdBy = getUserProperty(properties, ResourceProperties.PROP_CREATOR).getDisplayName();
item.setCreatedBy(createdBy);
}
catch(Exception e)
{
String createdBy = properties.getProperty(ResourceProperties.PROP_CREATOR);
item.setCreatedBy(createdBy);
}
try
{
Time modTime = properties.getTimeProperty(ResourceProperties.PROP_MODIFIED_DATE);
String modifiedTime = modTime.toStringLocalShortDate() + " " + modTime.toStringLocalShort();
item.setModifiedTime(modifiedTime);
}
catch(Exception e)
{
String modifiedTime = properties.getProperty(ResourceProperties.PROP_MODIFIED_DATE);
item.setModifiedTime(modifiedTime);
}
try
{
String modifiedBy = getUserProperty(properties, ResourceProperties.PROP_MODIFIED_BY).getDisplayName();
item.setModifiedBy(modifiedBy);
}
catch(Exception e)
{
String modifiedBy = properties.getProperty(ResourceProperties.PROP_MODIFIED_BY);
item.setModifiedBy(modifiedBy);
}
String url = ContentHostingService.getUrl(id);
item.setUrl(url);
String size = "";
if(properties.getProperty(ResourceProperties.PROP_CONTENT_LENGTH) != null)
{
size = properties.getPropertyFormatted(ResourceProperties.PROP_CONTENT_LENGTH) + " (" + Validator.getFileSizeWithDividor(properties.getProperty(ResourceProperties.PROP_CONTENT_LENGTH)) +" bytes)";
}
item.setSize(size);
String copyrightStatus = properties.getProperty(properties.getNamePropCopyrightChoice());
if(copyrightStatus == null || copyrightStatus.trim().equals(""))
{
copyrightStatus = (String) state.getAttribute(DEFAULT_COPYRIGHT);
}
item.setCopyrightStatus(copyrightStatus);
String copyrightInfo = properties.getPropertyFormatted(properties.getNamePropCopyright());
item.setCopyrightInfo(copyrightInfo);
String copyrightAlert = properties.getProperty(properties.getNamePropCopyrightAlert());
if("true".equalsIgnoreCase(copyrightAlert))
{
item.setCopyrightAlert(true);
}
else
{
item.setCopyrightAlert(false);
}
boolean pubviewset = ContentHostingService.isInheritingPubView(containerId) || ContentHostingService.isPubView(containerId);
item.setPubviewset(pubviewset);
boolean pubview = pubviewset;
if (!pubview)
{
pubview = ContentHostingService.isPubView(id);
}
item.setPubview(pubview);
Map metadata = new Hashtable();
List groups = (List) state.getAttribute(STATE_METADATA_GROUPS);
if(groups != null && ! groups.isEmpty())
{
Iterator it = groups.iterator();
while(it.hasNext())
{
MetadataGroup group = (MetadataGroup) it.next();
Iterator propIt = group.iterator();
while(propIt.hasNext())
{
ResourcesMetadata prop = (ResourcesMetadata) propIt.next();
String name = prop.getFullname();
String widget = prop.getWidget();
if(widget.equals(ResourcesMetadata.WIDGET_DATE) || widget.equals(ResourcesMetadata.WIDGET_DATETIME) || widget.equals(ResourcesMetadata.WIDGET_TIME))
{
Time time = TimeService.newTime();
try
{
time = properties.getTimeProperty(name);
}
catch(Exception ignore)
{
// use "now" as default in that case
}
metadata.put(name, time);
}
else
{
String value = properties.getPropertyFormatted(name);
metadata.put(name, value);
}
}
}
item.setMetadata(metadata);
}
else
{
item.setMetadata(new Hashtable());
}
// for collections only
if(item.isFolder())
{
// setup for quota - ADMIN only, site-root collection only
if (SecurityService.isSuperUser())
{
Reference ref = EntityManager.newReference(entity.getReference());
String context = ref.getContext();
String siteCollectionId = ContentHostingService.getSiteCollection(context);
if(siteCollectionId.equals(entity.getId()))
{
item.setCanSetQuota(true);
try
{
long quota = properties.getLongProperty(ResourceProperties.PROP_COLLECTION_BODY_QUOTA);
item.setHasQuota(true);
item.setQuota(Long.toString(quota));
}
catch (Exception any)
{
}
}
}
}
}
catch (IdUnusedException e)
{
addAlert(state, RESOURCE_NOT_EXIST_STRING);
}
catch (PermissionException e)
{
addAlert(state, rb.getString("notpermis2") + " " + id + ". " );
}
catch(TypeException e)
{
addAlert(state," " + rb.getString("typeex") + " " + id);
}
catch(ServerOverloadException e)
{
// this represents temporary unavailability of server's filesystem
// for server configured to save resource body in filesystem
addAlert(state, rb.getString("failed"));
}
catch(RuntimeException e)
{
logger.error("ResourcesAction.doEdit ***** Unknown Exception ***** " + e.getMessage());
addAlert(state, rb.getString("failed"));
}
return item;
}
/**
* This method updates the session state with information needed to create or modify
* structured artifacts in the resources tool. Among other things, it obtains a list
* of "forms" available to the user and places that list in state indexed as
* "STATE_STRUCTOBJ_HOMES". If the current formtype is known (in state indexed as
* "STATE_STACK_STRUCTOBJ_TYPE"), the list of properties associated with that form type is
* generated. If we are in a "create" context, the properties are added to each of
* the items in the list of items indexed as "STATE_STACK_CREATE_ITEMS". If we are in an
* "edit" context, the properties are added to the current item being edited (a state
* attribute indexed as "STATE_STACK_EDIT_ITEM"). The metaobj SchemaBean associated with
* the current form and its root SchemaNode object are also placed in state for later
* reference.
*/
public static void setupStructuredObjects(SessionState state)
{
Map current_stack_frame = peekAtStack(state);
String formtype = (String) current_stack_frame.get(STATE_STACK_STRUCTOBJ_TYPE);
if(formtype == null)
{
formtype = (String) state.getAttribute(STATE_STRUCTOBJ_TYPE);
if(formtype == null)
{
formtype = "";
}
current_stack_frame.put(STATE_STACK_STRUCTOBJ_TYPE, formtype);
}
HomeFactory factory = (HomeFactory) ComponentManager.get("homeFactory");
Map homes = factory.getHomes(StructuredArtifactHomeInterface.class);
List listOfHomes = new Vector();
Iterator it = homes.keySet().iterator();
while(it.hasNext())
{
String key = (String) it.next();
try
{
Object obj = homes.get(key);
listOfHomes.add(obj);
}
catch(Exception ignore)
{}
}
current_stack_frame.put(STATE_STRUCTOBJ_HOMES, listOfHomes);
StructuredArtifactHomeInterface home = null;
SchemaBean rootSchema = null;
ResourcesMetadata elements = null;
if(formtype == null || formtype.equals(""))
{
formtype = "";
current_stack_frame.put(STATE_STACK_STRUCTOBJ_TYPE, formtype);
}
else if(listOfHomes.isEmpty())
{
// hmmm
}
else
{
try
{
home = (StructuredArtifactHomeInterface) factory.getHome(formtype);
}
catch(NullPointerException ignore)
{
home = null;
}
}
if(home != null)
{
rootSchema = new SchemaBean(home.getRootNode(), home.getSchema(), formtype, home.getType().getDescription());
List fields = rootSchema.getFields();
String docRoot = rootSchema.getFieldName();
elements = new ResourcesMetadata("", docRoot, "", "", ResourcesMetadata.WIDGET_NESTED, ResourcesMetadata.WIDGET_NESTED);
elements.setDottedparts(docRoot);
elements.setContainer(null);
elements = createHierarchicalList(elements, fields, 1);
String instruction = home.getInstruction();
current_stack_frame.put(STATE_STACK_STRUCTOBJ_ROOTNAME, docRoot);
current_stack_frame.put(STATE_STACK_STRUCT_OBJ_SCHEMA, rootSchema);
List new_items = (List) current_stack_frame.get(STATE_STACK_CREATE_ITEMS);
if(new_items != null)
{
Integer number = (Integer) current_stack_frame.get(STATE_STACK_CREATE_NUMBER);
if(number == null)
{
number = (Integer) state.getAttribute(STATE_CREATE_NUMBER);
current_stack_frame.put(STATE_STACK_CREATE_NUMBER, number);
}
if(number == null)
{
number = new Integer(1);
current_stack_frame.put(STATE_STACK_CREATE_NUMBER, number);
}
List flatList = elements.getFlatList();
for(int i = 0; i < number.intValue(); i++)
{
//%%%%% doing this wipes out data that's been stored previously
EditItem item = (EditItem) new_items.get(i);
item.setRootname(docRoot);
item.setFormtype(formtype);
item.setInstruction(instruction);
item.setProperties(flatList);
item.setForm(elements);
}
current_stack_frame.put(STATE_STACK_CREATE_ITEMS, new_items);
}
else if(current_stack_frame.get(STATE_STACK_EDIT_ITEM) != null)
{
EditItem item = (EditItem) current_stack_frame.get(STATE_STACK_EDIT_ITEM);
item.setRootname(docRoot);
item.setFormtype(formtype);
item.setInstruction(instruction);
item.setForm(elements);
}
}
} // setupStructuredArtifacts
/**
* This method navigates through a list of SchemaNode objects representing fields in a form,
* creates a ResourcesMetadata object for each field and adds those as nested fields within
* a root element. If a field contains nested fields, a recursive call adds nested fields
* in the corresponding ResourcesMetadata object.
* @param element The root element to which field descriptions are added.
* @param fields A list of metaobj SchemaNode objects.
* @param depth The depth of nesting, corresponding to the amount of indent that will be used
* when displaying the list.
* @return The update root element.
*/
private static ResourcesMetadata createHierarchicalList(ResourcesMetadata element, List fields, int depth)
{
List properties = new Vector();
for(Iterator fieldIt = fields.iterator(); fieldIt.hasNext(); )
{
SchemaBean field = (SchemaBean) fieldIt.next();
SchemaNode node = field.getSchema();
Map annotations = field.getAnnotations();
Pattern pattern = null;
String localname = field.getFieldName();
String description = field.getDescription();
String label = (String) annotations.get("label");
if(label == null || label.trim().equals(""))
{
label = description;
}
String richText = (String) annotations.get("isRichText");
boolean isRichText = richText != null && richText.equalsIgnoreCase(Boolean.TRUE.toString());
Class javaclass = node.getObjectType();
String typename = javaclass.getName();
String widget = ResourcesMetadata.WIDGET_STRING;
int length = 0;
List enumerals = null;
if(field.getFields().size() > 0)
{
widget = ResourcesMetadata.WIDGET_NESTED;
}
else if(node.hasEnumerations())
{
enumerals = node.getEnumeration();
typename = String.class.getName();
widget = ResourcesMetadata.WIDGET_ENUM;
}
else if(typename.equals(String.class.getName()))
{
length = node.getType().getMaxLength();
String baseType = node.getType().getBaseType();
if(isRichText)
{
widget = ResourcesMetadata.WIDGET_WYSIWYG;
}
else if(baseType.trim().equalsIgnoreCase(ResourcesMetadata.NAMESPACE_XSD_ABBREV + ResourcesMetadata.XSD_NORMALIZED_STRING))
{
widget = ResourcesMetadata.WIDGET_STRING;
if(length > 50)
{
length = 50;
}
}
else if(length > 100 || length < 1)
{
widget = ResourcesMetadata.WIDGET_TEXTAREA;
}
else if(length > 50)
{
length = 50;
}
pattern = node.getType().getPattern();
}
else if(typename.equals(Date.class.getName()))
{
widget = ResourcesMetadata.WIDGET_DATE;
}
else if(typename.equals(Boolean.class.getName()))
{
widget = ResourcesMetadata.WIDGET_BOOLEAN;
}
else if(typename.equals(URI.class.getName()))
{
widget = ResourcesMetadata.WIDGET_ANYURI;
}
else if(typename.equals(Number.class.getName()))
{
widget = ResourcesMetadata.WIDGET_INTEGER;
//length = node.getType().getTotalDigits();
length = INTEGER_WIDGET_LENGTH;
}
else if(typename.equals(Double.class.getName()))
{
widget = ResourcesMetadata.WIDGET_DOUBLE;
length = DOUBLE_WIDGET_LENGTH;
}
int minCard = node.getMinOccurs();
int maxCard = node.getMaxOccurs();
if(maxCard < 1)
{
maxCard = Integer.MAX_VALUE;
}
if(minCard < 0)
{
minCard = 0;
}
minCard = java.lang.Math.max(0,minCard);
maxCard = java.lang.Math.max(1,maxCard);
int currentCount = java.lang.Math.min(java.lang.Math.max(1,minCard),maxCard);
ResourcesMetadata prop = new ResourcesMetadata(element.getDottedname(), localname, label, description, typename, widget);
List parts = new Vector(element.getDottedparts());
parts.add(localname);
prop.setDottedparts(parts);
prop.setContainer(element);
if(ResourcesMetadata.WIDGET_NESTED.equals(widget))
{
prop = createHierarchicalList(prop, field.getFields(), depth + 1);
}
prop.setMinCardinality(minCard);
prop.setMaxCardinality(maxCard);
prop.setCurrentCount(currentCount);
prop.setDepth(depth);
if(enumerals != null)
{
prop.setEnumeration(enumerals);
}
if(length > 0)
{
prop.setLength(length);
}
if(pattern != null)
{
prop.setPattern(pattern);
}
properties.add(prop);
}
element.setNested(properties);
return element;
} // createHierarchicalList
/**
* This method captures property values from an org.w3c.dom.Document and inserts them
* into a hierarchical list of ResourcesMetadata objects which describes the structure
* of the form. The values are added by inserting nested instances into the properties.
*
* @param element An org.w3c.dom.Element containing values to be imported.
* @param properties A hierarchical list of ResourcesMetadata objects describing a form
*/
public static void importStructuredArtifact(Node node, ResourcesMetadata property)
{
if(property == null || node == null)
{
return;
}
String tagname = property.getLocalname();
String nodename = node.getLocalName();
if(! tagname.equals(nodename))
{
// return;
}
if(property.getNested().size() == 0)
{
boolean value_found = false;
Node child = node.getFirstChild();
while(! value_found && child != null)
{
if(child.getNodeType() == Node.TEXT_NODE)
{
Text value = (Text) child;
if(ResourcesMetadata.WIDGET_DATE.equals(property.getWidget()) || ResourcesMetadata.WIDGET_DATETIME.equals(property.getWidget()) || ResourcesMetadata.WIDGET_TIME.equals(property.getWidget()))
{
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
Time time = TimeService.newTime();
try
{
Date date = df.parse(value.getData());
time = TimeService.newTime(date.getTime());
}
catch(Exception ignore)
{
// use "now" as default in that case
}
property.setValue(0, time);
}
else if(ResourcesMetadata.WIDGET_ANYURI.equals(property.getWidget()))
{
Reference ref = EntityManager.newReference(ContentHostingService.getReference(value.getData()));
property.setValue(0, ref);
}
else
{
property.setValue(0, value.getData());
}
}
child = child.getNextSibling();
}
}
else if(node instanceof Element)
{
// a nested element
Iterator nestedIt = property.getNested().iterator();
while(nestedIt.hasNext())
{
ResourcesMetadata prop = (ResourcesMetadata) nestedIt.next();
NodeList nodes = ((Element) node).getElementsByTagName(prop.getLocalname());
if(nodes == null)
{
continue;
}
for(int i = 0; i < nodes.getLength(); i++)
{
Node n = nodes.item(i);
if(n != null)
{
ResourcesMetadata instance = prop.addInstance();
if(instance != null)
{
importStructuredArtifact(n, instance);
}
}
}
}
}
} // importStructuredArtifact
protected static String validateURL(String url) throws MalformedURLException
{
if (url.equals (NULL_STRING))
{
// ignore the empty url field
}
else if (url.indexOf ("://") == -1)
{
// if it's missing the transport, add http://
url = "http://" + url;
}
if(!url.equals(NULL_STRING))
{
// valid protocol?
try
{
// test to see if the input validates as a URL.
// Checks string for format only.
URL u = new URL(url);
}
catch (MalformedURLException e1)
{
try
{
Pattern pattern = Pattern.compile("\\s*([a-zA-Z0-9]+)://([^\\n]+)");
Matcher matcher = pattern.matcher(url);
if(matcher.matches())
{
// if URL has "unknown" protocol, check remaider with
// "http" protocol and accept input it that validates.
URL test = new URL("http://" + matcher.group(2));
}
else
{
throw e1;
}
}
catch (MalformedURLException e2)
{
throw e1;
}
}
}
return url;
}
/**
* Retrieve values for an item from edit context. Edit context contains just one item at a time of a known type
* (folder, file, text document, structured-artifact, etc). This method retrieves the data apppropriate to the
* type and updates the values of the EditItem stored as the STATE_STACK_EDIT_ITEM attribute in state.
* @param state
* @param params
* @param item
*/
protected static void captureValues(SessionState state, ParameterParser params)
{
Map current_stack_frame = peekAtStack(state);
EditItem item = (EditItem) current_stack_frame.get(STATE_STACK_EDIT_ITEM);
Set alerts = (Set) state.getAttribute(STATE_EDIT_ALERTS);
if(alerts == null)
{
alerts = new HashSet();
state.setAttribute(STATE_EDIT_ALERTS, alerts);
}
String flow = params.getString("flow");
boolean intentChanged = "intentChanged".equals(flow);
String check_fileName = params.getString("check_fileName");
boolean expectFile = "true".equals(check_fileName);
String intent = params.getString("intent");
String oldintent = (String) current_stack_frame.get(STATE_STACK_EDIT_INTENT);
boolean upload_file = expectFile && item.isFileUpload() || ((item.isHtml() || item.isPlaintext()) && !intentChanged && INTENT_REPLACE_FILE.equals(intent) && INTENT_REPLACE_FILE.equals(oldintent));
boolean revise_file = (item.isHtml() || item.isPlaintext()) && !intentChanged && INTENT_REVISE_FILE.equals(intent) && INTENT_REVISE_FILE.equals(oldintent);
String name = params.getString("name");
if(name == null || "".equals(name.trim()))
{
alerts.add(rb.getString("titlenotnull"));
// addAlert(state, rb.getString("titlenotnull"));
}
else
{
item.setName(name.trim());
}
String description = params.getString("description");
if(description == null)
{
item.setDescription("");
}
else
{
item.setDescription(description);
}
item.setContentHasChanged(false);
if(upload_file)
{
String max_file_size_mb = (String) state.getAttribute(STATE_FILE_UPLOAD_MAX_SIZE);
int max_bytes = 1096 * 1096;
try
{
max_bytes = Integer.parseInt(max_file_size_mb) * 1096 * 1096;
}
catch(Exception e)
{
// if unable to parse an integer from the value
// in the properties file, use 1 MB as a default
max_file_size_mb = "1";
max_bytes = 1096 * 1096;
}
/*
// params.getContentLength() returns m_req.getContentLength()
if(params.getContentLength() >= max_bytes)
{
alerts.add(rb.getString("size") + " " + max_file_size_mb + "MB " + rb.getString("exceeded2"));
}
else
*/
{
// check for file replacement
FileItem fileitem = params.getFileItem("fileName");
if(fileitem == null)
{
// "The user submitted a file to upload but it was too big!"
alerts.clear();
alerts.add(rb.getString("size") + " " + max_file_size_mb + "MB " + rb.getString("exceeded2"));
//item.setMissing("fileName");
}
else if (fileitem.getFileName() == null || fileitem.getFileName().length() == 0)
{
if(item.getContent() == null || item.getContent().length <= 0)
{
// "The user submitted the form, but didn't select a file to upload!"
alerts.add(rb.getString("choosefile") + ". ");
//item.setMissing("fileName");
}
}
else if (fileitem.getFileName().length() > 0)
{
String filename = Validator.getFileName(fileitem.getFileName());
byte[] bytes = fileitem.get();
String contenttype = fileitem.getContentType();
if(bytes.length >= max_bytes)
{
alerts.clear();
alerts.add(rb.getString("size") + " " + max_file_size_mb + "MB " + rb.getString("exceeded2"));
// item.setMissing("fileName");
}
else if(bytes.length > 0)
{
item.setContent(bytes);
item.setContentHasChanged(true);
item.setMimeType(contenttype);
item.setFilename(filename);
}
}
}
}
else if(revise_file)
{
// check for input from editor (textarea)
String content = params.getString("content");
if(content != null)
{
item.setContent(content);
item.setContentHasChanged(true);
}
}
else if(item.isUrl())
{
String url = params.getString("Url");
if(url == null || url.trim().equals(""))
{
item.setFilename("");
alerts.add(rb.getString("validurl"));
}
else
{
// valid protocol?
item.setFilename(url);
try
{
// test format of input
URL u = new URL(url);
}
catch (MalformedURLException e1)
{
try
{
// if URL did not validate, check whether the problem was an
// unrecognized protocol, and accept input if that's the case.
Pattern pattern = Pattern.compile("\\s*([a-zA-Z0-9]+)://([^\\n]+)");
Matcher matcher = pattern.matcher(url);
if(matcher.matches())
{
URL test = new URL("http://" + matcher.group(2));
}
else
{
url = "http://" + url;
URL test = new URL(url);
item.setFilename(url);
}
}
catch (MalformedURLException e2)
{
// invalid url
alerts.add(rb.getString("validurl"));
}
}
}
}
else if(item.isFolder())
{
if(item.canSetQuota())
{
// read the quota fields
String setQuota = params.getString("setQuota");
boolean hasQuota = params.getBoolean("hasQuota");
item.setHasQuota(hasQuota);
if(hasQuota)
{
int q = params.getInt("quota");
item.setQuota(Integer.toString(q));
}
}
}
else if(item.isStructuredArtifact())
{
String formtype = (String) current_stack_frame.get(STATE_STACK_STRUCTOBJ_TYPE);
if(formtype == null)
{
formtype = (String) state.getAttribute(STATE_STRUCTOBJ_TYPE);
if(formtype == null)
{
formtype = "";
}
current_stack_frame.put(STATE_STACK_STRUCTOBJ_TYPE, formtype);
}
String formtype_check = params.getString("formtype");
if(formtype_check == null || formtype_check.equals(""))
{
alerts.add(rb.getString("type"));
item.setMissing("formtype");
}
else if(formtype_check.equals(formtype))
{
item.setFormtype(formtype);
capturePropertyValues(params, item, item.getProperties());
}
}
if(! item.isFolder() && ! item.isStructuredArtifact() && ! item.isUrl())
{
String mime_category = params.getString("mime_category");
String mime_subtype = params.getString("mime_subtype");
if(mime_category != null && mime_subtype != null)
{
String mimetype = mime_category + "/" + mime_subtype;
if(! mimetype.equals(item.getMimeType()))
{
item.setMimeType(mimetype);
item.setContentTypeHasChanged(true);
}
}
}
if(item.isFileUpload() || item.isHtml() || item.isPlaintext())
{
BasicRightsAssignment rightsObj = item.getRights();
rightsObj.captureValues(params);
boolean usingCreativeCommons = state.getAttribute(STATE_USING_CREATIVE_COMMONS) != null && state.getAttribute(STATE_USING_CREATIVE_COMMONS).equals(Boolean.TRUE.toString());
if(usingCreativeCommons)
{
String ccOwnership = params.getString("ccOwnership");
if(ccOwnership != null)
{
item.setRightsownership(ccOwnership);
}
String ccTerms = params.getString("ccTerms");
if(ccTerms != null)
{
item.setLicense(ccTerms);
}
String ccCommercial = params.getString("ccCommercial");
if(ccCommercial != null)
{
item.setAllowCommercial(ccCommercial);
}
String ccModification = params.getString("ccModification");
if(ccCommercial != null)
{
item.setAllowModifications(ccModification);
}
String ccRightsYear = params.getString("ccRightsYear");
if(ccRightsYear != null)
{
item.setRightstyear(ccRightsYear);
}
String ccRightsOwner = params.getString("ccRightsOwner");
if(ccRightsOwner != null)
{
item.setRightsowner(ccRightsOwner);
}
/*
ccValues.ccOwner = new Array();
ccValues.myRights = new Array();
ccValues.otherRights = new Array();
ccValues.ccCommercial = new Array();
ccValues.ccModifications = new Array();
ccValues.ccRightsYear = new Array();
ccValues.ccRightsOwner = new Array();
*/
}
else
{
// check for copyright status
// check for copyright info
// check for copyright alert
String copyrightStatus = StringUtil.trimToNull(params.getString ("copyrightStatus"));
String copyrightInfo = StringUtil.trimToNull(params.getCleanString ("copyrightInfo"));
String copyrightAlert = StringUtil.trimToNull(params.getString("copyrightAlert"));
if (copyrightStatus != null)
{
if (state.getAttribute(COPYRIGHT_NEW_COPYRIGHT) != null && copyrightStatus.equals(state.getAttribute(COPYRIGHT_NEW_COPYRIGHT)))
{
if (copyrightInfo != null)
{
item.setCopyrightInfo( copyrightInfo );
}
else
{
alerts.add(rb.getString("specifycp2"));
// addAlert(state, rb.getString("specifycp2"));
}
}
else if (state.getAttribute(COPYRIGHT_SELF_COPYRIGHT) != null && copyrightStatus.equals (state.getAttribute(COPYRIGHT_SELF_COPYRIGHT)))
{
item.setCopyrightInfo((String) state.getAttribute (STATE_MY_COPYRIGHT));
}
item.setCopyrightStatus( copyrightStatus );
}
item.setCopyrightAlert(copyrightAlert != null);
}
}
String access_mode = params.getString("access_mode");
if(access_mode != null)
{
item.setAccess(access_mode);
if(AccessMode.GROUPED.toString().equals(access_mode))
{
String xxx = params.getString("access_groups");
String[] access_groups = params.getStrings("access_groups");
item.clearGroups();
for(int gr = 0; gr < access_groups.length; gr++)
{
item.addGroup(access_groups[gr]);
}
}
}
Boolean preventPublicDisplay = (Boolean) state.getAttribute(STATE_PREVENT_PUBLIC_DISPLAY);
if(preventPublicDisplay == null)
{
preventPublicDisplay = Boolean.FALSE;
state.setAttribute(STATE_PREVENT_PUBLIC_DISPLAY, preventPublicDisplay);
}
if(preventPublicDisplay.equals(Boolean.FALSE))
{
boolean pubviewset = item.isPubviewset();
boolean pubview = false;
if (! RESOURCES_MODE_DROPBOX.equalsIgnoreCase((String) state.getAttribute(STATE_MODE_RESOURCES)))
{
if (!pubviewset)
{
pubview = params.getBoolean("pubview");
item.setPubview(pubview);
}
}
}
int noti = NotificationService.NOTI_NONE;
// %%STATE_MODE_RESOURCES%%
if (RESOURCES_MODE_DROPBOX.equalsIgnoreCase((String) state.getAttribute(STATE_MODE_RESOURCES)))
{
// set noti to none if in dropbox mode
noti = NotificationService.NOTI_NONE;
}
else
{
// read the notification options
String notification = params.getString("notify");
if ("r".equals(notification))
{
noti = NotificationService.NOTI_REQUIRED;
}
else if ("o".equals(notification))
{
noti = NotificationService.NOTI_OPTIONAL;
}
}
item.setNotification(noti);
List metadataGroups = (List) state.getAttribute(STATE_METADATA_GROUPS);
if(metadataGroups != null && ! metadataGroups.isEmpty())
{
Iterator groupIt = metadataGroups.iterator();
while(groupIt.hasNext())
{
MetadataGroup group = (MetadataGroup) groupIt.next();
if(group.isShowing())
{
Iterator propIt = group.iterator();
while(propIt.hasNext())
{
ResourcesMetadata prop = (ResourcesMetadata) propIt.next();
String propname = prop.getFullname();
if(ResourcesMetadata.WIDGET_DATE.equals(prop.getWidget()) || ResourcesMetadata.WIDGET_DATETIME.equals(prop.getWidget()) || ResourcesMetadata.WIDGET_TIME.equals(prop.getWidget()))
{
int year = 0;
int month = 0;
int day = 0;
int hour = 0;
int minute = 0;
int second = 0;
int millisecond = 0;
String ampm = "";
if(prop.getWidget().equals(ResourcesMetadata.WIDGET_DATE) ||
prop.getWidget().equals(ResourcesMetadata.WIDGET_DATETIME))
{
year = params.getInt(propname + "_year", year);
month = params.getInt(propname + "_month", month);
day = params.getInt(propname + "_day", day);
}
if(prop.getWidget().equals(ResourcesMetadata.WIDGET_TIME) ||
prop.getWidget().equals(ResourcesMetadata.WIDGET_DATETIME))
{
hour = params.getInt(propname + "_hour", hour);
minute = params.getInt(propname + "_minute", minute);
second = params.getInt(propname + "_second", second);
millisecond = params.getInt(propname + "_millisecond", millisecond);
ampm = params.getString(propname + "_ampm").trim();
if("pm".equalsIgnoreCase("ampm"))
{
if(hour < 12)
{
hour += 12;
}
}
else if(hour == 12)
{
hour = 0;
}
}
if(hour > 23)
{
hour = hour % 24;
day++;
}
Time value = TimeService.newTimeLocal(year, month, day, hour, minute, second, millisecond);
item.setMetadataItem(propname,value);
}
else
{
String value = params.getString(propname);
if(value != null)
{
item.setMetadataItem(propname, value);
}
}
}
}
}
}
current_stack_frame.put(STATE_STACK_EDIT_ITEM, item);
state.setAttribute(STATE_EDIT_ALERTS, alerts);
} // captureValues
/**
* Retrieve from an html form all the values needed to create a new resource
* @param item The EditItem object in which the values are temporarily stored.
* @param index The index of the item (used as a suffix in the name of the form element)
* @param state
* @param params
* @param markMissing Indicates whether to mark required elements if they are missing.
* @return
*/
public static Set captureValues(EditItem item, int index, SessionState state, ParameterParser params, boolean markMissing)
{
Map current_stack_frame = peekAtStack(state);
Set item_alerts = new HashSet();
boolean blank_entry = true;
item.clearMissing();
String name = params.getString("name" + index);
if(name == null || name.trim().equals(""))
{
if(markMissing)
{
item_alerts.add(rb.getString("titlenotnull"));
item.setMissing("name");
}
item.setName("");
// addAlert(state, rb.getString("titlenotnull"));
}
else
{
item.setName(name);
blank_entry = false;
}
String description = params.getString("description" + index);
if(description == null || description.trim().equals(""))
{
item.setDescription("");
}
else
{
item.setDescription(description);
blank_entry = false;
}
item.setContentHasChanged(false);
if(item.isFileUpload())
{
String max_file_size_mb = (String) state.getAttribute(STATE_FILE_UPLOAD_MAX_SIZE);
int max_bytes = 1096 * 1096;
try
{
max_bytes = Integer.parseInt(max_file_size_mb) * 1096 * 1096;
}
catch(Exception e)
{
// if unable to parse an integer from the value
// in the properties file, use 1 MB as a default
max_file_size_mb = "1";
max_bytes = 1096 * 1096;
}
/*
// params.getContentLength() returns m_req.getContentLength()
if(params.getContentLength() >= max_bytes)
{
item_alerts.add(rb.getString("size") + " " + max_file_size_mb + "MB " + rb.getString("exceeded2"));
}
else
*/
{
// check for file replacement
FileItem fileitem = null;
try
{
fileitem = params.getFileItem("fileName" + index);
}
catch(Exception e)
{
// this is an error in Firefox, Mozilla and Netscape
// "The user didn't select a file to upload!"
if(item.getContent() == null || item.getContent().length <= 0)
{
item_alerts.add(rb.getString("choosefile") + " " + (index + 1) + ". ");
item.setMissing("fileName");
}
}
if(fileitem == null)
{
// "The user submitted a file to upload but it was too big!"
item_alerts.clear();
item_alerts.add(rb.getString("size") + " " + max_file_size_mb + "MB " + rb.getString("exceeded2"));
item.setMissing("fileName");
}
else if (fileitem.getFileName() == null || fileitem.getFileName().length() == 0)
{
if(item.getContent() == null || item.getContent().length <= 0)
{
// "The user submitted the form, but didn't select a file to upload!"
item_alerts.add(rb.getString("choosefile") + " " + (index + 1) + ". ");
item.setMissing("fileName");
}
}
else if (fileitem.getFileName().length() > 0)
{
String filename = Validator.getFileName(fileitem.getFileName());
byte[] bytes = fileitem.get();
String contenttype = fileitem.getContentType();
if(bytes.length >= max_bytes)
{
item_alerts.clear();
item_alerts.add(rb.getString("size") + " " + max_file_size_mb + "MB " + rb.getString("exceeded2"));
item.setMissing("fileName");
}
else if(bytes.length > 0)
{
item.setContent(bytes);
item.setContentHasChanged(true);
item.setMimeType(contenttype);
item.setFilename(filename);
blank_entry = false;
}
else
{
item_alerts.add(rb.getString("choosefile") + " " + (index + 1) + ". ");
item.setMissing("fileName");
}
}
}
}
else if(item.isPlaintext())
{
// check for input from editor (textarea)
String content = params.getString("content" + index);
if(content != null)
{
item.setContentHasChanged(true);
item.setContent(content);
blank_entry = false;
}
item.setMimeType(MIME_TYPE_DOCUMENT_PLAINTEXT);
}
else if(item.isHtml())
{
// check for input from editor (textarea)
String content = params.getCleanString("content" + index);
StringBuffer alertMsg = new StringBuffer();
content = FormattedText.processHtmlDocument(content, alertMsg);
if (alertMsg.length() > 0)
{
item_alerts.add(alertMsg.toString());
}
if(content != null && !content.equals(""))
{
item.setContent(content);
item.setContentHasChanged(true);
blank_entry = false;
}
item.setMimeType(MIME_TYPE_DOCUMENT_HTML);
}
else if(item.isUrl())
{
item.setMimeType(ResourceProperties.TYPE_URL);
String url = params.getString("Url" + index);
if(url == null || url.trim().equals(""))
{
item.setFilename("");
item_alerts.add(rb.getString("specifyurl"));
item.setMissing("Url");
}
else
{
item.setFilename(url);
blank_entry = false;
// is protocol supplied and, if so, is it recognized?
try
{
// check format of input
URL u = new URL(url);
}
catch (MalformedURLException e1)
{
try
{
// if URL did not validate, check whether the problem was an
// unrecognized protocol, and accept input if that's the case.
Pattern pattern = Pattern.compile("\\s*([a-zA-Z0-9]+)://([^\\n]+)");
Matcher matcher = pattern.matcher(url);
if(matcher.matches())
{
URL test = new URL("http://" + matcher.group(2));
}
else
{
url = "http://" + url;
URL test = new URL(url);
item.setFilename(url);
}
}
catch (MalformedURLException e2)
{
// invalid url
item_alerts.add(rb.getString("validurl"));
item.setMissing("Url");
}
}
}
}
else if(item.isStructuredArtifact())
{
String formtype = (String) current_stack_frame.get(STATE_STACK_STRUCTOBJ_TYPE);
if(formtype == null)
{
formtype = (String) state.getAttribute(STATE_STRUCTOBJ_TYPE);
if(formtype == null)
{
formtype = "";
}
current_stack_frame.put(STATE_STACK_STRUCTOBJ_TYPE, formtype);
}
String formtype_check = params.getString("formtype");
if(formtype_check == null || formtype_check.equals(""))
{
item_alerts.add("Must select a form type");
item.setMissing("formtype");
}
else if(formtype_check.equals(formtype))
{
item.setFormtype(formtype);
capturePropertyValues(params, item, item.getProperties());
// blank_entry = false;
}
item.setMimeType(MIME_TYPE_STRUCTOBJ);
}
if(item.isFileUpload() || item.isHtml() || item.isPlaintext())
{
BasicRightsAssignment rightsObj = item.getRights();
rightsObj.captureValues(params);
boolean usingCreativeCommons = state.getAttribute(STATE_USING_CREATIVE_COMMONS) != null && state.getAttribute(STATE_USING_CREATIVE_COMMONS).equals(Boolean.TRUE.toString());
if(usingCreativeCommons)
{
String ccOwnership = params.getString("ccOwnership" + index);
if(ccOwnership != null)
{
item.setRightsownership(ccOwnership);
}
String ccTerms = params.getString("ccTerms" + index);
if(ccTerms != null)
{
item.setLicense(ccTerms);
}
String ccCommercial = params.getString("ccCommercial" + index);
if(ccCommercial != null)
{
item.setAllowCommercial(ccCommercial);
}
String ccModification = params.getString("ccModification" + index);
if(ccCommercial != null)
{
item.setAllowModifications(ccModification);
}
String ccRightsYear = params.getString("ccRightsYear" + index);
if(ccRightsYear != null)
{
item.setRightstyear(ccRightsYear);
}
String ccRightsOwner = params.getString("ccRightsOwner" + index);
if(ccRightsOwner != null)
{
item.setRightsowner(ccRightsOwner);
}
/*
ccValues.ccOwner = new Array();
ccValues.myRights = new Array();
ccValues.otherRights = new Array();
ccValues.ccCommercial = new Array();
ccValues.ccModifications = new Array();
ccValues.ccRightsYear = new Array();
ccValues.ccRightsOwner = new Array();
*/
}
else
{
// check for copyright status
// check for copyright info
// check for copyright alert
String copyrightStatus = StringUtil.trimToNull(params.getString ("copyright" + index));
String copyrightInfo = StringUtil.trimToNull(params.getCleanString ("newcopyright" + index));
String copyrightAlert = StringUtil.trimToNull(params.getString("copyrightAlert" + index));
if (copyrightStatus != null)
{
if (state.getAttribute(COPYRIGHT_NEW_COPYRIGHT) != null && copyrightStatus.equals(state.getAttribute(COPYRIGHT_NEW_COPYRIGHT)))
{
if (copyrightInfo != null)
{
item.setCopyrightInfo( copyrightInfo );
}
else
{
item_alerts.add(rb.getString("specifycp2"));
// addAlert(state, rb.getString("specifycp2"));
}
}
else if (state.getAttribute(COPYRIGHT_SELF_COPYRIGHT) != null && copyrightStatus.equals (state.getAttribute(COPYRIGHT_SELF_COPYRIGHT)))
{
item.setCopyrightInfo((String) state.getAttribute (STATE_MY_COPYRIGHT));
}
item.setCopyrightStatus( copyrightStatus );
}
item.setCopyrightAlert(copyrightAlert != null);
}
}
Boolean preventPublicDisplay = (Boolean) state.getAttribute(STATE_PREVENT_PUBLIC_DISPLAY);
if(preventPublicDisplay == null)
{
preventPublicDisplay = Boolean.FALSE;
state.setAttribute(STATE_PREVENT_PUBLIC_DISPLAY, preventPublicDisplay);
}
if(preventPublicDisplay.equals(Boolean.FALSE))
{
boolean pubviewset = item.isPubviewset();
boolean pubview = false;
if (! RESOURCES_MODE_DROPBOX.equalsIgnoreCase((String) state.getAttribute(STATE_MODE_RESOURCES)))
{
if (!pubviewset)
{
pubview = params.getBoolean("pubview");
item.setPubview(pubview);
}
}
}
String access_mode = params.getString("access_mode" + index);
if(access_mode != null)
{
item.setAccess(access_mode);
if(AccessMode.GROUPED.toString().equals(access_mode))
{
String[] access_groups = params.getStrings("access_groups" + index);
for(int gr = 0; gr < access_groups.length; gr++)
{
item.addGroup(access_groups[gr]);
}
}
}
int noti = NotificationService.NOTI_NONE;
// %%STATE_MODE_RESOURCES%%
if (RESOURCES_MODE_DROPBOX.equalsIgnoreCase((String) state.getAttribute(STATE_MODE_RESOURCES)))
{
// set noti to none if in dropbox mode
noti = NotificationService.NOTI_NONE;
}
else
{
// read the notification options
String notification = params.getString("notify" + index);
if ("r".equals(notification))
{
noti = NotificationService.NOTI_REQUIRED;
}
else if ("o".equals(notification))
{
noti = NotificationService.NOTI_OPTIONAL;
}
}
item.setNotification(noti);
List metadataGroups = (List) state.getAttribute(STATE_METADATA_GROUPS);
if(metadataGroups != null && ! metadataGroups.isEmpty())
{
Iterator groupIt = metadataGroups.iterator();
while(groupIt.hasNext())
{
MetadataGroup group = (MetadataGroup) groupIt.next();
if(item.isGroupShowing(group.getName()))
{
Iterator propIt = group.iterator();
while(propIt.hasNext())
{
ResourcesMetadata prop = (ResourcesMetadata) propIt.next();
String propname = prop.getFullname();
if(ResourcesMetadata.WIDGET_DATE.equals(prop.getWidget()) || ResourcesMetadata.WIDGET_DATETIME.equals(prop.getWidget()) || ResourcesMetadata.WIDGET_TIME.equals(prop.getWidget()))
{
int year = 0;
int month = 0;
int day = 0;
int hour = 0;
int minute = 0;
int second = 0;
int millisecond = 0;
String ampm = "";
if(prop.getWidget().equals(ResourcesMetadata.WIDGET_DATE) ||
prop.getWidget().equals(ResourcesMetadata.WIDGET_DATETIME))
{
year = params.getInt(propname + "_" + index + "_year", year);
month = params.getInt(propname + "_" + index + "_month", month);
day = params.getInt(propname + "_" + index + "_day", day);
}
if(prop.getWidget().equals(ResourcesMetadata.WIDGET_TIME) ||
prop.getWidget().equals(ResourcesMetadata.WIDGET_DATETIME))
{
hour = params.getInt(propname + "_" + index + "_hour", hour);
minute = params.getInt(propname + "_" + index + "_minute", minute);
second = params.getInt(propname + "_" + index + "_second", second);
millisecond = params.getInt(propname + "_" + index + "_millisecond", millisecond);
ampm = params.getString(propname + "_" + index + "_ampm").trim();
if("pm".equalsIgnoreCase(ampm))
{
if(hour < 12)
{
hour += 12;
}
}
else if(hour == 12)
{
hour = 0;
}
}
if(hour > 23)
{
hour = hour % 24;
day++;
}
Time value = TimeService.newTimeLocal(year, month, day, hour, minute, second, millisecond);
item.setMetadataItem(propname,value);
}
else
{
String value = params.getString(propname + "_" + index);
if(value != null)
{
item.setMetadataItem(propname, value);
}
}
}
}
}
}
item.markAsBlank(blank_entry);
return item_alerts;
}
/**
* Retrieve values for one or more items from create context. Create context contains up to ten items at a time
* all of the same type (folder, file, text document, structured-artifact, etc). This method retrieves the data
* apppropriate to the type and updates the values of the EditItem objects stored as the STATE_STACK_CREATE_ITEMS
* attribute in state. If the third parameter is "true", missing/incorrect user inputs will generate error messages
* and attach flags to the input elements.
* @param state
* @param params
* @param markMissing Should this method generate error messages and add flags for missing/incorrect user inputs?
*/
protected static void captureMultipleValues(SessionState state, ParameterParser params, boolean markMissing)
{
Map current_stack_frame = peekAtStack(state);
Integer number = (Integer) current_stack_frame.get(STATE_STACK_CREATE_NUMBER);
if(number == null)
{
number = (Integer) state.getAttribute(STATE_CREATE_NUMBER);
current_stack_frame.put(STATE_STACK_CREATE_NUMBER, number);
}
if(number == null)
{
number = new Integer(1);
current_stack_frame.put(STATE_STACK_CREATE_NUMBER, number);
}
List new_items = (List) current_stack_frame.get(STATE_STACK_CREATE_ITEMS);
if(new_items == null)
{
String defaultCopyrightStatus = (String) state.getAttribute(DEFAULT_COPYRIGHT);
if(defaultCopyrightStatus == null || defaultCopyrightStatus.trim().equals(""))
{
defaultCopyrightStatus = ServerConfigurationService.getString("default.copyright");
state.setAttribute(DEFAULT_COPYRIGHT, defaultCopyrightStatus);
}
String itemType = (String) current_stack_frame.get(STATE_STACK_CREATE_TYPE);
if(itemType == null || itemType.trim().equals(""))
{
itemType = (String) state.getAttribute(STATE_CREATE_TYPE);
if(itemType == null || itemType.trim().equals(""))
{
itemType = TYPE_UPLOAD;
}
current_stack_frame.put(STATE_STACK_CREATE_TYPE, itemType);
}
new_items = new Vector();
for(int i = 0; i < CREATE_MAX_ITEMS; i++)
{
EditItem item = new EditItem(itemType);
item.setCopyrightStatus(defaultCopyrightStatus);
new_items.add(item);
}
current_stack_frame.put(STATE_STACK_CREATE_ITEMS, new_items);
}
Set alerts = (Set) state.getAttribute(STATE_CREATE_ALERTS);
if(alerts == null)
{
alerts = new HashSet();
state.setAttribute(STATE_CREATE_ALERTS, alerts);
}
int actualCount = 0;
Set first_item_alerts = null;
String max_file_size_mb = (String) state.getAttribute(STATE_FILE_UPLOAD_MAX_SIZE);
int max_bytes = 1096 * 1096;
try
{
max_bytes = Integer.parseInt(max_file_size_mb) * 1096 * 1096;
}
catch(Exception e)
{
// if unable to parse an integer from the value
// in the properties file, use 1 MB as a default
max_file_size_mb = "1";
max_bytes = 1096 * 1096;
}
/*
// params.getContentLength() returns m_req.getContentLength()
if(params.getContentLength() > max_bytes)
{
alerts.add(rb.getString("size") + " " + max_file_size_mb + "MB " + rb.getString("exceeded2"));
state.setAttribute(STATE_CREATE_ALERTS, alerts);
return;
}
*/
for(int i = 0; i < number.intValue(); i++)
{
EditItem item = (EditItem) new_items.get(i);
Set item_alerts = captureValues(item, i, state, params, markMissing);
if(i == 0)
{
first_item_alerts = item_alerts;
}
else if(item.isBlank())
{
item.clearMissing();
}
if(! item.isBlank())
{
alerts.addAll(item_alerts);
actualCount ++;
}
}
if(actualCount > 0)
{
EditItem item = (EditItem) new_items.get(0);
if(item.isBlank())
{
item.clearMissing();
}
}
else if(markMissing)
{
alerts.addAll(first_item_alerts);
}
state.setAttribute(STATE_CREATE_ALERTS, alerts);
current_stack_frame.put(STATE_STACK_CREATE_ACTUAL_COUNT, Integer.toString(actualCount));
} // captureMultipleValues
protected static void capturePropertyValues(ParameterParser params, EditItem item, List properties)
{
// use the item's properties if they're not supplied
if(properties == null)
{
properties = item.getProperties();
}
// if max cardinality > 1, value is a list (Iterate over members of list)
// else value is an object, not a list
// if type is nested, object is a Map (iterate over name-value pairs for the properties of the nested object)
// else object is type to store value, usually a string or a date/time
Iterator it = properties.iterator();
while(it.hasNext())
{
ResourcesMetadata prop = (ResourcesMetadata) it.next();
String propname = prop.getDottedname();
if(ResourcesMetadata.WIDGET_NESTED.equals(prop.getWidget()))
{
// do nothing
}
else if(ResourcesMetadata.WIDGET_BOOLEAN.equals(prop.getWidget()))
{
String value = params.getString(propname);
if(value == null || Boolean.FALSE.toString().equals(value))
{
prop.setValue(0, Boolean.FALSE.toString());
}
else
{
prop.setValue(0, Boolean.TRUE.toString());
}
}
else if(ResourcesMetadata.WIDGET_DATE.equals(prop.getWidget()) || ResourcesMetadata.WIDGET_DATETIME.equals(prop.getWidget()) || ResourcesMetadata.WIDGET_TIME.equals(prop.getWidget()))
{
int year = 0;
int month = 0;
int day = 0;
int hour = 0;
int minute = 0;
int second = 0;
int millisecond = 0;
String ampm = "";
if(prop.getWidget().equals(ResourcesMetadata.WIDGET_DATE) ||
prop.getWidget().equals(ResourcesMetadata.WIDGET_DATETIME))
{
year = params.getInt(propname + "_year", year);
month = params.getInt(propname + "_month", month);
day = params.getInt(propname + "_day", day);
}
if(prop.getWidget().equals(ResourcesMetadata.WIDGET_TIME) ||
prop.getWidget().equals(ResourcesMetadata.WIDGET_DATETIME))
{
hour = params.getInt(propname + "_hour", hour);
minute = params.getInt(propname + "_minute", minute);
second = params.getInt(propname + "_second", second);
millisecond = params.getInt(propname + "_millisecond", millisecond);
ampm = params.getString(propname + "_ampm");
if("pm".equalsIgnoreCase(ampm))
{
if(hour < 12)
{
hour += 12;
}
}
else if(hour == 12)
{
hour = 0;
}
}
if(hour > 23)
{
hour = hour % 24;
day++;
}
Time value = TimeService.newTimeLocal(year, month, day, hour, minute, second, millisecond);
prop.setValue(0, value);
}
else if(ResourcesMetadata.WIDGET_ANYURI.equals(prop.getWidget()))
{
String value = params.getString(propname);
if(value != null && ! value.trim().equals(""))
{
Reference ref = EntityManager.newReference(ContentHostingService.getReference(value));
prop.setValue(0, ref);
}
}
else
{
String value = params.getString(propname);
if(value != null)
{
prop.setValue(0, value);
}
}
}
} // capturePropertyValues
/**
* Modify the properties
*/
public static void doSavechanges ( RunData data)
{
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
ParameterParser params = data.getParameters ();
String flow = params.getString("flow").trim();
if(flow == null || "cancel".equals(flow))
{
doCancel(data);
return;
}
// get values from form and update STATE_STACK_EDIT_ITEM attribute in state
captureValues(state, params);
Map current_stack_frame = peekAtStack(state);
EditItem item = (EditItem) current_stack_frame.get(STATE_STACK_EDIT_ITEM);
if(flow.equals("showMetadata"))
{
doShow_metadata(data);
return;
}
else if(flow.equals("hideMetadata"))
{
doHide_metadata(data);
return;
}
else if(flow.equals("intentChanged"))
{
doToggle_intent(data);
return;
}
else if(flow.equals("addInstance"))
{
String field = params.getString("field");
addInstance(field, item.getProperties());
ResourcesMetadata form = item.getForm();
List flatList = form.getFlatList();
item.setProperties(flatList);
return;
}
else if(flow.equals("linkResource"))
{
// captureMultipleValues(state, params, false);
createLink(data, state);
//Map new_stack_frame = pushOnStack(state);
//new_stack_frame.put(ResourcesAction.STATE_RESOURCES_HELPER_MODE, ResourcesAction.MODE_ATTACHMENT_SELECT);
state.setAttribute(ResourcesAction.STATE_RESOURCES_HELPER_MODE, ResourcesAction.MODE_ATTACHMENT_SELECT);
return;
}
Set alerts = (Set) state.getAttribute(STATE_EDIT_ALERTS);
if(item.isStructuredArtifact())
{
SchemaBean bean = (SchemaBean) current_stack_frame.get(STATE_STACK_STRUCT_OBJ_SCHEMA);
SaveArtifactAttempt attempt = new SaveArtifactAttempt(item, bean.getSchema());
validateStructuredArtifact(attempt);
Iterator errorIt = attempt.getErrors().iterator();
while(errorIt.hasNext())
{
ValidationError error = (ValidationError) errorIt.next();
alerts.add(error.getDefaultMessage());
}
}
if(alerts.isEmpty())
{
// populate the property list
try
{
// get an edit
ContentCollectionEdit cedit = null;
ContentResourceEdit redit = null;
GroupAwareEdit gedit = null;
ResourcePropertiesEdit pedit = null;
if(item.isFolder())
{
cedit = ContentHostingService.editCollection(item.getId());
gedit = cedit;
pedit = cedit.getPropertiesEdit();
}
else
{
redit = ContentHostingService.editResource(item.getId());
gedit = redit;
pedit = redit.getPropertiesEdit();
}
try
{
if((AccessMode.INHERITED.toString().equals(item.getAccess()) || AccessMode.SITE.toString().equals(item.getAccess())) && AccessMode.GROUPED == gedit.getAccess())
{
gedit.clearGroupAccess();
}
else if(gedit.getAccess() == AccessMode.GROUPED && item.getGroups().isEmpty())
{
gedit.clearGroupAccess();
}
else if(!item.getGroups().isEmpty())
{
Collection groupRefs = new Vector();
Iterator it = item.getGroups().iterator();
while(it.hasNext())
{
Group group = (Group) it.next();
groupRefs.add(group.getReference());
}
gedit.setGroupAccess(groupRefs);
}
}
catch(InconsistentException e)
{
// TODO: Should this be reported to user??
logger.error("ResourcesAction.doSavechanges ***** InconsistentException changing groups ***** " + e.getMessage());
}
if(item.isFolder())
{
}
else
{
if(item.isUrl())
{
redit.setContent(item.getFilename().getBytes());
}
else if(item.isStructuredArtifact())
{
redit.setContentType(item.getMimeType());
redit.setContent(item.getContent());
}
else if(item.contentHasChanged())
{
redit.setContentType(item.getMimeType());
redit.setContent(item.getContent());
}
else if(item.contentTypeHasChanged())
{
redit.setContentType(item.getMimeType());
}
BasicRightsAssignment rightsObj = item.getRights();
rightsObj.addResourceProperties(pedit);
String copyright = StringUtil.trimToNull(params.getString ("copyright"));
String newcopyright = StringUtil.trimToNull(params.getCleanString (NEW_COPYRIGHT));
String copyrightAlert = StringUtil.trimToNull(params.getString("copyrightAlert"));
if (copyright != null)
{
if (state.getAttribute(COPYRIGHT_NEW_COPYRIGHT) != null && copyright.equals(state.getAttribute(COPYRIGHT_NEW_COPYRIGHT)))
{
if (newcopyright != null)
{
pedit.addProperty (ResourceProperties.PROP_COPYRIGHT, newcopyright);
}
else
{
alerts.add(rb.getString("specifycp2"));
// addAlert(state, rb.getString("specifycp2"));
}
}
else if (state.getAttribute(COPYRIGHT_SELF_COPYRIGHT) != null && copyright.equals (state.getAttribute(COPYRIGHT_SELF_COPYRIGHT)))
{
String mycopyright = (String) state.getAttribute (STATE_MY_COPYRIGHT);
pedit.addProperty (ResourceProperties.PROP_COPYRIGHT, mycopyright);
}
pedit.addProperty(ResourceProperties.PROP_COPYRIGHT_CHOICE, copyright);
}
if (copyrightAlert != null)
{
pedit.addProperty (ResourceProperties.PROP_COPYRIGHT_ALERT, copyrightAlert);
}
else
{
pedit.removeProperty (ResourceProperties.PROP_COPYRIGHT_ALERT);
}
}
if (!(item.isFolder() && (item.getId().equals ((String) state.getAttribute (STATE_HOME_COLLECTION_ID)))))
{
pedit.addProperty (ResourceProperties.PROP_DISPLAY_NAME, item.getName());
} // the home collection's title is not modificable
pedit.addProperty (ResourceProperties.PROP_DESCRIPTION, item.getDescription());
// deal with quota (collections only)
if ((cedit != null) && item.canSetQuota())
{
if (item.hasQuota())
{
// set the quota
pedit.addProperty(ResourceProperties.PROP_COLLECTION_BODY_QUOTA, item.getQuota());
}
else
{
// clear the quota
pedit.removeProperty(ResourceProperties.PROP_COLLECTION_BODY_QUOTA);
}
}
List metadataGroups = (List) state.getAttribute(STATE_METADATA_GROUPS);
state.setAttribute(STATE_EDIT_ALERTS, alerts);
saveMetadata(pedit, metadataGroups, item);
alerts = (Set) state.getAttribute(STATE_EDIT_ALERTS);
// commit the change
if (cedit != null)
{
ContentHostingService.commitCollection(cedit);
}
else
{
ContentHostingService.commitResource(redit, item.getNotification());
}
current_stack_frame.put(STATE_STACK_EDIT_INTENT, INTENT_REVISE_FILE);
Boolean preventPublicDisplay = (Boolean) state.getAttribute(STATE_PREVENT_PUBLIC_DISPLAY);
if(preventPublicDisplay == null)
{
preventPublicDisplay = Boolean.FALSE;
state.setAttribute(STATE_PREVENT_PUBLIC_DISPLAY, preventPublicDisplay);
}
if(preventPublicDisplay.equals(Boolean.FALSE))
{
if (! RESOURCES_MODE_DROPBOX.equalsIgnoreCase((String) state.getAttribute(STATE_MODE_RESOURCES)))
{
if (!item.isPubviewset())
{
ContentHostingService.setPubView(item.getId(), item.isPubview());
}
}
}
// need to refresh collection containing current edit item make changes show up
String containerId = ContentHostingService.getContainingCollectionId(item.getId());
Map expandedCollections = (Map) state.getAttribute(STATE_EXPANDED_COLLECTIONS);
Object old = expandedCollections.remove(containerId);
if (old != null)
{
try
{
ContentCollection container = ContentHostingService.getCollection(containerId);
expandedCollections.put(containerId, container);
}
catch (Throwable ignore){}
}
}
catch (TypeException e)
{
alerts.add(rb.getString("typeex") + " " + item.getId());
// addAlert(state," " + rb.getString("typeex") + " " + item.getId());
}
catch (IdUnusedException e)
{
alerts.add(RESOURCE_NOT_EXIST_STRING);
// addAlert(state,RESOURCE_NOT_EXIST_STRING);
}
catch (PermissionException e)
{
alerts.add(rb.getString("notpermis10") + " " + item.getId());
// addAlert(state, rb.getString("notpermis10") + " " + item.getId() + ". " );
}
catch (InUseException e)
{
alerts.add(rb.getString("someone") + " " + item.getId());
// addAlert(state, rb.getString("someone") + " " + item.getId() + ". ");
}
catch (ServerOverloadException e)
{
alerts.add(rb.getString("failed"));
}
catch (OverQuotaException e)
{
alerts.add(rb.getString("changing1") + " " + item.getId() + " " + rb.getString("changing2"));
// addAlert(state, rb.getString("changing1") + " " + item.getId() + " " + rb.getString("changing2"));
}
catch(RuntimeException e)
{
logger.error("ResourcesAction.doSavechanges ***** Unknown Exception ***** " + e.getMessage());
logger.error("ResourcesAction.doSavechanges ***** Unknown Exception ***** ", e);
alerts.add(rb.getString("failed"));
}
} // if - else
if(alerts.isEmpty())
{
// modify properties sucessful
String mode = (String) state.getAttribute(STATE_MODE);
popFromStack(state);
resetCurrentMode(state);
} //if-else
else
{
Iterator alertIt = alerts.iterator();
while(alertIt.hasNext())
{
String alert = (String) alertIt.next();
addAlert(state, alert);
}
alerts.clear();
state.setAttribute(STATE_EDIT_ALERTS, alerts);
// state.setAttribute(STATE_CREATE_MISSING_ITEM, missing);
}
} // doSavechanges
/**
* @param pedit
* @param metadataGroups
* @param metadata
*/
private static void saveMetadata(ResourcePropertiesEdit pedit, List metadataGroups, EditItem item)
{
if(metadataGroups != null && !metadataGroups.isEmpty())
{
MetadataGroup group = null;
Iterator it = metadataGroups.iterator();
while(it.hasNext())
{
group = (MetadataGroup) it.next();
Iterator props = group.iterator();
while(props.hasNext())
{
ResourcesMetadata prop = (ResourcesMetadata) props.next();
if(ResourcesMetadata.WIDGET_DATETIME.equals(prop.getWidget()) || ResourcesMetadata.WIDGET_DATE.equals(prop.getWidget()) || ResourcesMetadata.WIDGET_TIME.equals(prop.getWidget()))
{
Time val = (Time)item.getMetadata().get(prop.getFullname());
if(val != null)
{
pedit.addProperty(prop.getFullname(), val.toString());
}
}
else
{
String val = (String) item.getMetadata().get(prop.getFullname());
pedit.addProperty(prop.getFullname(), val);
}
}
}
}
}
/**
* @param data
*/
protected static void doToggle_intent(RunData data)
{
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
ParameterParser params = data.getParameters ();
String intent = params.getString("intent");
Map current_stack_frame = peekAtStack(state);
current_stack_frame.put(STATE_STACK_EDIT_INTENT, intent);
} // doToggle_intent
/**
* @param data
*/
public static void doHideOtherSites(RunData data)
{
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
state.setAttribute(STATE_SHOW_OTHER_SITES, Boolean.FALSE.toString());
//get the ParameterParser from RunData
ParameterParser params = data.getParameters ();
// save the current selections
Set selectedSet = new TreeSet();
String[] selectedItems = params.getStrings("selectedMembers");
if(selectedItems != null)
{
selectedSet.addAll(Arrays.asList(selectedItems));
}
state.setAttribute(STATE_LIST_SELECTIONS, selectedSet);
}
/**
* @param data
*/
public static void doShowOtherSites(RunData data)
{
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
//get the ParameterParser from RunData
ParameterParser params = data.getParameters ();
// save the current selections
Set selectedSet = new TreeSet();
String[] selectedItems = params.getStrings("selectedMembers");
if(selectedItems != null)
{
selectedSet.addAll(Arrays.asList(selectedItems));
}
state.setAttribute(STATE_LIST_SELECTIONS, selectedSet);
state.setAttribute(STATE_SHOW_OTHER_SITES, Boolean.TRUE.toString());
}
/**
* @param data
*/
public static void doHide_metadata(RunData data)
{
ParameterParser params = data.getParameters ();
String name = params.getString("metadataGroup");
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
List metadataGroups = (List) state.getAttribute(STATE_METADATA_GROUPS);
if(metadataGroups != null && ! metadataGroups.isEmpty())
{
boolean found = false;
MetadataGroup group = null;
Iterator it = metadataGroups.iterator();
while(!found && it.hasNext())
{
group = (MetadataGroup) it.next();
found = (name.equals(Validator.escapeUrl(group.getName())) || name.equals(group.getName()));
}
if(found)
{
group.setShowing(false);
}
}
} // doHide_metadata
/**
* @param data
*/
public static void doShow_metadata(RunData data)
{
ParameterParser params = data.getParameters ();
String name = params.getString("metadataGroup");
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
List metadataGroups = (List) state.getAttribute(STATE_METADATA_GROUPS);
if(metadataGroups != null && ! metadataGroups.isEmpty())
{
boolean found = false;
MetadataGroup group = null;
Iterator it = metadataGroups.iterator();
while(!found && it.hasNext())
{
group = (MetadataGroup) it.next();
found = (name.equals(Validator.escapeUrl(group.getName())) || name.equals(group.getName()));
}
if(found)
{
group.setShowing(true);
}
}
} // doShow_metadata
/**
* Sort based on the given property
*/
public static void doSort ( RunData data)
{
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
//get the ParameterParser from RunData
ParameterParser params = data.getParameters ();
// save the current selections
Set selectedSet = new TreeSet();
String[] selectedItems = data.getParameters ().getStrings ("selectedMembers");
if(selectedItems != null)
{
selectedSet.addAll(Arrays.asList(selectedItems));
}
state.setAttribute(STATE_LIST_SELECTIONS, selectedSet);
String criteria = params.getString ("criteria");
if (criteria.equals ("title"))
{
criteria = ResourceProperties.PROP_DISPLAY_NAME;
}
else if (criteria.equals ("size"))
{
criteria = ResourceProperties.PROP_CONTENT_LENGTH;
}
else if (criteria.equals ("created by"))
{
criteria = ResourceProperties.PROP_CREATOR;
}
else if (criteria.equals ("last modified"))
{
criteria = ResourceProperties.PROP_MODIFIED_DATE;
}
// current sorting sequence
String asc = NULL_STRING;
if (!criteria.equals (state.getAttribute (STATE_SORT_BY)))
{
state.setAttribute (STATE_SORT_BY, criteria);
asc = Boolean.TRUE.toString();
state.setAttribute (STATE_SORT_ASC, asc);
}
else
{
// current sorting sequence
asc = (String) state.getAttribute (STATE_SORT_ASC);
//toggle between the ascending and descending sequence
if (asc.equals (Boolean.TRUE.toString()))
{
asc = Boolean.FALSE.toString();
}
else
{
asc = Boolean.TRUE.toString();
}
state.setAttribute (STATE_SORT_ASC, asc);
}
if (state.getAttribute(STATE_MESSAGE) == null)
{
// sort sucessful
// state.setAttribute (STATE_MODE, MODE_LIST);
} // if-else
} // doSort
/**
* set the state name to be "deletecofirm" if any item has been selected for deleting
*/
public void doDeleteconfirm ( RunData data)
{
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
Set deleteIdSet = new TreeSet();
// cancel copy if there is one in progress
if(! Boolean.FALSE.toString().equals(state.getAttribute (STATE_COPY_FLAG)))
{
initCopyContext(state);
}
// cancel move if there is one in progress
if(! Boolean.FALSE.toString().equals(state.getAttribute (STATE_MOVE_FLAG)))
{
initMoveContext(state);
}
String[] deleteIds = data.getParameters ().getStrings ("selectedMembers");
if (deleteIds == null)
{
// there is no resource selected, show the alert message to the user
addAlert(state, rb.getString("choosefile3"));
}
else
{
deleteIdSet.addAll(Arrays.asList(deleteIds));
List deleteItems = new Vector();
List notDeleteItems = new Vector();
List nonEmptyFolders = new Vector();
List roots = (List) state.getAttribute(STATE_COLLECTION_ROOTS);
Iterator rootIt = roots.iterator();
while(rootIt.hasNext())
{
BrowseItem root = (BrowseItem) rootIt.next();
List members = root.getMembers();
Iterator memberIt = members.iterator();
while(memberIt.hasNext())
{
BrowseItem member = (BrowseItem) memberIt.next();
if(deleteIdSet.contains(member.getId()))
{
if(member.isFolder())
{
if(ContentHostingService.allowRemoveCollection(member.getId()))
{
deleteItems.add(member);
if(! member.isEmpty())
{
nonEmptyFolders.add(member);
}
}
else
{
notDeleteItems.add(member);
}
}
else if(ContentHostingService.allowRemoveResource(member.getId()))
{
deleteItems.add(member);
}
else
{
notDeleteItems.add(member);
}
}
}
}
if(! notDeleteItems.isEmpty())
{
String notDeleteNames = "";
boolean first_item = true;
Iterator notIt = notDeleteItems.iterator();
while(notIt.hasNext())
{
BrowseItem item = (BrowseItem) notIt.next();
if(first_item)
{
notDeleteNames = item.getName();
first_item = false;
}
else if(notIt.hasNext())
{
notDeleteNames += ", " + item.getName();
}
else
{
notDeleteNames += " and " + item.getName();
}
}
addAlert(state, rb.getString("notpermis14") + notDeleteNames);
}
/*
//htripath-SAK-1712 - Set new collectionId as resources are not deleted under 'more' requirement.
if(state.getAttribute(STATE_MESSAGE) == null){
String newCollectionId=ContentHostingService.getContainingCollectionId(currentId);
state.setAttribute(STATE_COLLECTION_ID, newCollectionId);
}
*/
// delete item
state.setAttribute (STATE_DELETE_ITEMS, deleteItems);
state.setAttribute (STATE_DELETE_ITEMS_NOT_EMPTY, nonEmptyFolders);
} // if-else
if (state.getAttribute(STATE_MESSAGE) == null)
{
state.setAttribute (STATE_MODE, MODE_DELETE_CONFIRM);
state.setAttribute(STATE_LIST_SELECTIONS, deleteIdSet);
}
} // doDeleteconfirm
/**
* set the state name to be "cut" if any item has been selected for cutting
*/
public void doCut ( RunData data)
{
// get the state object
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
String[] cutItems = data.getParameters ().getStrings ("selectedMembers");
if (cutItems == null)
{
// there is no resource selected, show the alert message to the user
addAlert(state, rb.getString("choosefile5"));
state.setAttribute (STATE_MODE, MODE_LIST);
}
else
{
Vector cutIdsVector = new Vector ();
String nonCutIds = NULL_STRING;
String cutId = NULL_STRING;
for (int i = 0; i < cutItems.length; i++)
{
cutId = cutItems[i];
try
{
ResourceProperties properties = ContentHostingService.getProperties (cutId);
if (properties.getProperty (ResourceProperties.PROP_IS_COLLECTION).equals (Boolean.TRUE.toString()))
{
String alert = (String) state.getAttribute(STATE_MESSAGE);
if (alert == null || ((alert != null) && (alert.indexOf(RESOURCE_INVALID_OPERATION_ON_COLLECTION_STRING) == -1)))
{
addAlert(state, RESOURCE_INVALID_OPERATION_ON_COLLECTION_STRING);
}
}
else
{
if (ContentHostingService.allowRemoveResource (cutId))
{
cutIdsVector.add (cutId);
}
else
{
nonCutIds = nonCutIds + " " + properties.getProperty (ResourceProperties.PROP_DISPLAY_NAME) + "; ";
}
}
}
catch (PermissionException e)
{
addAlert(state, rb.getString("notpermis15"));
}
catch (IdUnusedException e)
{
addAlert(state,RESOURCE_NOT_EXIST_STRING);
} // try-catch
}
if (state.getAttribute(STATE_MESSAGE) == null)
{
if (nonCutIds.length ()>0)
{
addAlert(state, rb.getString("notpermis16") +" " + nonCutIds);
}
if (cutIdsVector.size ()>0)
{
state.setAttribute (STATE_CUT_FLAG, Boolean.TRUE.toString());
if (((String) state.getAttribute (STATE_SELECT_ALL_FLAG)).equals (Boolean.TRUE.toString()))
{
state.setAttribute (STATE_SELECT_ALL_FLAG, Boolean.FALSE.toString());
}
Vector copiedIds = (Vector) state.getAttribute (STATE_COPIED_IDS);
for (int i = 0; i < cutIdsVector.size (); i++)
{
String currentId = (String) cutIdsVector.elementAt (i);
if ( copiedIds.contains (currentId))
{
copiedIds.remove (currentId);
}
}
if (copiedIds.size ()==0)
{
state.setAttribute (STATE_COPY_FLAG, Boolean.FALSE.toString());
}
state.setAttribute (STATE_COPIED_IDS, copiedIds);
state.setAttribute (STATE_CUT_IDS, cutIdsVector);
}
}
} // if-else
} // doCut
/**
* set the state name to be "copy" if any item has been selected for copying
*/
public void doCopy ( RunData data )
{
// get the state object
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
// cancel copy if there is one in progress
if(! Boolean.FALSE.toString().equals(state.getAttribute (STATE_COPY_FLAG)))
{
initCopyContext(state);
}
// cancel move if there is one in progress
if(! Boolean.FALSE.toString().equals(state.getAttribute (STATE_MOVE_FLAG)))
{
initMoveContext(state);
}
Vector copyItemsVector = new Vector ();
String[] copyItems = data.getParameters ().getStrings ("selectedMembers");
if (copyItems == null)
{
// there is no resource selected, show the alert message to the user
addAlert(state, rb.getString("choosefile6"));
state.setAttribute (STATE_MODE, MODE_LIST);
}
else
{
String copyId = NULL_STRING;
for (int i = 0; i < copyItems.length; i++)
{
copyId = copyItems[i];
try
{
ResourceProperties properties = ContentHostingService.getProperties (copyId);
/*
if (properties.getProperty (ResourceProperties.PROP_IS_COLLECTION).equals (Boolean.TRUE.toString()))
{
String alert = (String) state.getAttribute(STATE_MESSAGE);
if (alert == null || ((alert != null) && (alert.indexOf(RESOURCE_INVALID_OPERATION_ON_COLLECTION_STRING) == -1)))
{
addAlert(state, RESOURCE_INVALID_OPERATION_ON_COLLECTION_STRING);
}
}
*/
}
catch (PermissionException e)
{
addAlert(state, rb.getString("notpermis15"));
}
catch (IdUnusedException e)
{
addAlert(state,RESOURCE_NOT_EXIST_STRING);
} // try-catch
}
if (state.getAttribute(STATE_MESSAGE) == null)
{
state.setAttribute (STATE_COPY_FLAG, Boolean.TRUE.toString());
copyItemsVector.addAll(Arrays.asList(copyItems));
ContentHostingService.eliminateDuplicates(copyItemsVector);
state.setAttribute (STATE_COPIED_IDS, copyItemsVector);
} // if-else
} // if-else
} // doCopy
/**
* Handle user's selection of items to be moved.
*/
public void doMove ( RunData data )
{
// get the state object
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
List moveItemsVector = new Vector();
// cancel copy if there is one in progress
if(! Boolean.FALSE.toString().equals(state.getAttribute (STATE_COPY_FLAG)))
{
initCopyContext(state);
}
// cancel move if there is one in progress
if(! Boolean.FALSE.toString().equals(state.getAttribute (STATE_MOVE_FLAG)))
{
initMoveContext(state);
}
state.setAttribute(STATE_LIST_SELECTIONS, new TreeSet());
String[] moveItems = data.getParameters ().getStrings ("selectedMembers");
if (moveItems == null)
{
// there is no resource selected, show the alert message to the user
addAlert(state, rb.getString("choosefile6"));
state.setAttribute (STATE_MODE, MODE_LIST);
}
else
{
String moveId = NULL_STRING;
for (int i = 0; i < moveItems.length; i++)
{
moveId = moveItems[i];
try
{
ResourceProperties properties = ContentHostingService.getProperties (moveId);
/*
if (properties.getProperty (ResourceProperties.PROP_IS_COLLECTION).equals (Boolean.TRUE.toString()))
{
String alert = (String) state.getAttribute(STATE_MESSAGE);
if (alert == null || ((alert != null) && (alert.indexOf(RESOURCE_INVALID_OPERATION_ON_COLLECTION_STRING) == -1)))
{
addAlert(state, RESOURCE_INVALID_OPERATION_ON_COLLECTION_STRING);
}
}
*/
}
catch (PermissionException e)
{
addAlert(state, rb.getString("notpermis15"));
}
catch (IdUnusedException e)
{
addAlert(state,RESOURCE_NOT_EXIST_STRING);
} // try-catch
}
if (state.getAttribute(STATE_MESSAGE) == null)
{
state.setAttribute (STATE_MOVE_FLAG, Boolean.TRUE.toString());
moveItemsVector.addAll(Arrays.asList(moveItems));
ContentHostingService.eliminateDuplicates(moveItemsVector);
state.setAttribute (STATE_MOVED_IDS, moveItemsVector);
} // if-else
} // if-else
} // doMove
/**
* If copy-flag is set to false, erase the copied-id's list and set copied flags to false
* in all the browse items. If copied-id's list is empty, set copy-flag to false and set
* copied flags to false in all the browse items. If copy-flag is set to true and copied-id's
* list is not empty, update the copied flags of all browse items so copied flags for the
* copied items are set to true and all others are set to false.
*/
protected void setCopyFlags(SessionState state)
{
String copyFlag = (String) state.getAttribute(STATE_COPY_FLAG);
List copyItemsVector = (List) state.getAttribute(STATE_COPIED_IDS);
if(copyFlag == null)
{
copyFlag = Boolean.FALSE.toString();
state.setAttribute(STATE_COPY_FLAG, copyFlag);
}
if(copyFlag.equals(Boolean.TRUE.toString()))
{
if(copyItemsVector == null)
{
copyItemsVector = new Vector();
state.setAttribute(STATE_COPIED_IDS, copyItemsVector);
}
if(copyItemsVector.isEmpty())
{
state.setAttribute(STATE_COPY_FLAG, Boolean.FALSE.toString());
}
}
else
{
copyItemsVector = new Vector();
state.setAttribute(STATE_COPIED_IDS, copyItemsVector);
}
List roots = (List) state.getAttribute(STATE_COLLECTION_ROOTS);
Iterator rootIt = roots.iterator();
while(rootIt.hasNext())
{
BrowseItem root = (BrowseItem) rootIt.next();
boolean root_copied = copyItemsVector.contains(root.getId());
root.setCopied(root_copied);
List members = root.getMembers();
Iterator memberIt = members.iterator();
while(memberIt.hasNext())
{
BrowseItem member = (BrowseItem) memberIt.next();
boolean member_copied = copyItemsVector.contains(member.getId());
member.setCopied(member_copied);
}
}
// check -- jim
state.setAttribute(STATE_COLLECTION_ROOTS, roots);
} // setCopyFlags
/**
* Expand all the collection resources.
*/
static public void doExpandall ( RunData data)
{
// get the state object
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
//get the ParameterParser from RunData
ParameterParser params = data.getParameters ();
// save the current selections
Set selectedSet = new TreeSet();
String[] selectedItems = params.getStrings("selectedMembers");
if(selectedItems != null)
{
selectedSet.addAll(Arrays.asList(selectedItems));
}
state.setAttribute(STATE_LIST_SELECTIONS, selectedSet);
// expansion actually occurs in getBrowseItems method.
state.setAttribute(STATE_EXPAND_ALL_FLAG, Boolean.TRUE.toString());
state.setAttribute(STATE_NEED_TO_EXPAND_ALL, Boolean.TRUE.toString());
} // doExpandall
/**
* Unexpand all the collection resources
*/
public static void doUnexpandall ( RunData data)
{
// get the state object
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
//get the ParameterParser from RunData
ParameterParser params = data.getParameters ();
// save the current selections
Set selectedSet = new TreeSet();
String[] selectedItems = params.getStrings ("selectedMembers");
if(selectedItems != null)
{
selectedSet.addAll(Arrays.asList(selectedItems));
}
state.setAttribute(STATE_LIST_SELECTIONS, selectedSet);
state.setAttribute(STATE_EXPANDED_COLLECTIONS, new HashMap());
state.setAttribute(STATE_EXPAND_ALL_FLAG, Boolean.FALSE.toString());
} // doUnexpandall
/**
* Populate the state object, if needed - override to do something!
*/
protected void initState(SessionState state, VelocityPortlet portlet, JetspeedRunData data)
{
super.initState(state, portlet, data);
if(state.getAttribute(STATE_INITIALIZED) == null)
{
initCopyContext(state);
initMoveContext(state);
}
initStateAttributes(state, portlet);
} // initState
/**
* Remove the state variables used internally, on the way out.
*/
static private void cleanupState(SessionState state)
{
state.removeAttribute(STATE_FROM_TEXT);
state.removeAttribute(STATE_HAS_ATTACHMENT_BEFORE);
state.removeAttribute(STATE_ATTACH_SHOW_DROPBOXES);
state.removeAttribute(STATE_ATTACH_COLLECTION_ID);
state.removeAttribute(COPYRIGHT_FAIRUSE_URL);
state.removeAttribute(COPYRIGHT_NEW_COPYRIGHT);
state.removeAttribute(COPYRIGHT_SELF_COPYRIGHT);
state.removeAttribute(COPYRIGHT_TYPES);
state.removeAttribute(DEFAULT_COPYRIGHT_ALERT);
state.removeAttribute(DEFAULT_COPYRIGHT);
state.removeAttribute(STATE_EXPANDED_COLLECTIONS);
state.removeAttribute(STATE_FILE_UPLOAD_MAX_SIZE);
state.removeAttribute(NEW_COPYRIGHT_INPUT);
state.removeAttribute(STATE_COLLECTION_ID);
state.removeAttribute(STATE_COLLECTION_PATH);
state.removeAttribute(STATE_CONTENT_SERVICE);
state.removeAttribute(STATE_CONTENT_TYPE_IMAGE_SERVICE);
//state.removeAttribute(STATE_STACK_EDIT_INTENT);
state.removeAttribute(STATE_EXPAND_ALL_FLAG);
state.removeAttribute(STATE_HELPER_NEW_ITEMS);
state.removeAttribute(STATE_HELPER_CHANGED);
state.removeAttribute(STATE_HOME_COLLECTION_DISPLAY_NAME);
state.removeAttribute(STATE_HOME_COLLECTION_ID);
state.removeAttribute(STATE_LIST_SELECTIONS);
state.removeAttribute(STATE_MY_COPYRIGHT);
state.removeAttribute(STATE_NAVIGATION_ROOT);
state.removeAttribute(STATE_PASTE_ALLOWED_FLAG);
state.removeAttribute(STATE_SELECT_ALL_FLAG);
state.removeAttribute(STATE_SHOW_ALL_SITES);
state.removeAttribute(STATE_SITE_TITLE);
state.removeAttribute(STATE_SORT_ASC);
state.removeAttribute(STATE_SORT_BY);
state.removeAttribute(STATE_STACK_STRUCTOBJ_TYPE);
state.removeAttribute(STATE_STACK_STRUCTOBJ_TYPE_READONLY);
state.removeAttribute(STATE_INITIALIZED);
state.removeAttribute(VelocityPortletPaneledAction.STATE_HELPER);
} // cleanupState
public static void initStateAttributes(SessionState state, VelocityPortlet portlet)
{
if (state.getAttribute (STATE_INITIALIZED) != null) return;
if (state.getAttribute(STATE_FILE_UPLOAD_MAX_SIZE) == null)
{
state.setAttribute(STATE_FILE_UPLOAD_MAX_SIZE, ServerConfigurationService.getString("content.upload.max", "1"));
}
PortletConfig config = portlet.getPortletConfig();
try
{
Integer size = new Integer(config.getInitParameter(PARAM_PAGESIZE));
if(size == null || size.intValue() < 1)
{
size = new Integer(DEFAULT_PAGE_SIZE);
}
state.setAttribute(STATE_PAGESIZE, size);
}
catch(Exception any)
{
state.setAttribute(STATE_PAGESIZE, new Integer(DEFAULT_PAGE_SIZE));
}
// state.setAttribute(STATE_TOP_PAGE_MESSAGE, "");
state.setAttribute (STATE_CONTENT_SERVICE, ContentHostingService.getInstance());
state.setAttribute (STATE_CONTENT_TYPE_IMAGE_SERVICE, ContentTypeImageService.getInstance());
TimeBreakdown timeBreakdown = (TimeService.newTime()).breakdownLocal ();
String mycopyright = COPYRIGHT_SYMBOL + " " + timeBreakdown.getYear () +", " + UserDirectoryService.getCurrentUser().getDisplayName () + ". All Rights Reserved. ";
state.setAttribute (STATE_MY_COPYRIGHT, mycopyright);
if(state.getAttribute(STATE_MODE) == null)
{
state.setAttribute (STATE_MODE, MODE_LIST);
state.setAttribute (STATE_FROM, NULL_STRING);
}
state.setAttribute (STATE_SORT_BY, ResourceProperties.PROP_DISPLAY_NAME);
state.setAttribute (STATE_SORT_ASC, Boolean.TRUE.toString());
state.setAttribute (STATE_SELECT_ALL_FLAG, Boolean.FALSE.toString());
state.setAttribute (STATE_EXPAND_ALL_FLAG, Boolean.FALSE.toString());
state.setAttribute(STATE_LIST_SELECTIONS, new TreeSet());
state.setAttribute (STATE_COLLECTION_PATH, new Vector ());
// %%STATE_MODE_RESOURCES%%
// In helper mode, calling tool should set attribute STATE_MODE_RESOURCES
String resources_mode = (String) state.getAttribute(STATE_MODE_RESOURCES);
if(resources_mode == null)
{
// get resources mode from tool registry
resources_mode = portlet.getPortletConfig().getInitParameter("resources_mode");
if(resources_mode != null)
{
state.setAttribute(STATE_MODE_RESOURCES, resources_mode);
}
}
boolean show_other_sites = false;
if(RESOURCES_MODE_HELPER.equals(resources_mode))
{
show_other_sites = ServerConfigurationService.getBoolean("resources.show_all_collections.helper", SHOW_ALL_SITES_IN_FILE_PICKER);
}
else if(RESOURCES_MODE_DROPBOX.equals(resources_mode))
{
show_other_sites = ServerConfigurationService.getBoolean("resources.show_all_collections.dropbox", SHOW_ALL_SITES_IN_DROPBOX);
}
else
{
show_other_sites = ServerConfigurationService.getBoolean("resources.show_all_collections.tool", SHOW_ALL_SITES_IN_RESOURCES);
}
/** This attribute indicates whether "Other Sites" twiggle should show */
state.setAttribute(STATE_SHOW_ALL_SITES, Boolean.toString(show_other_sites));
/** This attribute indicates whether "Other Sites" twiggle should be open */
state.setAttribute(STATE_SHOW_OTHER_SITES, Boolean.FALSE.toString());
// set the home collection to the parameter, if present, or the default if not
String home = StringUtil.trimToNull(portlet.getPortletConfig().getInitParameter("home"));
state.setAttribute (STATE_HOME_COLLECTION_DISPLAY_NAME, home);
if ((home == null) || (home.length() == 0))
{
// no home set, see if we are in dropbox mode
if (RESOURCES_MODE_DROPBOX.equalsIgnoreCase(resources_mode))
{
home = ContentHostingService.getDropboxCollection();
// if it came back null, we will pretend not to be in dropbox mode
if (home != null)
{
state.setAttribute(STATE_HOME_COLLECTION_DISPLAY_NAME, ContentHostingService.getDropboxDisplayName());
// create/update the collection of folders in the dropbox
ContentHostingService.createDropboxCollection();
}
}
// if we still don't have a home,
if ((home == null) || (home.length() == 0))
{
home = ContentHostingService.getSiteCollection(ToolManager.getCurrentPlacement().getContext());
// TODO: what's the 'name' of the context? -ggolden
// we'll need this to create the home collection if needed
state.setAttribute (STATE_HOME_COLLECTION_DISPLAY_NAME, ToolManager.getCurrentPlacement().getContext()
/*SiteService.getSiteDisplay(ToolManager.getCurrentPlacement().getContext()) */);
}
}
state.setAttribute (STATE_HOME_COLLECTION_ID, home);
state.setAttribute (STATE_COLLECTION_ID, home);
state.setAttribute (STATE_NAVIGATION_ROOT, home);
HomeFactory factory = (HomeFactory) ComponentManager.get("homeFactory");
if(factory != null)
{
Map homes = factory.getHomes(StructuredArtifactHomeInterface.class);
if(! homes.isEmpty())
{
state.setAttribute(STATE_SHOW_FORM_ITEMS, Boolean.TRUE.toString());
}
}
// state.setAttribute (STATE_COLLECTION_ID, state.getAttribute (STATE_HOME_COLLECTION_ID));
if (state.getAttribute(STATE_SITE_TITLE) == null)
{
String title = "";
try
{
title = ((Site) SiteService.getSite(ToolManager.getCurrentPlacement().getContext())).getTitle();
}
catch (IdUnusedException e)
{ // ignore
}
state.setAttribute(STATE_SITE_TITLE, title);
}
HashMap expandedCollections = new HashMap();
//expandedCollections.add (state.getAttribute (STATE_HOME_COLLECTION_ID));
state.setAttribute(STATE_EXPANDED_COLLECTIONS, expandedCollections);
if(state.getAttribute(STATE_USING_CREATIVE_COMMONS) == null)
{
String usingCreativeCommons = ServerConfigurationService.getString("copyright.use_creative_commons");
if( usingCreativeCommons != null && usingCreativeCommons.equalsIgnoreCase(Boolean.TRUE.toString()))
{
state.setAttribute(STATE_USING_CREATIVE_COMMONS, Boolean.TRUE.toString());
}
else
{
state.setAttribute(STATE_USING_CREATIVE_COMMONS, Boolean.FALSE.toString());
}
}
if (state.getAttribute(COPYRIGHT_TYPES) == null)
{
if (ServerConfigurationService.getStrings("copyrighttype") != null)
{
state.setAttribute(COPYRIGHT_TYPES, new ArrayList(Arrays.asList(ServerConfigurationService.getStrings("copyrighttype"))));
}
}
if (state.getAttribute(DEFAULT_COPYRIGHT) == null)
{
if (ServerConfigurationService.getString("default.copyright") != null)
{
state.setAttribute(DEFAULT_COPYRIGHT, ServerConfigurationService.getString("default.copyright"));
}
}
if (state.getAttribute(DEFAULT_COPYRIGHT_ALERT) == null)
{
if (ServerConfigurationService.getString("default.copyright.alert") != null)
{
state.setAttribute(DEFAULT_COPYRIGHT_ALERT, ServerConfigurationService.getString("default.copyright.alert"));
}
}
if (state.getAttribute(NEW_COPYRIGHT_INPUT) == null)
{
if (ServerConfigurationService.getString("newcopyrightinput") != null)
{
state.setAttribute(NEW_COPYRIGHT_INPUT, ServerConfigurationService.getString("newcopyrightinput"));
}
}
if (state.getAttribute(COPYRIGHT_FAIRUSE_URL) == null)
{
if (ServerConfigurationService.getString("fairuse.url") != null)
{
state.setAttribute(COPYRIGHT_FAIRUSE_URL, ServerConfigurationService.getString("fairuse.url"));
}
}
if (state.getAttribute(COPYRIGHT_SELF_COPYRIGHT) == null)
{
if (ServerConfigurationService.getString("copyrighttype.own") != null)
{
state.setAttribute(COPYRIGHT_SELF_COPYRIGHT, ServerConfigurationService.getString("copyrighttype.own"));
}
}
if (state.getAttribute(COPYRIGHT_NEW_COPYRIGHT) == null)
{
if (ServerConfigurationService.getString("copyrighttype.new") != null)
{
state.setAttribute(COPYRIGHT_NEW_COPYRIGHT, ServerConfigurationService.getString("copyrighttype.new"));
}
}
// get resources mode from tool registry
String optional_properties = portlet.getPortletConfig().getInitParameter("optional_properties");
if(optional_properties != null && "true".equalsIgnoreCase(optional_properties))
{
initMetadataContext(state);
}
state.setAttribute(STATE_PREVENT_PUBLIC_DISPLAY, Boolean.FALSE);
String[] siteTypes = ServerConfigurationService.getStrings("prevent.public.resources");
if(siteTypes != null)
{
Site site;
try
{
site = SiteService.getSite(ToolManager.getCurrentPlacement().getContext());
for(int i = 0; i < siteTypes.length; i++)
{
if ((StringUtil.trimToNull(siteTypes[i])).equals(site.getType()))
{
state.setAttribute(STATE_PREVENT_PUBLIC_DISPLAY, Boolean.TRUE);
}
}
}
catch (IdUnusedException e)
{
// allow public display
}
catch(NullPointerException e)
{
// allow public display
}
}
state.setAttribute (STATE_INITIALIZED, Boolean.TRUE.toString());
}
/**
* Setup our observer to be watching for change events for the collection
*/
private void updateObservation(SessionState state, String peid)
{
// ContentObservingCourier observer = (ContentObservingCourier) state.getAttribute(STATE_OBSERVER);
//
// // the delivery location for this tool
// String deliveryId = clientWindowId(state, peid);
// observer.setDeliveryId(deliveryId);
}
/**
* Add additional resource pattern to the observer
*@param pattern The pattern value to be added
*@param state The state object
*/
private static void addObservingPattern(String pattern, SessionState state)
{
// // get the observer and add the pattern
// ContentObservingCourier o = (ContentObservingCourier) state.getAttribute(STATE_OBSERVER);
// o.addResourcePattern(ContentHostingService.getReference(pattern));
//
// // add it back to state
// state.setAttribute(STATE_OBSERVER, o);
} // addObservingPattern
/**
* Remove a resource pattern from the observer
*@param pattern The pattern value to be removed
*@param state The state object
*/
private static void removeObservingPattern(String pattern, SessionState state)
{
// // get the observer and remove the pattern
// ContentObservingCourier o = (ContentObservingCourier) state.getAttribute(STATE_OBSERVER);
// o.removeResourcePattern(ContentHostingService.getReference(pattern));
//
// // add it back to state
// state.setAttribute(STATE_OBSERVER, o);
} // removeObservingPattern
/**
* initialize the copy context
*/
private static void initCopyContext (SessionState state)
{
state.setAttribute (STATE_COPIED_IDS, new Vector ());
state.setAttribute (STATE_COPY_FLAG, Boolean.FALSE.toString());
} // initCopyContent
/**
* initialize the copy context
*/
private static void initMoveContext (SessionState state)
{
state.setAttribute (STATE_MOVED_IDS, new Vector ());
state.setAttribute (STATE_MOVE_FLAG, Boolean.FALSE.toString());
} // initCopyContent
/**
* initialize the cut context
*/
private void initCutContext (SessionState state)
{
state.setAttribute (STATE_CUT_IDS, new Vector ());
state.setAttribute (STATE_CUT_FLAG, Boolean.FALSE.toString());
} // initCutContent
/**
* find out whether there is a duplicate item in testVector
* @param testVector The Vector to be tested on
* @param testSize The integer of the test range
* @return The index value of the duplicate ite
*/
private int repeatedName (Vector testVector, int testSize)
{
for (int i=1; i <= testSize; i++)
{
String currentName = (String) testVector.get (i);
for (int j=i+1; j <= testSize; j++)
{
String comparedTitle = (String) testVector.get (j);
if (comparedTitle.length()>0 && currentName.length()>0 && comparedTitle.equals (currentName))
{
return j;
}
}
}
return 0;
} // repeatedName
/**
* Is the id already exist in the current resource?
* @param testVector The Vector to be tested on
* @param testSize The integer of the test range
* @parma isCollection Looking for collection or not
* @return The index value of the exist id
*/
private int foundInResource (Vector testVector, int testSize, String collectionId, boolean isCollection)
{
try
{
ContentCollection c = ContentHostingService.getCollection(collectionId);
Iterator membersIterator = c.getMemberResources().iterator();
while (membersIterator.hasNext())
{
ResourceProperties p = ((Entity) membersIterator.next()).getProperties();
String displayName = p.getProperty(ResourceProperties.PROP_DISPLAY_NAME);
if (displayName != null)
{
String collectionOrResource = p.getProperty(ResourceProperties.PROP_IS_COLLECTION);
for (int i=1; i <= testSize; i++)
{
String testName = (String) testVector.get(i);
if ((testName != null) && (displayName.equals (testName))
&& ((isCollection && collectionOrResource.equals (Boolean.TRUE.toString()))
|| (!isCollection && collectionOrResource.equals(Boolean.FALSE.toString()))))
{
return i;
}
} // for
}
}
}
catch (IdUnusedException e){}
catch (TypeException e){}
catch (PermissionException e){}
return 0;
} // foundInResource
/**
* empty String Vector object with the size sepecified
* @param size The Vector object size -1
* @return The Vector object consists of null Strings
*/
private static Vector emptyVector (int size)
{
Vector v = new Vector ();
for (int i=0; i <= size; i++)
{
v.add (i, "");
}
return v;
} // emptyVector
/**
* Setup for customization
**/
public String buildOptionsPanelContext( VelocityPortlet portlet,
Context context,
RunData data,
SessionState state)
{
context.put("tlang",rb);
String home = (String) state.getAttribute(STATE_HOME_COLLECTION_ID);
Reference ref = EntityManager.newReference(ContentHostingService.getReference(home));
String siteId = ref.getContext();
context.put("form-submit", BUTTON + "doConfigure_update");
context.put("form-cancel", BUTTON + "doCancel_options");
context.put("description", "Setting options for Resources in worksite "
+ SiteService.getSiteDisplay(siteId));
// pick the "-customize" template based on the standard template name
String template = (String)getContext(data).get("template");
return template + "-customize";
} // buildOptionsPanelContext
/**
* Handle the configure context's update button
*/
public void doConfigure_update(RunData data, Context context)
{
// access the portlet element id to find our state
String peid = ((JetspeedRunData)data).getJs_peid();
SessionState state = ((JetspeedRunData)data).getPortletSessionState(peid);
// we are done with customization... back to the main (browse) mode
state.setAttribute(STATE_MODE, MODE_LIST);
// commit the change
// saveOptions();
cancelOptions();
} // doConfigure_update
/**
* doCancel_options called for form input tags type="submit" named="eventSubmit_doCancel"
* cancel the options process
*/
public void doCancel_options(RunData data, Context context)
{
// access the portlet element id to find our state
String peid = ((JetspeedRunData)data).getJs_peid();
SessionState state = ((JetspeedRunData)data).getPortletSessionState(peid);
// cancel the options
cancelOptions();
// we are done with customization... back to the main (MODE_LIST) mode
state.setAttribute(STATE_MODE, MODE_LIST);
} // doCancel_options
/**
* Add the collection id into the expanded collection list
* @throws PermissionException
* @throws TypeException
* @throws IdUnusedException
*/
public static void doExpand_collection(RunData data) throws IdUnusedException, TypeException, PermissionException
{
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
HashMap currentMap = (HashMap) state.getAttribute(STATE_EXPANDED_COLLECTIONS);
//get the ParameterParser from RunData
ParameterParser params = data.getParameters ();
// save the current selections
Set selectedSet = new TreeSet();
String[] selectedItems = params.getStrings ("selectedMembers");
if(selectedItems != null)
{
selectedSet.addAll(Arrays.asList(selectedItems));
}
state.setAttribute(STATE_LIST_SELECTIONS, selectedSet);
String id = params.getString("collectionId");
currentMap.put (id,ContentHostingService.getCollection (id));
state.setAttribute(STATE_EXPANDED_COLLECTIONS, currentMap);
// add this folder id into the set to be event-observed
addObservingPattern(id, state);
} // doExpand_collection
/**
* Remove the collection id from the expanded collection list
*/
static public void doCollapse_collection(RunData data)
{
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
HashMap currentMap = (HashMap) state.getAttribute(STATE_EXPANDED_COLLECTIONS);
//get the ParameterParser from RunData
ParameterParser params = data.getParameters ();
String collectionId = params.getString("collectionId");
// save the current selections
Set selectedSet = new TreeSet();
String[] selectedItems = data.getParameters ().getStrings ("selectedMembers");
if(selectedItems != null)
{
selectedSet.addAll(Arrays.asList(selectedItems));
}
state.setAttribute(STATE_LIST_SELECTIONS, selectedSet);
HashMap newSet = new HashMap();
Iterator l = currentMap.keySet().iterator ();
while (l.hasNext ())
{
// remove the collection id and all of the subcollections
// Resource collection = (Resource) l.next();
// String id = (String) collection.getId();
String id = (String) l.next();
if (id.indexOf (collectionId)==-1)
{
// newSet.put(id,collection);
newSet.put(id,currentMap.get(id));
}
}
state.setAttribute(STATE_EXPANDED_COLLECTIONS, newSet);
// remove this folder id into the set to be event-observed
removeObservingPattern(collectionId, state);
} // doCollapse_collection
/**
* @param state
* @param homeCollectionId
* @param currentCollectionId
* @return
*/
public static List getCollectionPath(SessionState state)
{
org.sakaiproject.content.api.ContentHostingService contentService = (org.sakaiproject.content.api.ContentHostingService) state.getAttribute (STATE_CONTENT_SERVICE);
// make sure the channedId is set
String currentCollectionId = (String) state.getAttribute (STATE_COLLECTION_ID);
if(! isStackEmpty(state))
{
Map current_stack_frame = peekAtStack(state);
String createCollectionId = (String) current_stack_frame.get(STATE_STACK_CREATE_COLLECTION_ID);
if(createCollectionId == null)
{
createCollectionId = (String) state.getAttribute(STATE_CREATE_COLLECTION_ID);
}
if(createCollectionId != null)
{
currentCollectionId = createCollectionId;
}
else
{
String editCollectionId = (String) current_stack_frame.get(STATE_EDIT_COLLECTION_ID);
if(editCollectionId == null)
{
editCollectionId = (String) state.getAttribute(STATE_EDIT_COLLECTION_ID);
}
if(editCollectionId != null)
{
currentCollectionId = editCollectionId;
}
}
}
String homeCollectionId = (String) state.getAttribute(STATE_HOME_COLLECTION_ID);
String navRoot = (String) state.getAttribute(STATE_NAVIGATION_ROOT);
LinkedList collectionPath = new LinkedList();
String previousCollectionId = "";
Vector pathitems = new Vector();
while(currentCollectionId != null && ! currentCollectionId.equals(navRoot) && ! currentCollectionId.equals(previousCollectionId))
{
pathitems.add(currentCollectionId);
previousCollectionId = currentCollectionId;
currentCollectionId = contentService.getContainingCollectionId(currentCollectionId);
}
pathitems.add(navRoot);
if(!navRoot.equals(homeCollectionId))
{
pathitems.add(homeCollectionId);
}
Iterator items = pathitems.iterator();
while(items.hasNext())
{
String id = (String) items.next();
try
{
ResourceProperties props = contentService.getProperties(id);
String name = props.getPropertyFormatted(ResourceProperties.PROP_DISPLAY_NAME);
PathItem item = new PathItem(id, name);
boolean canRead = contentService.allowGetCollection(id) || contentService.allowGetResource(id);
item.setCanRead(canRead);
String url = contentService.getUrl(id);
item.setUrl(url);
item.setLast(collectionPath.isEmpty());
if(id.equals(homeCollectionId))
{
item.setRoot(homeCollectionId);
}
else
{
item.setRoot(navRoot);
}
try
{
boolean isFolder = props.getBooleanProperty(ResourceProperties.PROP_IS_COLLECTION);
item.setIsFolder(isFolder);
}
catch (EntityPropertyNotDefinedException e1)
{
}
catch (EntityPropertyTypeException e1)
{
}
collectionPath.addFirst(item);
}
catch (PermissionException e)
{
}
catch (IdUnusedException e)
{
}
}
return collectionPath;
}
/**
* Get the items in this folder that should be seen.
* @param collectionId - String version of
* @param expandedCollections - Hash of collection resources
* @param sortedBy - pass through to ContentHostingComparator
* @param sortedAsc - pass through to ContentHostingComparator
* @param parent - The folder containing this item
* @param isLocal - true if navigation root and home collection id of site are the same, false otherwise
* @param state - The session state
* @return a List of BrowseItem objects
*/
protected static List getBrowseItems(String collectionId, HashMap expandedCollections, Set highlightedItems, String sortedBy, String sortedAsc, BrowseItem parent, boolean isLocal, SessionState state)
{
boolean need_to_expand_all = Boolean.TRUE.toString().equals((String)state.getAttribute(STATE_NEED_TO_EXPAND_ALL));
List newItems = new LinkedList();
try
{
// find the ContentHosting service
org.sakaiproject.content.api.ContentHostingService contentService = (org.sakaiproject.content.api.ContentHostingService) state.getAttribute (STATE_CONTENT_SERVICE);
// get the collection
// try using existing resource first
ContentCollection collection = null;
// get the collection
if (expandedCollections.containsKey(collectionId))
{
collection = (ContentCollection) expandedCollections.get(collectionId);
}
else
{
collection = ContentHostingService.getCollection(collectionId);
if(need_to_expand_all)
{
expandedCollections.put(collectionId, collection);
state.setAttribute(STATE_EXPANDED_COLLECTIONS, expandedCollections);
}
}
String dummyId = collectionId.trim();
if(dummyId.endsWith(Entity.SEPARATOR))
{
dummyId += "dummy";
}
else
{
dummyId += Entity.SEPARATOR + "dummy";
}
boolean canRead = false;
boolean canDelete = false;
boolean canRevise = false;
boolean canAddFolder = false;
boolean canAddItem = false;
boolean canUpdate = false;
int depth = 0;
if(parent == null || ! parent.canRead())
{
canRead = contentService.allowGetCollection(collectionId);
}
else
{
canRead = parent.canRead();
}
if(parent == null || ! parent.canDelete())
{
canDelete = contentService.allowRemoveResource(collectionId);
}
else
{
canDelete = parent.canDelete();
}
if(parent == null || ! parent.canRevise())
{
canRevise = contentService.allowUpdateResource(collectionId);
}
else
{
canRevise = parent.canRevise();
}
if(parent == null || ! parent.canAddFolder())
{
canAddFolder = contentService.allowAddCollection(dummyId);
}
else
{
canAddFolder = parent.canAddFolder();
}
if(parent == null || ! parent.canAddItem())
{
canAddItem = contentService.allowAddResource(dummyId);
}
else
{
canAddItem = parent.canAddItem();
}
if(parent == null || ! parent.canUpdate())
{
canUpdate = AuthzGroupService.allowUpdate(collectionId);
}
else
{
canUpdate = parent.canUpdate();
}
if(parent != null)
{
depth = parent.getDepth() + 1;
}
if(canAddItem)
{
state.setAttribute(STATE_PASTE_ALLOWED_FLAG, Boolean.TRUE.toString());
}
boolean hasDeletableChildren = canDelete;
boolean hasCopyableChildren = canRead;
String homeCollectionId = (String) state.getAttribute(STATE_HOME_COLLECTION_ID);
ResourceProperties cProperties = collection.getProperties();
String folderName = cProperties.getProperty(ResourceProperties.PROP_DISPLAY_NAME);
if(collectionId.equals(homeCollectionId))
{
folderName = (String) state.getAttribute(STATE_HOME_COLLECTION_DISPLAY_NAME);
}
BrowseItem folder = new BrowseItem(collectionId, folderName, "folder");
if(parent == null)
{
folder.setRoot(collectionId);
}
else
{
folder.setRoot(parent.getRoot());
}
BasicRightsAssignment rightsObj = new BasicRightsAssignment(folder.getItemNum(), cProperties);
folder.setRights(rightsObj);
AccessMode access = collection.getAccess();
if(access == null || AccessMode.SITE.equals(access))
{
folder.setAccess(AccessMode.INHERITED.toString());
}
else
{
folder.setAccess(access.toString());
}
AccessMode inherited_access = collection.getInheritedAccess();
if(inherited_access == null || AccessMode.SITE.equals(inherited_access))
{
folder.setInheritedAccess(AccessMode.INHERITED.toString());
}
else
{
folder.setInheritedAccess(inherited_access.toString());
}
Collection access_groups = collection.getGroupObjects();
if(access_groups == null)
{
access_groups = new Vector();
}
Collection inherited_access_groups = collection.getInheritedGroupObjects();
if(inherited_access_groups == null)
{
inherited_access_groups = new Vector();
}
folder.setInheritedGroups(access_groups);
if(highlightedItems == null || highlightedItems.isEmpty())
{
// do nothing
}
else if(parent != null && parent.isHighlighted())
{
folder.setInheritsHighlight(true);
folder.setHighlighted(true);
}
else if(highlightedItems.contains(collectionId))
{
folder.setHighlighted(true);
folder.setInheritsHighlight(false);
}
String containerId = contentService.getContainingCollectionId (collectionId);
folder.setContainer(containerId);
folder.setCanRead(canRead);
folder.setCanRevise(canRevise);
folder.setCanAddItem(canAddItem);
folder.setCanAddFolder(canAddFolder);
folder.setCanDelete(canDelete);
folder.setCanUpdate(canUpdate);
try
{
Time createdTime = cProperties.getTimeProperty(ResourceProperties.PROP_CREATION_DATE);
String createdTimeString = createdTime.toStringLocalShortDate();
folder.setCreatedTime(createdTimeString);
}
catch(Exception e)
{
String createdTimeString = cProperties.getProperty(ResourceProperties.PROP_CREATION_DATE);
folder.setCreatedTime(createdTimeString);
}
try
{
String createdBy = getUserProperty(cProperties, ResourceProperties.PROP_CREATOR).getDisplayName();
folder.setCreatedBy(createdBy);
}
catch(Exception e)
{
String createdBy = cProperties.getProperty(ResourceProperties.PROP_CREATOR);
folder.setCreatedBy(createdBy);
}
try
{
Time modifiedTime = cProperties.getTimeProperty(ResourceProperties.PROP_MODIFIED_DATE);
String modifiedTimeString = modifiedTime.toStringLocalShortDate();
folder.setModifiedTime(modifiedTimeString);
}
catch(Exception e)
{
String modifiedTimeString = cProperties.getProperty(ResourceProperties.PROP_MODIFIED_DATE);
folder.setModifiedTime(modifiedTimeString);
}
try
{
String modifiedBy = getUserProperty(cProperties, ResourceProperties.PROP_MODIFIED_BY).getDisplayName();
folder.setModifiedBy(modifiedBy);
}
catch(Exception e)
{
String modifiedBy = cProperties.getProperty(ResourceProperties.PROP_MODIFIED_BY);
folder.setModifiedBy(modifiedBy);
}
String url = contentService.getUrl(collectionId);
folder.setUrl(url);
try
{
int collection_size = contentService.getCollectionSize(collectionId);
folder.setIsEmpty(collection_size < 1);
folder.setIsTooBig(collection_size > EXPANDABLE_FOLDER_SIZE_LIMIT);
}
catch(RuntimeException e)
{
folder.setIsEmpty(true);
folder.setIsTooBig(false);
}
folder.setDepth(depth);
newItems.add(folder);
if(need_to_expand_all || expandedCollections.containsKey (collectionId))
{
// Get the collection members from the 'new' collection
List newMembers = collection.getMemberResources ();
Collections.sort (newMembers, ContentHostingService.newContentHostingComparator (sortedBy, Boolean.valueOf (sortedAsc).booleanValue ()));
// loop thru the (possibly) new members and add to the list
Iterator it = newMembers.iterator();
while(it.hasNext())
{
ContentEntity resource = (ContentEntity) it.next();
ResourceProperties props = resource.getProperties();
String itemId = resource.getId();
if(resource.isCollection())
{
List offspring = getBrowseItems(itemId, expandedCollections, highlightedItems, sortedBy, sortedAsc, folder, isLocal, state);
if(! offspring.isEmpty())
{
BrowseItem child = (BrowseItem) offspring.get(0);
hasDeletableChildren = hasDeletableChildren || child.hasDeletableChildren();
hasCopyableChildren = hasCopyableChildren || child.hasCopyableChildren();
}
// add all the items in the subfolder to newItems
newItems.addAll(offspring);
}
else
{
String itemType = ((ContentResource)resource).getContentType();
String itemName = props.getProperty(ResourceProperties.PROP_DISPLAY_NAME);
BrowseItem newItem = new BrowseItem(itemId, itemName, itemType);
BasicRightsAssignment rightsObj2 = new BasicRightsAssignment(newItem.getItemNum(), props);
newItem.setRights(rightsObj2);
AccessMode access_mode = ((GroupAwareEntity) resource).getAccess();
if(access_mode == null)
{
newItem.setAccess(AccessMode.SITE.toString());
}
else
{
newItem.setAccess(access_mode.toString());
}
Collection groups = ((GroupAwareEntity) resource).getGroupObjects();
if(groups == null)
{
groups = new Vector();
}
Collection inheritedGroups = ((GroupAwareEntity) resource).getInheritedGroupObjects();
if(inheritedGroups == null)
{
inheritedGroups = new Vector();
}
newItem.setGroups(groups);
newItem.setInheritedGroups(inheritedGroups);
newItem.setContainer(collectionId);
newItem.setRoot(folder.getRoot());
newItem.setCanDelete(canDelete);
newItem.setCanRevise(canRevise);
newItem.setCanRead(canRead);
newItem.setCanCopy(canRead);
newItem.setCanAddItem(canAddItem); // true means this user can add an item in the folder containing this item (used for "duplicate")
if(highlightedItems == null || highlightedItems.isEmpty())
{
// do nothing
}
else if(folder.isHighlighted())
{
newItem.setInheritsHighlight(true);
newItem.setHighlighted(true);
}
else if(highlightedItems.contains(itemId))
{
newItem.setHighlighted(true);
newItem.setInheritsHighlight(false);
}
try
{
Time createdTime = props.getTimeProperty(ResourceProperties.PROP_CREATION_DATE);
String createdTimeString = createdTime.toStringLocalShortDate();
newItem.setCreatedTime(createdTimeString);
}
catch(Exception e)
{
String createdTimeString = props.getProperty(ResourceProperties.PROP_CREATION_DATE);
newItem.setCreatedTime(createdTimeString);
}
try
{
String createdBy = getUserProperty(props, ResourceProperties.PROP_CREATOR).getDisplayName();
newItem.setCreatedBy(createdBy);
}
catch(Exception e)
{
String createdBy = props.getProperty(ResourceProperties.PROP_CREATOR);
newItem.setCreatedBy(createdBy);
}
try
{
Time modifiedTime = props.getTimeProperty(ResourceProperties.PROP_MODIFIED_DATE);
String modifiedTimeString = modifiedTime.toStringLocalShortDate();
newItem.setModifiedTime(modifiedTimeString);
}
catch(Exception e)
{
String modifiedTimeString = props.getProperty(ResourceProperties.PROP_MODIFIED_DATE);
newItem.setModifiedTime(modifiedTimeString);
}
try
{
String modifiedBy = getUserProperty(props, ResourceProperties.PROP_MODIFIED_BY).getDisplayName();
newItem.setModifiedBy(modifiedBy);
}
catch(Exception e)
{
String modifiedBy = props.getProperty(ResourceProperties.PROP_MODIFIED_BY);
newItem.setModifiedBy(modifiedBy);
}
String size = props.getPropertyFormatted(ResourceProperties.PROP_CONTENT_LENGTH);
newItem.setSize(size);
String target = Validator.getResourceTarget(props.getProperty(ResourceProperties.PROP_CONTENT_TYPE));
newItem.setTarget(target);
String newUrl = contentService.getUrl(itemId);
newItem.setUrl(newUrl);
try
{
boolean copyrightAlert = props.getBooleanProperty(ResourceProperties.PROP_COPYRIGHT_ALERT);
newItem.setCopyrightAlert(copyrightAlert);
}
catch(Exception e)
{}
newItem.setDepth(depth + 1);
if (checkItemFilter((ContentResource)resource, newItem, state))
{
newItems.add(newItem);
}
}
}
}
folder.seDeletableChildren(hasDeletableChildren);
folder.setCopyableChildren(hasCopyableChildren);
// return newItems;
}
catch (IdUnusedException ignore)
{
// this condition indicates a site that does not have a resources collection (mercury?)
}
catch (TypeException e)
{
addAlert(state, "TypeException.");
}
catch (PermissionException e)
{
// ignore -- we'll just skip this collection since user lacks permission to access it.
//addAlert(state, "PermissionException");
}
return newItems;
} // getBrowseItems
protected static boolean checkItemFilter(ContentResource resource, BrowseItem newItem, SessionState state)
{
ContentResourceFilter filter = (ContentResourceFilter)state.getAttribute(STATE_ATTACH_FILTER);
if (filter != null)
{
if (newItem != null)
{
newItem.setCanSelect(filter.allowSelect(resource));
}
return filter.allowView(resource);
}
else if (newItem != null)
{
newItem.setCanSelect(true);
}
return true;
}
protected static boolean checkSelctItemFilter(ContentResource resource, SessionState state)
{
ContentResourceFilter filter = (ContentResourceFilter)state.getAttribute(STATE_ATTACH_FILTER);
if (filter != null)
{
return filter.allowSelect(resource);
}
return true;
}
/**
* set the state name to be "copy" if any item has been selected for copying
*/
public void doCopyitem ( RunData data )
{
// get the state object
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
String itemId = data.getParameters ().getString ("itemId");
if (itemId == null)
{
// there is no resource selected, show the alert message to the user
addAlert(state, rb.getString("choosefile6"));
state.setAttribute (STATE_MODE, MODE_LIST);
}
else
{
try
{
ResourceProperties properties = ContentHostingService.getProperties (itemId);
/*
if (properties.getProperty (ResourceProperties.PROP_IS_COLLECTION).equals (Boolean.TRUE.toString()))
{
String alert = (String) state.getAttribute(STATE_MESSAGE);
if (alert == null || ((alert != null) && (alert.indexOf(RESOURCE_INVALID_OPERATION_ON_COLLECTION_STRING) == -1)))
{
addAlert(state, RESOURCE_INVALID_OPERATION_ON_COLLECTION_STRING);
}
}
*/
}
catch (PermissionException e)
{
addAlert(state, rb.getString("notpermis15"));
}
catch (IdUnusedException e)
{
addAlert(state,RESOURCE_NOT_EXIST_STRING);
} // try-catch
if (state.getAttribute(STATE_MESSAGE) == null)
{
state.setAttribute (STATE_COPY_FLAG, Boolean.TRUE.toString());
state.setAttribute (STATE_COPIED_ID, itemId);
} // if-else
} // if-else
} // doCopyitem
/**
* Paste the previously copied item(s)
*/
public static void doPasteitems ( RunData data)
{
ParameterParser params = data.getParameters ();
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
List items = (List) state.getAttribute(STATE_COPIED_IDS);
String collectionId = params.getString ("collectionId");
Iterator itemIter = items.iterator();
while (itemIter.hasNext())
{
// get the copied item to be pasted
String itemId = (String) itemIter.next();
String originalDisplayName = NULL_STRING;
try
{
String id = ContentHostingService.copyIntoFolder(itemId, collectionId);
String mode = (String) state.getAttribute(STATE_MODE);
if(MODE_HELPER.equals(mode))
{
String helper_mode = (String) state.getAttribute(STATE_RESOURCES_HELPER_MODE);
if(helper_mode != null && MODE_ATTACHMENT_NEW_ITEM.equals(helper_mode))
{
// add to the attachments vector
List attachments = EntityManager.newReferenceList();
Reference ref = EntityManager.newReference(ContentHostingService.getReference(id));
attachments.add(ref);
cleanupState(state);
state.setAttribute(STATE_ATTACHMENTS, attachments);
}
else
{
if(state.getAttribute(STATE_ATTACH_LINKS) == null)
{
attachItem(id, state);
}
else
{
attachLink(id, state);
}
}
}
}
catch (PermissionException e)
{
addAlert(state, rb.getString("notpermis8") + " " + originalDisplayName + ". ");
}
catch (IdUnusedException e)
{
addAlert(state,RESOURCE_NOT_EXIST_STRING);
}
catch (InUseException e)
{
addAlert(state, rb.getString("someone") + " " + originalDisplayName);
}
catch (TypeException e)
{
addAlert(state, rb.getString("pasteitem") + " " + originalDisplayName + " " + rb.getString("mismatch"));
}
catch(IdUsedException e)
{
addAlert(state, rb.getString("toomany"));
}
catch(IdLengthException e)
{
addAlert(state, rb.getString("toolong") + " " + e.getMessage());
}
catch(IdUniquenessException e)
{
addAlert(state, "Could not add this item to this folder");
}
catch(ServerOverloadException e)
{
addAlert(state, rb.getString("failed"));
}
catch(InconsistentException e)
{
addAlert(state, rb.getString("recursive") + " " + itemId);
}
catch (OverQuotaException e)
{
addAlert(state, rb.getString("overquota"));
} // try-catch
catch(RuntimeException e)
{
logger.error("ResourcesAction.doPasteitems ***** Unknown Exception ***** " + e.getMessage());
addAlert(state, rb.getString("failed"));
}
if (state.getAttribute(STATE_MESSAGE) == null)
{
// delete sucessful
String mode = (String) state.getAttribute(STATE_MODE);
if(MODE_HELPER.equals(mode))
{
state.setAttribute(STATE_RESOURCES_HELPER_MODE, MODE_ATTACHMENT_SELECT);
}
else
{
state.setAttribute (STATE_MODE, MODE_LIST);
}
// try to expand the collection
HashMap expandedCollections = (HashMap) state.getAttribute(STATE_EXPANDED_COLLECTIONS);
if(! expandedCollections.containsKey(collectionId))
{
org.sakaiproject.content.api.ContentHostingService contentService = (org.sakaiproject.content.api.ContentHostingService) state.getAttribute (STATE_CONTENT_SERVICE);
try
{
ContentCollection coll = contentService.getCollection(collectionId);
expandedCollections.put(collectionId, coll);
}
catch(Exception ignore){}
}
// reset the copy flag
if (((String)state.getAttribute (STATE_COPY_FLAG)).equals (Boolean.TRUE.toString()))
{
state.setAttribute (STATE_COPY_FLAG, Boolean.FALSE.toString());
}
}
}
} // doPasteitems
/**
* Paste the item(s) selected to be moved
*/
public static void doMoveitems ( RunData data)
{
ParameterParser params = data.getParameters ();
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
// cancel copy if there is one in progress
if(! Boolean.FALSE.toString().equals(state.getAttribute (STATE_COPY_FLAG)))
{
initCopyContext(state);
}
List items = (List) state.getAttribute(STATE_MOVED_IDS);
String collectionId = params.getString ("collectionId");
Iterator itemIter = items.iterator();
while (itemIter.hasNext())
{
// get the copied item to be pasted
String itemId = (String) itemIter.next();
String originalDisplayName = NULL_STRING;
try
{
/*
ResourceProperties properties = ContentHostingService.getProperties (itemId);
originalDisplayName = properties.getPropertyFormatted (ResourceProperties.PROP_DISPLAY_NAME);
// copy, cut and paste not operated on collections
if (properties.getProperty (ResourceProperties.PROP_IS_COLLECTION).equals (Boolean.TRUE.toString()))
{
String alert = (String) state.getAttribute(STATE_MESSAGE);
if (alert == null || ((alert != null) && (alert.indexOf(RESOURCE_INVALID_OPERATION_ON_COLLECTION_STRING) == -1)))
{
addAlert(state, RESOURCE_INVALID_OPERATION_ON_COLLECTION_STRING);
}
}
else
*/
{
ContentHostingService.moveIntoFolder(itemId, collectionId);
} // if-else
}
catch (PermissionException e)
{
addAlert(state, rb.getString("notpermis8") + " " + originalDisplayName + ". ");
}
catch (IdUnusedException e)
{
addAlert(state,RESOURCE_NOT_EXIST_STRING);
}
catch (InUseException e)
{
addAlert(state, rb.getString("someone") + " " + originalDisplayName);
}
catch (TypeException e)
{
addAlert(state, rb.getString("pasteitem") + " " + originalDisplayName + " " + rb.getString("mismatch"));
}
catch (InconsistentException e)
{
addAlert(state, rb.getString("recursive") + " " + itemId);
}
catch(IdUsedException e)
{
addAlert(state, rb.getString("toomany"));
}
catch(ServerOverloadException e)
{
addAlert(state, rb.getString("failed"));
}
catch (OverQuotaException e)
{
addAlert(state, rb.getString("overquota"));
} // try-catch
catch(RuntimeException e)
{
logger.error("ResourcesAction.doMoveitems ***** Unknown Exception ***** " + e.getMessage());
addAlert(state, rb.getString("failed"));
}
if (state.getAttribute(STATE_MESSAGE) == null)
{
// delete sucessful
String mode = (String) state.getAttribute(STATE_MODE);
if(MODE_HELPER.equals(mode))
{
state.setAttribute(STATE_RESOURCES_HELPER_MODE, MODE_ATTACHMENT_SELECT);
}
else
{
state.setAttribute (STATE_MODE, MODE_LIST);
}
// try to expand the collection
HashMap expandedCollections = (HashMap) state.getAttribute(STATE_EXPANDED_COLLECTIONS);
if(! expandedCollections.containsKey(collectionId))
{
org.sakaiproject.content.api.ContentHostingService contentService = (org.sakaiproject.content.api.ContentHostingService) state.getAttribute (STATE_CONTENT_SERVICE);
try
{
ContentCollection coll = contentService.getCollection(collectionId);
expandedCollections.put(collectionId, coll);
}
catch(Exception ignore){}
}
// reset the copy flag
if (((String)state.getAttribute (STATE_MOVE_FLAG)).equals (Boolean.TRUE.toString()))
{
state.setAttribute (STATE_MOVE_FLAG, Boolean.FALSE.toString());
}
}
}
} // doMoveitems
/**
* Paste the previously copied item(s)
*/
public static void doPasteitem ( RunData data)
{
ParameterParser params = data.getParameters ();
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
// get the copied item to be pasted
String itemId = params.getString("itemId");
String collectionId = params.getString ("collectionId");
String originalDisplayName = NULL_STRING;
try
{
ResourceProperties properties = ContentHostingService.getProperties (itemId);
originalDisplayName = properties.getPropertyFormatted (ResourceProperties.PROP_DISPLAY_NAME);
// copy, cut and paste not operated on collections
if (properties.getProperty (ResourceProperties.PROP_IS_COLLECTION).equals (Boolean.TRUE.toString()))
{
String alert = (String) state.getAttribute(STATE_MESSAGE);
if (alert == null || ((alert != null) && (alert.indexOf(RESOURCE_INVALID_OPERATION_ON_COLLECTION_STRING) == -1)))
{
addAlert(state, RESOURCE_INVALID_OPERATION_ON_COLLECTION_STRING);
}
}
else
{
// paste the resource
ContentResource resource = ContentHostingService.getResource (itemId);
ResourceProperties p = ContentHostingService.getProperties(itemId);
String displayName = DUPLICATE_STRING + p.getProperty(ResourceProperties.PROP_DISPLAY_NAME);
String newItemId = ContentHostingService.copyIntoFolder(itemId, collectionId);
ContentResourceEdit copy = ContentHostingService.editResource(newItemId);
ResourcePropertiesEdit pedit = copy.getPropertiesEdit();
pedit.addProperty(ResourceProperties.PROP_DISPLAY_NAME, displayName);
ContentHostingService.commitResource(copy, NotificationService.NOTI_NONE);
} // if-else
}
catch (PermissionException e)
{
addAlert(state, rb.getString("notpermis8") + " " + originalDisplayName + ". ");
}
catch (IdUnusedException e)
{
addAlert(state,RESOURCE_NOT_EXIST_STRING);
}
catch (IdUsedException e)
{
addAlert(state, rb.getString("notaddreso") + " " + originalDisplayName + " " + rb.getString("used2"));
}
catch(IdLengthException e)
{
addAlert(state, rb.getString("toolong") + " " + e.getMessage());
}
catch(IdUniquenessException e)
{
addAlert(state, "Could not add this item to this folder");
}
catch (InconsistentException ee)
{
addAlert(state, RESOURCE_INVALID_TITLE_STRING);
}
catch(InUseException e)
{
addAlert(state, rb.getString("someone") + " " + originalDisplayName + ". ");
}
catch(OverQuotaException e)
{
addAlert(state, rb.getString("overquota"));
}
catch(ServerOverloadException e)
{
// this represents temporary unavailability of server's filesystem
// for server configured to save resource body in filesystem
addAlert(state, rb.getString("failed"));
}
catch (TypeException e)
{
addAlert(state, rb.getString("pasteitem") + " " + originalDisplayName + " " + rb.getString("mismatch"));
} // try-catch
if (state.getAttribute(STATE_MESSAGE) == null)
{
// delete sucessful
String mode = (String) state.getAttribute(STATE_MODE);
if(MODE_HELPER.equals(mode))
{
state.setAttribute(STATE_RESOURCES_HELPER_MODE, MODE_ATTACHMENT_SELECT);
}
else
{
state.setAttribute (STATE_MODE, MODE_LIST);
}
// try to expand the collection
HashMap expandedCollections = (HashMap) state.getAttribute(STATE_EXPANDED_COLLECTIONS);
if(! expandedCollections.containsKey(collectionId))
{
org.sakaiproject.content.api.ContentHostingService contentService = (org.sakaiproject.content.api.ContentHostingService) state.getAttribute (STATE_CONTENT_SERVICE);
try
{
ContentCollection coll = contentService.getCollection(collectionId);
expandedCollections.put(collectionId, coll);
}
catch(Exception ignore){}
}
// reset the copy flag
if (((String)state.getAttribute (STATE_COPY_FLAG)).equals (Boolean.TRUE.toString()))
{
state.setAttribute (STATE_COPY_FLAG, Boolean.FALSE.toString());
}
}
} // doPasteitem
/**
* Fire up the permissions editor for the current folder's permissions
*/
public void doFolder_permissions(RunData data, Context context)
{
SessionState state = ((JetspeedRunData)data).getPortletSessionState(((JetspeedRunData)data).getJs_peid());
ParameterParser params = data.getParameters();
// cancel copy if there is one in progress
if(! Boolean.FALSE.toString().equals(state.getAttribute (STATE_COPY_FLAG)))
{
initCopyContext(state);
}
// cancel move if there is one in progress
if(! Boolean.FALSE.toString().equals(state.getAttribute (STATE_MOVE_FLAG)))
{
initMoveContext(state);
}
// get the current collection id and the related site
String collectionId = params.getString("collectionId"); //(String) state.getAttribute (STATE_COLLECTION_ID);
String title = "";
try
{
title = ContentHostingService.getProperties(collectionId).getProperty(ResourceProperties.PROP_DISPLAY_NAME);
}
catch (PermissionException e)
{
addAlert(state, rb.getString("notread"));
}
catch (IdUnusedException e)
{
addAlert(state, rb.getString("notfindfol"));
}
// the folder to edit
Reference ref = EntityManager.newReference(ContentHostingService.getReference(collectionId));
state.setAttribute(PermissionsHelper.TARGET_REF, ref.getReference());
// use the folder's context (as a site) for roles
String siteRef = SiteService.siteReference(ref.getContext());
state.setAttribute(PermissionsHelper.ROLES_REF, siteRef);
// ... with this description
state.setAttribute(PermissionsHelper.DESCRIPTION, rb.getString("setpermis") + " " + title);
// ... showing only locks that are prpefixed with this
state.setAttribute(PermissionsHelper.PREFIX, "content.");
// get into helper mode with this helper tool
startHelper(data.getRequest(), "sakai.permissions.helper");
} // doFolder_permissions
/**
* Fire up the permissions editor for the tool's permissions
*/
public void doPermissions(RunData data, Context context)
{
SessionState state = ((JetspeedRunData)data).getPortletSessionState(((JetspeedRunData)data).getJs_peid());
// cancel copy if there is one in progress
if(! Boolean.FALSE.toString().equals(state.getAttribute (STATE_COPY_FLAG)))
{
initCopyContext(state);
}
// cancel move if there is one in progress
if(! Boolean.FALSE.toString().equals(state.getAttribute (STATE_MOVE_FLAG)))
{
initMoveContext(state);
}
// should we save here?
state.setAttribute(STATE_LIST_SELECTIONS, new TreeSet());
// get the current home collection id and the related site
String collectionId = (String) state.getAttribute (STATE_HOME_COLLECTION_ID);
Reference ref = EntityManager.newReference(ContentHostingService.getReference(collectionId));
String siteRef = SiteService.siteReference(ref.getContext());
// setup for editing the permissions of the site for this tool, using the roles of this site, too
state.setAttribute(PermissionsHelper.TARGET_REF, siteRef);
// ... with this description
state.setAttribute(PermissionsHelper.DESCRIPTION, rb.getString("setpermis1")
+ SiteService.getSiteDisplay(ref.getContext()));
// ... showing only locks that are prpefixed with this
state.setAttribute(PermissionsHelper.PREFIX, "content.");
// get into helper mode with this helper tool
startHelper(data.getRequest(), "sakai.permissions.helper");
} // doPermissions
/**
* is notification enabled?
*/
protected boolean notificationEnabled(SessionState state)
{
return true;
} // notificationEnabled
/**
* Processes the HTML document that is coming back from the browser
* (from the formatted text editing widget).
* @param state Used to pass in any user-visible alerts or errors when processing the text
* @param strFromBrowser The string from the browser
* @return The formatted text
*/
private String processHtmlDocumentFromBrowser(SessionState state, String strFromBrowser)
{
StringBuffer alertMsg = new StringBuffer();
String text = FormattedText.processHtmlDocument(strFromBrowser, alertMsg);
if (alertMsg.length() > 0) addAlert(state, alertMsg.toString());
return text;
}
/**
*
* Whether a resource item can be replaced
* @param p The ResourceProperties object for the resource item
* @return true If it can be replaced; false otherwise
*/
private static boolean replaceable(ResourceProperties p)
{
boolean rv = true;
if (p.getPropertyFormatted (ResourceProperties.PROP_IS_COLLECTION).equals (Boolean.TRUE.toString()))
{
rv = false;
}
else if (p.getProperty (ResourceProperties.PROP_CONTENT_TYPE).equals (ResourceProperties.TYPE_URL))
{
rv = false;
}
String displayName = p.getPropertyFormatted (ResourceProperties.PROP_DISPLAY_NAME);
if (displayName.indexOf(SHORTCUT_STRING) != -1)
{
rv = false;
}
return rv;
} // replaceable
/**
*
* put copyright info into context
*/
private static void copyrightChoicesIntoContext(SessionState state, Context context)
{
boolean usingCreativeCommons = state.getAttribute(STATE_USING_CREATIVE_COMMONS) != null && state.getAttribute(STATE_USING_CREATIVE_COMMONS).equals(Boolean.TRUE.toString());
if(usingCreativeCommons)
{
String ccOwnershipLabel = "Who created this resource?";
List ccOwnershipList = new Vector();
ccOwnershipList.add("-- Select --");
ccOwnershipList.add("I created this resource");
ccOwnershipList.add("Someone else created this resource");
String ccMyGrantLabel = "Terms of use";
List ccMyGrantOptions = new Vector();
ccMyGrantOptions.add("-- Select --");
ccMyGrantOptions.add("Use my copyright");
ccMyGrantOptions.add("Use Creative Commons License");
ccMyGrantOptions.add("Use Public Domain Dedication");
String ccCommercialLabel = "Allow commercial use?";
List ccCommercialList = new Vector();
ccCommercialList.add("Yes");
ccCommercialList.add("No");
String ccModificationLabel = "Allow Modifications?";
List ccModificationList = new Vector();
ccModificationList.add("Yes");
ccModificationList.add("Yes, share alike");
ccModificationList.add("No");
String ccOtherGrantLabel = "Terms of use";
List ccOtherGrantList = new Vector();
ccOtherGrantList.add("Subject to fair-use exception");
ccOtherGrantList.add("Public domain (created before copyright law applied)");
ccOtherGrantList.add("Public domain (copyright has expired)");
ccOtherGrantList.add("Public domain (government document not subject to copyright)");
String ccRightsYear = "Year";
String ccRightsOwner = "Copyright owner";
String ccAcknowledgeLabel = "Require users to acknowledge author's rights before access?";
List ccAcknowledgeList = new Vector();
ccAcknowledgeList.add("Yes");
ccAcknowledgeList.add("No");
String ccInfoUrl = "";
int year = TimeService.newTime().breakdownLocal().getYear();
String username = UserDirectoryService.getCurrentUser().getDisplayName();
context.put("usingCreativeCommons", Boolean.TRUE);
context.put("ccOwnershipLabel", ccOwnershipLabel);
context.put("ccOwnershipList", ccOwnershipList);
context.put("ccMyGrantLabel", ccMyGrantLabel);
context.put("ccMyGrantOptions", ccMyGrantOptions);
context.put("ccCommercialLabel", ccCommercialLabel);
context.put("ccCommercialList", ccCommercialList);
context.put("ccModificationLabel", ccModificationLabel);
context.put("ccModificationList", ccModificationList);
context.put("ccOtherGrantLabel", ccOtherGrantLabel);
context.put("ccOtherGrantList", ccOtherGrantList);
context.put("ccRightsYear", ccRightsYear);
context.put("ccRightsOwner", ccRightsOwner);
context.put("ccAcknowledgeLabel", ccAcknowledgeLabel);
context.put("ccAcknowledgeList", ccAcknowledgeList);
context.put("ccInfoUrl", ccInfoUrl);
context.put("ccThisYear", Integer.toString(year));
context.put("ccThisUser", username);
}
else
{
//copyright
if (state.getAttribute(COPYRIGHT_FAIRUSE_URL) != null)
{
context.put("fairuseurl", state.getAttribute(COPYRIGHT_FAIRUSE_URL));
}
if (state.getAttribute(NEW_COPYRIGHT_INPUT) != null)
{
context.put("newcopyrightinput", state.getAttribute(NEW_COPYRIGHT_INPUT));
}
if (state.getAttribute(COPYRIGHT_TYPES) != null)
{
List copyrightTypes = (List) state.getAttribute(COPYRIGHT_TYPES);
context.put("copyrightTypes", copyrightTypes);
context.put("copyrightTypesSize", new Integer(copyrightTypes.size() - 1));
context.put("USE_THIS_COPYRIGHT", copyrightTypes.get(copyrightTypes.size() - 1));
}
}
Boolean preventPublicDisplay = (Boolean) state.getAttribute(STATE_PREVENT_PUBLIC_DISPLAY);
if(preventPublicDisplay == null)
{
preventPublicDisplay = Boolean.FALSE;
state.setAttribute(STATE_PREVENT_PUBLIC_DISPLAY, preventPublicDisplay);
}
context.put("preventPublicDisplay", preventPublicDisplay);
} // copyrightChoicesIntoContext
/**
* Add variables and constants to the velocity context to render an editor
* for inputing and modifying optional metadata properties about a resource.
*/
private static void metadataGroupsIntoContext(SessionState state, Context context)
{
context.put("STRING", ResourcesMetadata.WIDGET_STRING);
context.put("TEXTAREA", ResourcesMetadata.WIDGET_TEXTAREA);
context.put("BOOLEAN", ResourcesMetadata.WIDGET_BOOLEAN);
context.put("INTEGER", ResourcesMetadata.WIDGET_INTEGER);
context.put("DOUBLE", ResourcesMetadata.WIDGET_DOUBLE);
context.put("DATE", ResourcesMetadata.WIDGET_DATE);
context.put("TIME", ResourcesMetadata.WIDGET_TIME);
context.put("DATETIME", ResourcesMetadata.WIDGET_DATETIME);
context.put("ANYURI", ResourcesMetadata.WIDGET_ANYURI);
context.put("WYSIWYG", ResourcesMetadata.WIDGET_WYSIWYG);
context.put("today", TimeService.newTime());
List metadataGroups = (List) state.getAttribute(STATE_METADATA_GROUPS);
if(metadataGroups != null && !metadataGroups.isEmpty())
{
context.put("metadataGroups", metadataGroups);
}
} // metadataGroupsIntoContext
/**
* initialize the metadata context
*/
private static void initMetadataContext(SessionState state)
{
// define MetadataSets map
List metadataGroups = (List) state.getAttribute(STATE_METADATA_GROUPS);
if(metadataGroups == null)
{
metadataGroups = new Vector();
state.setAttribute(STATE_METADATA_GROUPS, metadataGroups);
}
// define DublinCore
if( !metadataGroups.contains(new MetadataGroup(rb.getString("opt_props"))) )
{
MetadataGroup dc = new MetadataGroup( rb.getString("opt_props") );
// dc.add(ResourcesMetadata.PROPERTY_DC_TITLE);
// dc.add(ResourcesMetadata.PROPERTY_DC_DESCRIPTION);
dc.add(ResourcesMetadata.PROPERTY_DC_ALTERNATIVE);
dc.add(ResourcesMetadata.PROPERTY_DC_CREATOR);
dc.add(ResourcesMetadata.PROPERTY_DC_PUBLISHER);
dc.add(ResourcesMetadata.PROPERTY_DC_SUBJECT);
dc.add(ResourcesMetadata.PROPERTY_DC_CREATED);
dc.add(ResourcesMetadata.PROPERTY_DC_ISSUED);
// dc.add(ResourcesMetadata.PROPERTY_DC_MODIFIED);
// dc.add(ResourcesMetadata.PROPERTY_DC_TABLEOFCONTENTS);
dc.add(ResourcesMetadata.PROPERTY_DC_ABSTRACT);
dc.add(ResourcesMetadata.PROPERTY_DC_CONTRIBUTOR);
// dc.add(ResourcesMetadata.PROPERTY_DC_TYPE);
// dc.add(ResourcesMetadata.PROPERTY_DC_FORMAT);
// dc.add(ResourcesMetadata.PROPERTY_DC_IDENTIFIER);
// dc.add(ResourcesMetadata.PROPERTY_DC_SOURCE);
// dc.add(ResourcesMetadata.PROPERTY_DC_LANGUAGE);
// dc.add(ResourcesMetadata.PROPERTY_DC_COVERAGE);
// dc.add(ResourcesMetadata.PROPERTY_DC_RIGHTS);
dc.add(ResourcesMetadata.PROPERTY_DC_AUDIENCE);
dc.add(ResourcesMetadata.PROPERTY_DC_EDULEVEL);
metadataGroups.add(dc);
state.setAttribute(STATE_METADATA_GROUPS, metadataGroups);
}
/*
// define DublinCore
if(!metadataGroups.contains(new MetadataGroup("Test of Datatypes")))
{
MetadataGroup dc = new MetadataGroup("Test of Datatypes");
dc.add(ResourcesMetadata.PROPERTY_DC_TITLE);
dc.add(ResourcesMetadata.PROPERTY_DC_DESCRIPTION);
dc.add(ResourcesMetadata.PROPERTY_DC_ANYURI);
dc.add(ResourcesMetadata.PROPERTY_DC_DOUBLE);
dc.add(ResourcesMetadata.PROPERTY_DC_DATETIME);
dc.add(ResourcesMetadata.PROPERTY_DC_TIME);
dc.add(ResourcesMetadata.PROPERTY_DC_DATE);
dc.add(ResourcesMetadata.PROPERTY_DC_BOOLEAN);
dc.add(ResourcesMetadata.PROPERTY_DC_INTEGER);
metadataGroups.add(dc);
state.setAttribute(STATE_METADATA_GROUPS, metadataGroups);
}
*/
}
/**
* Internal class that encapsulates all information about a resource that is needed in the browse mode
*/
public static class BrowseItem
{
protected static Integer seqnum = new Integer(0);
private String m_itemnum;
// attributes of all resources
protected String m_name;
protected String m_id;
protected String m_type;
protected boolean m_canRead;
protected boolean m_canRevise;
protected boolean m_canDelete;
protected boolean m_canCopy;
protected boolean m_isCopied;
protected boolean m_canAddItem;
protected boolean m_canAddFolder;
protected boolean m_canSelect;
protected List m_members;
protected boolean m_isEmpty;
protected boolean m_isHighlighted;
protected boolean m_inheritsHighlight;
protected String m_createdBy;
protected String m_createdTime;
protected String m_modifiedBy;
protected String m_modifiedTime;
protected String m_size;
protected String m_target;
protected String m_container;
protected String m_root;
protected int m_depth;
protected boolean m_hasDeletableChildren;
protected boolean m_hasCopyableChildren;
protected boolean m_copyrightAlert;
protected String m_url;
protected boolean m_isLocal;
protected boolean m_isAttached;
private boolean m_isMoved;
private boolean m_canUpdate;
private boolean m_toobig;
protected String m_access;
protected String m_inheritedAccess;
protected List m_groups;
protected List m_inheritedGroups;
protected BasicRightsAssignment m_rights;
/**
* @param id
* @param name
* @param type
*/
public BrowseItem(String id, String name, String type)
{
m_name = name;
m_id = id;
m_type = type;
Integer snum;
synchronized(seqnum)
{
snum = seqnum;
seqnum = new Integer((seqnum.intValue() + 1) % 10000);
}
m_itemnum = "Item00000000".substring(0,10 - snum.toString().length()) + snum.toString();
// set defaults
m_rights = new BasicRightsAssignment(m_itemnum, false);
m_members = new LinkedList();
m_canRead = false;
m_canRevise = false;
m_canDelete = false;
m_canCopy = false;
m_isEmpty = true;
m_toobig = false;
m_isCopied = false;
m_isMoved = false;
m_isAttached = false;
m_canSelect = true; // default is true.
m_hasDeletableChildren = false;
m_hasCopyableChildren = false;
m_createdBy = "";
m_modifiedBy = "";
// m_createdTime = TimeService.newTime().toStringLocalDate();
// m_modifiedTime = TimeService.newTime().toStringLocalDate();
m_size = "";
m_depth = 0;
m_copyrightAlert = false;
m_url = "";
m_target = "";
m_root = "";
m_isHighlighted = false;
m_inheritsHighlight = false;
m_canAddItem = false;
m_canAddFolder = false;
m_canUpdate = false;
m_access = AccessMode.INHERITED.toString();
m_groups = new Vector();
}
public String getItemNum()
{
return m_itemnum;
}
public void setIsTooBig(boolean toobig)
{
m_toobig = toobig;
}
public boolean isTooBig()
{
return m_toobig;
}
/**
* @param name
*/
public void setName(String name)
{
m_name = name;
}
/**
* @param root
*/
public void setRoot(String root)
{
m_root = root;
}
/**
* @return
*/
public String getRoot()
{
return m_root;
}
/**
* @return
*/
public List getMembers()
{
List rv = new LinkedList();
if(m_members != null)
{
rv.addAll(m_members);
}
return rv;
}
/**
* @param members
*/
public void addMembers(Collection members)
{
if(m_members == null)
{
m_members = new LinkedList();
}
m_members.addAll(members);
}
/**
* @return
*/
public boolean canAddItem()
{
return m_canAddItem;
}
/**
* @return
*/
public boolean canDelete()
{
return m_canDelete;
}
/**
* @return
*/
public boolean canRead()
{
return m_canRead;
}
public boolean canSelect() {
return m_canSelect;
}
/**
* @return
*/
public boolean canRevise()
{
return m_canRevise;
}
/**
* @return
*/
public String getId()
{
return m_id;
}
/**
* @return
*/
public String getName()
{
return m_name;
}
/**
* @return
*/
public int getDepth()
{
return m_depth;
}
/**
* @param depth
*/
public void setDepth(int depth)
{
m_depth = depth;
}
/**
* @param canCreate
*/
public void setCanAddItem(boolean canAddItem)
{
m_canAddItem = canAddItem;
}
/**
* @param canDelete
*/
public void setCanDelete(boolean canDelete)
{
m_canDelete = canDelete;
}
/**
* @param canRead
*/
public void setCanRead(boolean canRead)
{
m_canRead = canRead;
}
public void setCanSelect(boolean canSelect) {
m_canSelect = canSelect;
}
/**
* @param canRevise
*/
public void setCanRevise(boolean canRevise)
{
m_canRevise = canRevise;
}
/**
* @return
*/
public boolean isFolder()
{
return TYPE_FOLDER.equals(m_type);
}
/**
* @return
*/
public String getType()
{
return m_type;
}
/**
* @return
*/
public boolean canAddFolder()
{
return m_canAddFolder;
}
/**
* @param b
*/
public void setCanAddFolder(boolean canAddFolder)
{
m_canAddFolder = canAddFolder;
}
/**
* @return
*/
public boolean canCopy()
{
return m_canCopy;
}
/**
* @param canCopy
*/
public void setCanCopy(boolean canCopy)
{
m_canCopy = canCopy;
}
/**
* @return
*/
public boolean hasCopyrightAlert()
{
return m_copyrightAlert;
}
/**
* @param copyrightAlert
*/
public void setCopyrightAlert(boolean copyrightAlert)
{
m_copyrightAlert = copyrightAlert;
}
/**
* @return
*/
public String getUrl()
{
return m_url;
}
/**
* @param url
*/
public void setUrl(String url)
{
m_url = url;
}
/**
* @return
*/
public boolean isCopied()
{
return m_isCopied;
}
/**
* @param isCopied
*/
public void setCopied(boolean isCopied)
{
m_isCopied = isCopied;
}
/**
* @return
*/
public boolean isMoved()
{
return m_isMoved;
}
/**
* @param isCopied
*/
public void setMoved(boolean isMoved)
{
m_isMoved = isMoved;
}
/**
* @return
*/
public String getCreatedBy()
{
return m_createdBy;
}
/**
* @return
*/
public String getCreatedTime()
{
return m_createdTime;
}
/**
* @return
*/
public String getModifiedBy()
{
return m_modifiedBy;
}
/**
* @return
*/
public String getModifiedTime()
{
return m_modifiedTime;
}
/**
* @return
*/
public String getSize()
{
if(m_size == null)
{
m_size = "";
}
return m_size;
}
/**
* @param creator
*/
public void setCreatedBy(String creator)
{
m_createdBy = creator;
}
/**
* @param time
*/
public void setCreatedTime(String time)
{
m_createdTime = time;
}
/**
* @param modifier
*/
public void setModifiedBy(String modifier)
{
m_modifiedBy = modifier;
}
/**
* @param time
*/
public void setModifiedTime(String time)
{
m_modifiedTime = time;
}
/**
* @param size
*/
public void setSize(String size)
{
m_size = size;
}
/**
* @return
*/
public String getTarget()
{
return m_target;
}
/**
* @param target
*/
public void setTarget(String target)
{
m_target = target;
}
/**
* @return
*/
public boolean isEmpty()
{
return m_isEmpty;
}
/**
* @param isEmpty
*/
public void setIsEmpty(boolean isEmpty)
{
m_isEmpty = isEmpty;
}
/**
* @return
*/
public String getContainer()
{
return m_container;
}
/**
* @param container
*/
public void setContainer(String container)
{
m_container = container;
}
public void setIsLocal(boolean isLocal)
{
m_isLocal = isLocal;
}
public boolean isLocal()
{
return m_isLocal;
}
/**
* @return Returns the isAttached.
*/
public boolean isAttached()
{
return m_isAttached;
}
/**
* @param isAttached The isAttached to set.
*/
public void setAttached(boolean isAttached)
{
this.m_isAttached = isAttached;
}
/**
* @return Returns the hasCopyableChildren.
*/
public boolean hasCopyableChildren()
{
return m_hasCopyableChildren;
}
/**
* @param hasCopyableChildren The hasCopyableChildren to set.
*/
public void setCopyableChildren(boolean hasCopyableChildren)
{
this.m_hasCopyableChildren = hasCopyableChildren;
}
/**
* @return Returns the hasDeletableChildren.
*/
public boolean hasDeletableChildren()
{
return m_hasDeletableChildren;
}
/**
* @param hasDeletableChildren The hasDeletableChildren to set.
*/
public void seDeletableChildren(boolean hasDeletableChildren)
{
this.m_hasDeletableChildren = hasDeletableChildren;
}
/**
* @return Returns the canUpdate.
*/
public boolean canUpdate()
{
return m_canUpdate;
}
/**
* @param canUpdate The canUpdate to set.
*/
public void setCanUpdate(boolean canUpdate)
{
m_canUpdate = canUpdate;
}
public void setHighlighted(boolean isHighlighted)
{
m_isHighlighted = isHighlighted;
}
public boolean isHighlighted()
{
return m_isHighlighted;
}
public void setInheritsHighlight(boolean inheritsHighlight)
{
m_inheritsHighlight = inheritsHighlight;
}
public boolean inheritsHighlighted()
{
return m_inheritsHighlight;
}
/**
* Access the access mode for this item.
* @return The access mode.
*/
public String getAccess()
{
return m_access;
}
/**
* Access the access mode for this item.
* @return The access mode.
*/
public String getInheritedAccess()
{
return m_inheritedAccess;
}
public String getEntityAccess()
{
String rv = AccessMode.INHERITED.toString();
boolean sameGroups = true;
if(AccessMode.GROUPED.toString().equals(m_access))
{
Iterator it = getGroups().iterator();
while(sameGroups && it.hasNext())
{
Group g = (Group) it.next();
sameGroups = inheritsGroup(g.getReference());
}
it = getInheritedGroups().iterator();
while(sameGroups && it.hasNext())
{
Group g = (Group) it.next();
sameGroups = hasGroup(g.getReference());
}
if(!sameGroups)
{
rv = AccessMode.GROUPED.toString();
}
}
return rv;
}
/**
* Set the access mode for this item.
* @param access
*/
public void setAccess(String access)
{
m_access = access;
}
/**
* Set the access mode for this item.
* @param access
*/
public void setInheritedAccess(String access)
{
m_inheritedAccess = access;
}
/**
* Access a list of Group objects that can access this item.
* @return Returns the groups.
*/
public List getGroups()
{
if(m_groups == null)
{
m_groups = new Vector();
}
return m_groups;
}
/**
* Access a list of Group objects that can access this item.
* @return Returns the groups.
*/
public List getInheritedGroups()
{
if(m_inheritedGroups == null)
{
m_inheritedGroups = new Vector();
}
return m_inheritedGroups;
}
/**
* Determine whether a group has access to this item.
* @param groupRef The internal reference string that uniquely identifies the group.
* @return true if the group has access, false otherwise.
*/
public boolean hasGroup(String groupRef)
{
if(m_groups == null)
{
m_groups = new Vector();
}
boolean found = false;
Iterator it = m_groups.iterator();
while(it.hasNext() && !found)
{
Group gr = (Group) it.next();
found = gr.getReference().equals(groupRef);
}
return found;
}
/**
* Determine whether a group has access to this item.
* @param groupRef The internal reference string that uniquely identifies the group.
* @return true if the group has access, false otherwise.
*/
public boolean inheritsGroup(String groupRef)
{
if(m_inheritedGroups == null)
{
m_inheritedGroups = new Vector();
}
boolean found = false;
Iterator it = m_inheritedGroups.iterator();
while(it.hasNext() && !found)
{
Group gr = (Group) it.next();
found = gr.getReference().equals(groupRef);
}
return found;
}
/**
* Replace the current list of groups with this list of Group objects representing the groups that have access to this item.
* @param groups The groups to set.
*/
public void setGroups(Collection groups)
{
if(groups == null)
{
return;
}
if(m_groups == null)
{
m_groups = new Vector();
}
m_groups.clear();
Iterator it = groups.iterator();
while(it.hasNext())
{
Object obj = it.next();
if(obj instanceof Group)
{
m_groups.add(obj);
}
else if(obj instanceof String)
{
addGroup((String) obj);
}
}
}
/**
* Replace the current list of groups with this list of Group objects representing the groups that have access to this item.
* @param groups The groups to set.
*/
public void setInheritedGroups(Collection groups)
{
if(groups == null)
{
return;
}
if(m_inheritedGroups == null)
{
m_inheritedGroups = new Vector();
}
m_inheritedGroups.clear();
Iterator it = groups.iterator();
while(it.hasNext())
{
Object obj = it.next();
if(obj instanceof Group)
{
m_inheritedGroups.add(obj);
}
else if(obj instanceof String)
{
addInheritedGroup((String) obj);
}
}
}
/**
* Add a string reference identifying a Group to the list of groups that have access to this item.
* @param groupRef
*/
public void addGroup(String groupId)
{
if(m_groups == null)
{
m_groups = new Vector();
}
if(m_container == null)
{
if(m_id == null)
{
m_container = ContentHostingService.getSiteCollection(ToolManager.getCurrentPlacement().getContext());
}
else
{
m_container = ContentHostingService.getContainingCollectionId(m_id);
}
if(m_container == null || m_container.trim() == "")
{
m_container = ContentHostingService.getSiteCollection(ToolManager.getCurrentPlacement().getContext());
}
}
boolean found = false;
Collection groups = ContentHostingService.getGroupsWithReadAccess(m_container);
Iterator it = groups.iterator();
while( it.hasNext() && !found )
{
Group group = (Group) it.next();
if(group.getId().equals(groupId))
{
if(! hasGroup(group.getReference()))
{
m_groups.add(group);
}
found = true;
}
}
}
/**
* Add a string reference identifying a Group to the list of groups that have access to this item.
* @param groupRef
*/
public void addInheritedGroup(String groupId)
{
if(m_inheritedGroups == null)
{
m_inheritedGroups = new Vector();
}
if(m_container == null)
{
if(m_id == null)
{
m_container = ContentHostingService.getSiteCollection(ToolManager.getCurrentPlacement().getContext());
}
else
{
m_container = ContentHostingService.getContainingCollectionId(m_id);
}
if(m_container == null || m_container.trim() == "")
{
m_container = ContentHostingService.getSiteCollection(ToolManager.getCurrentPlacement().getContext());
}
}
boolean found = false;
Collection groups = ContentHostingService.getGroupsWithReadAccess(m_container);
Iterator it = groups.iterator();
while( it.hasNext() && !found )
{
Group group = (Group) it.next();
if(group.getId().equals(groupId))
{
if(! hasGroup(group.getReference()))
{
m_inheritedGroups.add(group);
}
found = true;
}
}
}
/**
* Remove all groups from the item.
*/
public void clearGroups()
{
if(this.m_groups == null)
{
m_groups = new Vector();
}
m_groups.clear();
}
/**
* Remove all inherited groups from the item.
*/
public void clearInheritedGroups()
{
if(m_inheritedGroups == null)
{
m_inheritedGroups = new Vector();
}
m_inheritedGroups.clear();
}
/**
* @return Returns the rights.
*/
public BasicRightsAssignment getRights()
{
return m_rights;
}
/**
* @param rights The rights to set.
*/
public void setRights(BasicRightsAssignment rights)
{
this.m_rights = rights;
}
} // inner class BrowseItem
/**
* Inner class encapsulates information about resources (folders and items) for editing
*/
public static class EditItem
extends BrowseItem
{
protected String m_copyrightStatus;
protected String m_copyrightInfo;
// protected boolean m_copyrightAlert;
protected boolean m_pubview;
protected boolean m_pubviewset;
protected String m_filename;
protected byte[] m_content;
protected String m_encoding;
protected String m_mimetype;
protected String m_description;
protected Map m_metadata;
protected boolean m_hasQuota;
protected boolean m_canSetQuota;
protected String m_quota;
protected boolean m_isUrl;
protected boolean m_contentHasChanged;
protected boolean m_contentTypeHasChanged;
protected int m_notification = NotificationService.NOTI_NONE;
protected String m_formtype;
protected String m_rootname;
protected Map m_structuredArtifact;
protected List m_properties;
protected Set m_metadataGroupsShowing;
protected Set m_missingInformation;
protected boolean m_hasBeenAdded;
protected ResourcesMetadata m_form;
protected boolean m_isBlank;
protected String m_instruction;
protected String m_ccRightsownership;
protected String m_ccLicense;
protected String m_ccCommercial;
protected String m_ccModification;
protected String m_ccRightsOwner;
protected String m_ccRightsYear;
/**
* @param id
* @param name
* @param type
*/
public EditItem(String id, String name, String type)
{
super(id, name, type);
m_filename = "";
m_contentHasChanged = false;
m_contentTypeHasChanged = false;
m_metadata = new Hashtable();
m_structuredArtifact = new Hashtable();
m_metadataGroupsShowing = new HashSet();
m_mimetype = type;
m_content = null;
m_encoding = "UTF-8";
m_notification = NotificationService.NOTI_NONE;
m_hasQuota = false;
m_canSetQuota = false;
m_formtype = "";
m_rootname = "";
m_missingInformation = new HashSet();
m_hasBeenAdded = false;
m_properties = new Vector();
m_isBlank = true;
m_instruction = "";
m_pubview = false;
m_pubviewset = false;
m_ccRightsownership = "";
m_ccLicense = "";
// m_copyrightStatus = ServerConfigurationService.getString("default.copyright");
}
public void setRightsowner(String ccRightsOwner)
{
m_ccRightsOwner = ccRightsOwner;
}
public String getRightsowner()
{
return m_ccRightsOwner;
}
public void setRightstyear(String ccRightsYear)
{
m_ccRightsYear = ccRightsYear;
}
public String getRightsyear()
{
return m_ccRightsYear;
}
public void setAllowModifications(String ccModification)
{
m_ccModification = ccModification;
}
public String getAllowModifications()
{
return m_ccModification;
}
public void setAllowCommercial(String ccCommercial)
{
m_ccCommercial = ccCommercial;
}
public String getAllowCommercial()
{
return m_ccCommercial;
}
/**
*
* @param license
*/
public void setLicense(String license)
{
m_ccLicense = license;
}
/**
*
* @return
*/
public String getLicense()
{
return m_ccLicense;
}
/**
* Record a value for instructions to be displayed to the user in the editor (for Form Items).
* @param instruction The value of the instructions.
*/
public void setInstruction(String instruction)
{
if(instruction == null)
{
instruction = "";
}
m_instruction = instruction.trim();
}
/**
* Access instructions to be displayed to the user in the editor (for Form Items).
* @return The instructions.
*/
public String getInstruction()
{
return m_instruction;
}
/**
* Set the character encoding type that will be used when converting content body between strings and byte arrays.
* Default is "UTF-8".
* @param encoding A valid name for a character set encoding scheme (@see java.lang.Charset)
*/
public void setEncoding(String encoding)
{
m_encoding = encoding;
}
/**
* Get the character encoding type that is used when converting content body between strings and byte arrays.
* Default is "UTF-8".
* @return The name of the character set encoding scheme (@see java.lang.Charset)
*/
public String getEncoding()
{
return m_encoding;
}
/**
* Set marker indicating whether current item is a blank entry
* @param isBlank
*/
public void markAsBlank(boolean isBlank)
{
m_isBlank = isBlank;
}
/**
* Access marker indicating whether current item is a blank entry
* @return true if current entry is blank, false otherwise
*/
public boolean isBlank()
{
return m_isBlank;
}
/**
* Change the root ResourcesMetadata object that defines the form for a Structured Artifact.
* @param form
*/
public void setForm(ResourcesMetadata form)
{
m_form = form;
}
/**
* Access the root ResourcesMetadata object that defines the form for a Structured Artifact.
* @return the form.
*/
public ResourcesMetadata getForm()
{
return m_form;
}
/**
* @param properties
*/
public void setProperties(List properties)
{
m_properties = properties;
}
public List getProperties()
{
return m_properties;
}
/**
* Replace current values of Structured Artifact with new values.
* @param map The new values.
*/
public void setValues(Map map)
{
m_structuredArtifact = map;
}
/**
* Access the entire set of values stored in the Structured Artifact
* @return The set of values.
*/
public Map getValues()
{
return m_structuredArtifact;
}
/**
* @param id
* @param name
* @param type
*/
public EditItem(String type)
{
this(null, "", type);
}
/**
* @param id
*/
public void setId(String id)
{
m_id = id;
}
/**
* Show the indicated metadata group for the item
* @param group
*/
public void showMetadataGroup(String group)
{
m_metadataGroupsShowing.add(group);
}
/**
* Hide the indicated metadata group for the item
* @param group
*/
public void hideMetadataGroup(String group)
{
m_metadataGroupsShowing.remove(group);
m_metadataGroupsShowing.remove(Validator.escapeUrl(group));
}
/**
* Query whether the indicated metadata group is showing for the item
* @param group
* @return true if the metadata group is showing, false otherwise
*/
public boolean isGroupShowing(String group)
{
return m_metadataGroupsShowing.contains(group) || m_metadataGroupsShowing.contains(Validator.escapeUrl(group));
}
/**
* @return
*/
public boolean isFileUpload()
{
return !isFolder() && !isUrl() && !isHtml() && !isPlaintext() && !isStructuredArtifact();
}
/**
* @param type
*/
public void setType(String type)
{
m_type = type;
}
/**
* @param mimetype
*/
public void setMimeType(String mimetype)
{
m_mimetype = mimetype;
}
public String getRightsownership()
{
return m_ccRightsownership;
}
public void setRightsownership(String owner)
{
m_ccRightsownership = owner;
}
/**
* @return
*/
public String getMimeType()
{
return m_mimetype;
}
public String getMimeCategory()
{
if(this.m_mimetype == null || this.m_mimetype.equals(""))
{
return "";
}
int index = this.m_mimetype.indexOf("/");
if(index < 0)
{
return this.m_mimetype;
}
return this.m_mimetype.substring(0, index);
}
public String getMimeSubtype()
{
if(this.m_mimetype == null || this.m_mimetype.equals(""))
{
return "";
}
int index = this.m_mimetype.indexOf("/");
if(index < 0 || index + 1 == this.m_mimetype.length())
{
return "";
}
return this.m_mimetype.substring(index + 1);
}
/**
* @param formtype
*/
public void setFormtype(String formtype)
{
m_formtype = formtype;
}
/**
* @return
*/
public String getFormtype()
{
return m_formtype;
}
/**
* @return Returns the copyrightInfo.
*/
public String getCopyrightInfo() {
return m_copyrightInfo;
}
/**
* @param copyrightInfo The copyrightInfo to set.
*/
public void setCopyrightInfo(String copyrightInfo) {
m_copyrightInfo = copyrightInfo;
}
/**
* @return Returns the copyrightStatus.
*/
public String getCopyrightStatus() {
return m_copyrightStatus;
}
/**
* @param copyrightStatus The copyrightStatus to set.
*/
public void setCopyrightStatus(String copyrightStatus) {
m_copyrightStatus = copyrightStatus;
}
/**
* @return Returns the description.
*/
public String getDescription() {
return m_description;
}
/**
* @param description The description to set.
*/
public void setDescription(String description) {
m_description = description;
}
/**
* @return Returns the filename.
*/
public String getFilename() {
return m_filename;
}
/**
* @param filename The filename to set.
*/
public void setFilename(String filename) {
m_filename = filename;
}
/**
* @return Returns the metadata.
*/
public Map getMetadata() {
return m_metadata;
}
/**
* @param metadata The metadata to set.
*/
public void setMetadata(Map metadata) {
m_metadata = metadata;
}
/**
* @param name
* @param value
*/
public void setMetadataItem(String name, Object value)
{
m_metadata.put(name, value);
}
/**
* @return Returns the pubview.
*/
public boolean isPubview() {
return m_pubview;
}
/**
* @param pubview The pubview to set.
*/
public void setPubview(boolean pubview) {
m_pubview = pubview;
}
/**
* @return Returns the pubviewset.
*/
public boolean isPubviewset() {
return m_pubviewset;
}
/**
* @param pubviewset The pubviewset to set.
*/
public void setPubviewset(boolean pubviewset) {
m_pubviewset = pubviewset;
}
/**
* @return Returns the content.
*/
public byte[] getContent() {
return m_content;
}
/**
* @return Returns the content as a String.
*/
public String getContentstring()
{
String rv = "";
if(m_content != null && m_content.length > 0)
{
try
{
rv = new String( m_content, m_encoding );
}
catch(UnsupportedEncodingException e)
{
rv = new String( m_content );
}
}
return rv;
}
/**
* @param content The content to set.
*/
public void setContent(byte[] content) {
m_content = content;
}
/**
* @param content The content to set.
*/
public void setContent(String content) {
try
{
m_content = content.getBytes(m_encoding);
}
catch(UnsupportedEncodingException e)
{
m_content = content.getBytes();
}
}
/**
* @return Returns the canSetQuota.
*/
public boolean canSetQuota() {
return m_canSetQuota;
}
/**
* @param canSetQuota The canSetQuota to set.
*/
public void setCanSetQuota(boolean canSetQuota) {
m_canSetQuota = canSetQuota;
}
/**
* @return Returns the hasQuota.
*/
public boolean hasQuota() {
return m_hasQuota;
}
/**
* @param hasQuota The hasQuota to set.
*/
public void setHasQuota(boolean hasQuota) {
m_hasQuota = hasQuota;
}
/**
* @return Returns the quota.
*/
public String getQuota() {
return m_quota;
}
/**
* @param quota The quota to set.
*/
public void setQuota(String quota) {
m_quota = quota;
}
/**
* @return true if content-type of item indicates it represents a URL, false otherwise
*/
public boolean isUrl()
{
return TYPE_URL.equals(m_type) || ResourceProperties.TYPE_URL.equals(m_mimetype);
}
/**
* @return true if content-type of item indicates it represents a URL, false otherwise
*/
public boolean isStructuredArtifact()
{
return TYPE_FORM.equals(m_type);
}
/**
* @return true if content-type of item is "text/text" (plain text), false otherwise
*/
public boolean isPlaintext()
{
return MIME_TYPE_DOCUMENT_PLAINTEXT.equals(m_mimetype) || MIME_TYPE_DOCUMENT_PLAINTEXT.equals(m_type);
}
/**
* @return true if content-type of item is "text/html" (an html document), false otherwise
*/
public boolean isHtml()
{
return MIME_TYPE_DOCUMENT_HTML.equals(m_mimetype) || MIME_TYPE_DOCUMENT_HTML.equals(m_type);
}
public boolean contentHasChanged()
{
return m_contentHasChanged;
}
public void setContentHasChanged(boolean changed)
{
m_contentHasChanged = changed;
}
public boolean contentTypeHasChanged()
{
return m_contentTypeHasChanged;
}
public void setContentTypeHasChanged(boolean changed)
{
m_contentTypeHasChanged = changed;
}
public void setNotification(int notification)
{
m_notification = notification;
}
public int getNotification()
{
return m_notification;
}
/**
* @return Returns the artifact.
*/
public Map getStructuredArtifact()
{
return m_structuredArtifact;
}
/**
* @param artifact The artifact to set.
*/
public void setStructuredArtifact(Map artifact)
{
this.m_structuredArtifact = artifact;
}
/**
* @param name
* @param value
*/
public void setValue(String name, Object value)
{
setValue(name, 0, value);
}
/**
* @param name
* @param index
* @param value
*/
public void setValue(String name, int index, Object value)
{
List list = getList(name);
try
{
list.set(index, value);
}
catch(ArrayIndexOutOfBoundsException e)
{
list.add(value);
}
m_structuredArtifact.put(name, list);
}
/**
* Access a value of a structured artifact field of type String.
* @param name The name of the field to access.
* @return the value, or null if the named field is null or not a String.
*/
public String getString(String name)
{
if(m_structuredArtifact == null)
{
m_structuredArtifact = new Hashtable();
}
Object value = m_structuredArtifact.get(name);
String rv = "";
if(value == null)
{
// do nothing
}
else if(value instanceof String)
{
rv = (String) value;
}
else
{
rv = value.toString();
}
return rv;
}
public Object getValue(String name, int index)
{
List list = getList(name);
Object rv = null;
try
{
rv = list.get(index);
}
catch(ArrayIndexOutOfBoundsException e)
{
// return null
}
return rv;
}
public Object getPropertyValue(String name)
{
return getPropertyValue(name, 0);
}
/**
* Access a particular value in a Structured Artifact, as identified by the parameter "name". This
* implementation of the method assumes that the name is a series of String identifiers delimited
* by the ResourcesAction.ResourcesMetadata.DOT String.
* @param name The delimited identifier for the item.
* @return The value identified by the name, or null if the name does not identify a valid item.
*/
public Object getPropertyValue(String name, int index)
{
String[] names = name.split(ResourcesMetadata.DOT);
Object rv = null;
if(m_properties == null)
{
m_properties = new Vector();
}
Iterator it = m_properties.iterator();
while(rv == null && it.hasNext())
{
ResourcesMetadata prop = (ResourcesMetadata) it.next();
if(name.equals(prop.getDottedname()))
{
rv = prop.getValue(index);
}
}
return rv;
}
public void setPropertyValue(String name, Object value)
{
setPropertyValue(name, 0, value);
}
/**
* Access a particular value in a Structured Artifact, as identified by the parameter "name". This
* implementation of the method assumes that the name is a series of String identifiers delimited
* by the ResourcesAction.ResourcesMetadata.DOT String.
* @param name The delimited identifier for the item.
* @return The value identified by the name, or null if the name does not identify a valid item.
*/
public void setPropertyValue(String name, int index, Object value)
{
if(m_properties == null)
{
m_properties = new Vector();
}
boolean found = false;
Iterator it = m_properties.iterator();
while(!found && it.hasNext())
{
ResourcesMetadata prop = (ResourcesMetadata) it.next();
if(name.equals(prop.getDottedname()))
{
found = true;
prop.setValue(index, value);
}
}
}
/**
* Access a particular value in a Structured Artifact, as identified by the parameter "name". This
* implementation of the method assumes that the name is a series of String identifiers delimited
* by the ResourcesAction.ResourcesMetadata.DOT String.
* @param name The delimited identifier for the item.
* @return The value identified by the name, or null if the name does not identify a valid item.
*/
public Object getValue(String name)
{
String[] names = name.split(ResourcesMetadata.DOT);
Object rv = m_structuredArtifact;
if(rv != null && (rv instanceof Map) && ((Map) rv).isEmpty())
{
rv = null;
}
for(int i = 1; rv != null && i < names.length; i++)
{
if(rv instanceof Map)
{
rv = ((Map) rv).get(names[i]);
}
else
{
rv = null;
}
}
return rv;
}
/**
* Access a list of values associated with a named property of a structured artifact.
* @param name The name of the property.
* @return The list of values associated with that name, or an empty list if the property is not defined.
*/
public List getList(String name)
{
if(m_structuredArtifact == null)
{
m_structuredArtifact = new Hashtable();
}
Object value = m_structuredArtifact.get(name);
List rv = new Vector();
if(value == null)
{
m_structuredArtifact.put(name, rv);
}
else if(value instanceof Collection)
{
rv.addAll((Collection)value);
}
else
{
rv.add(value);
}
return rv;
}
/**
* @return
*/
/*
public Element exportStructuredArtifact(List properties)
{
return null;
}
*/
/**
* @return Returns the name of the root of a structured artifact definition.
*/
public String getRootname()
{
return m_rootname;
}
/**
* @param rootname The name to be assigned for the root of a structured artifact.
*/
public void setRootname(String rootname)
{
m_rootname = rootname;
}
/**
* Add a property name to the list of properties missing from the input.
* @param propname The name of the property.
*/
public void setMissing(String propname)
{
m_missingInformation.add(propname);
}
/**
* Query whether a particular property is missing
* @param propname The name of the property
* @return The value "true" if the property is missing, "false" otherwise.
*/
public boolean isMissing(String propname)
{
return m_missingInformation.contains(propname) || m_missingInformation.contains(Validator.escapeUrl(propname));
}
/**
* Empty the list of missing properties.
*/
public void clearMissing()
{
m_missingInformation.clear();
}
public void setAdded(boolean added)
{
m_hasBeenAdded = added;
}
public boolean hasBeenAdded()
{
return m_hasBeenAdded;
}
} // inner class EditItem
/**
* Inner class encapsulates information about folders (and final item?) in a collection path (a.k.a. breadcrumb)
*/
public static class PathItem
{
protected String m_url;
protected String m_name;
protected String m_id;
protected boolean m_canRead;
protected boolean m_isFolder;
protected boolean m_isLast;
protected String m_root;
protected boolean m_isLocal;
public PathItem(String id, String name)
{
m_id = id;
m_name = name;
m_canRead = false;
m_isFolder = false;
m_isLast = false;
m_url = "";
m_isLocal = true;
}
/**
* @return
*/
public boolean canRead()
{
return m_canRead;
}
/**
* @return
*/
public String getId()
{
return m_id;
}
/**
* @return
*/
public boolean isFolder()
{
return m_isFolder;
}
/**
* @return
*/
public boolean isLast()
{
return m_isLast;
}
/**
* @return
*/
public String getName()
{
return m_name;
}
/**
* @param canRead
*/
public void setCanRead(boolean canRead)
{
m_canRead = canRead;
}
/**
* @param id
*/
public void setId(String id)
{
m_id = id;
}
/**
* @param isFolder
*/
public void setIsFolder(boolean isFolder)
{
m_isFolder = isFolder;
}
/**
* @param isLast
*/
public void setLast(boolean isLast)
{
m_isLast = isLast;
}
/**
* @param name
*/
public void setName(String name)
{
m_name = name;
}
/**
* @return
*/
public String getUrl()
{
return m_url;
}
/**
* @param url
*/
public void setUrl(String url)
{
m_url = url;
}
/**
* @param root
*/
public void setRoot(String root)
{
m_root = root;
}
/**
* @return
*/
public String getRoot()
{
return m_root;
}
public void setIsLocal(boolean isLocal)
{
m_isLocal = isLocal;
}
public boolean isLocal()
{
return m_isLocal;
}
} // inner class PathItem
/**
*
* inner class encapsulates information about groups of metadata tags (such as DC, LOM, etc.)
*
*/
public static class MetadataGroup
extends Vector
{
/**
*
*/
private static final long serialVersionUID = -821054142728929236L;
protected String m_name;
protected boolean m_isShowing;
/**
* @param name
*/
public MetadataGroup(String name)
{
super();
m_name = name;
m_isShowing = false;
}
/**
* @return
*/
public boolean isShowing()
{
return m_isShowing;
}
/**
* @param isShowing
*/
public void setShowing(boolean isShowing)
{
m_isShowing = isShowing;
}
/**
* @return
*/
public String getName()
{
return m_name;
}
/**
* @param name
*/
public void setName(String name)
{
m_name = name;
}
/* (non-Javadoc)
* @see java.lang.Object#equals(java.lang.Object)
* needed to determine List.contains()
*/
public boolean equals(Object obj)
{
MetadataGroup mg = (MetadataGroup) obj;
boolean rv = (obj != null) && (m_name.equals(mg));
return rv;
}
}
public static class AttachItem
{
protected String m_id;
protected String m_displayName;
protected String m_accessUrl;
protected String m_collectionId;
protected String m_contentType;
/**
* @param id
* @param displayName
* @param collectionId
* @param accessUrl
*/
public AttachItem(String id, String displayName, String collectionId, String accessUrl)
{
m_id = id;
m_displayName = displayName;
m_collectionId = collectionId;
m_accessUrl = accessUrl;
}
/**
* @return Returns the accessUrl.
*/
public String getAccessUrl()
{
return m_accessUrl;
}
/**
* @param accessUrl The accessUrl to set.
*/
public void setAccessUrl(String accessUrl)
{
m_accessUrl = accessUrl;
}
/**
* @return Returns the collectionId.
*/
public String getCollectionId()
{
return m_collectionId;
}
/**
* @param collectionId The collectionId to set.
*/
public void setCollectionId(String collectionId)
{
m_collectionId = collectionId;
}
/**
* @return Returns the id.
*/
public String getId()
{
return m_id;
}
/**
* @param id The id to set.
*/
public void setId(String id)
{
m_id = id;
}
/**
* @return Returns the name.
*/
public String getDisplayName()
{
String displayName = m_displayName;
if(displayName == null || displayName.trim().equals(""))
{
displayName = isolateName(m_id);
}
return displayName;
}
/**
* @param name The name to set.
*/
public void setDisplayName(String name)
{
m_displayName = name;
}
/**
* @return Returns the contentType.
*/
public String getContentType()
{
return m_contentType;
}
/**
* @param contentType
*/
public void setContentType(String contentType)
{
this.m_contentType = contentType;
}
} // Inner class AttachItem
public static class ElementCarrier
{
protected Element element;
protected String parent;
public ElementCarrier(Element element, String parent)
{
this.element = element;
this.parent = parent;
}
public Element getElement()
{
return element;
}
public void setElement(Element element)
{
this.element = element;
}
public String getParent()
{
return parent;
}
public void setParent(String parent)
{
this.parent = parent;
}
}
public static class SaveArtifactAttempt
{
protected EditItem item;
protected List errors;
protected SchemaNode schema;
public SaveArtifactAttempt(EditItem item, SchemaNode schema)
{
this.item = item;
this.schema = schema;
}
/**
* @return Returns the errors.
*/
public List getErrors()
{
return errors;
}
/**
* @param errors The errors to set.
*/
public void setErrors(List errors)
{
this.errors = errors;
}
/**
* @return Returns the item.
*/
public EditItem getItem()
{
return item;
}
/**
* @param item The item to set.
*/
public void setItem(EditItem item)
{
this.item = item;
}
/**
* @return Returns the schema.
*/
public SchemaNode getSchema()
{
return schema;
}
/**
* @param schema The schema to set.
*/
public void setSchema(SchemaNode schema)
{
this.schema = schema;
}
}
/**
* Develop a list of all the site collections that there are to page.
* Sort them as appropriate, and apply search criteria.
*/
protected static List readAllResources(SessionState state)
{
List other_sites = new Vector();
String collectionId = (String) state.getAttribute (STATE_ATTACH_COLLECTION_ID);
if(collectionId == null)
{
collectionId = (String) state.getAttribute (STATE_COLLECTION_ID);
}
HashMap expandedCollections = (HashMap) state.getAttribute(STATE_EXPANDED_COLLECTIONS);
// set the sort values
String sortedBy = (String) state.getAttribute (STATE_SORT_BY);
String sortedAsc = (String) state.getAttribute (STATE_SORT_ASC);
Boolean showRemove = (Boolean) state.getAttribute(STATE_SHOW_REMOVE_ACTION);
boolean showRemoveAction = showRemove != null && showRemove.booleanValue();
Boolean showMove = (Boolean) state.getAttribute(STATE_SHOW_MOVE_ACTION);
boolean showMoveAction = showMove != null && showMove.booleanValue();
Boolean showCopy = (Boolean) state.getAttribute(STATE_SHOW_COPY_ACTION);
boolean showCopyAction = showCopy != null && showCopy.booleanValue();
Set highlightedItems = (Set) state.getAttribute(STATE_HIGHLIGHTED_ITEMS);
// add user's personal workspace
User user = UserDirectoryService.getCurrentUser();
String userId = user.getId();
String userName = user.getDisplayName();
String wsId = SiteService.getUserSiteId(userId);
String wsCollectionId = ContentHostingService.getSiteCollection(wsId);
if(! collectionId.equals(wsCollectionId))
{
List members = getBrowseItems(wsCollectionId, expandedCollections, highlightedItems, sortedBy, sortedAsc, (BrowseItem) null, false, state);
if(members != null && members.size() > 0)
{
BrowseItem root = (BrowseItem) members.remove(0);
showRemoveAction = showRemoveAction || root.hasDeletableChildren();
showMoveAction = showMoveAction || root.hasDeletableChildren();
showCopyAction = showCopyAction || root.hasCopyableChildren();
root.addMembers(members);
root.setName(userName + " " + rb.getString("gen.wsreso"));
other_sites.add(root);
}
}
// add all other sites user has access to
/*
* NOTE: This does not (and should not) get all sites for admin.
* Getting all sites for admin is too big a request and
* would result in too big a display to render in html.
*/
Map othersites = ContentHostingService.getCollectionMap();
Iterator siteIt = othersites.keySet().iterator();
SortedSet sort = new TreeSet();
while(siteIt.hasNext())
{
String collId = (String) siteIt.next();
String displayName = (String) othersites.get(collId);
sort.add(displayName + DELIM + collId);
}
Iterator sortIt = sort.iterator();
while(sortIt.hasNext())
{
String item = (String) sortIt.next();
String displayName = item.substring(0, item.lastIndexOf(DELIM));
String collId = item.substring(item.lastIndexOf(DELIM) + 1);
if(! collectionId.equals(collId) && ! wsCollectionId.equals(collId))
{
List members = getBrowseItems(collId, expandedCollections, highlightedItems, sortedBy, sortedAsc, (BrowseItem) null, false, state);
if(members != null && members.size() > 0)
{
BrowseItem root = (BrowseItem) members.remove(0);
root.addMembers(members);
root.setName(displayName);
other_sites.add(root);
}
}
}
return other_sites;
}
/**
* Prepare the current page of site collections to display.
* @return List of BrowseItem objects to display on this page.
*/
protected static List prepPage(SessionState state)
{
List rv = new Vector();
// access the page size
int pageSize = ((Integer) state.getAttribute(STATE_PAGESIZE)).intValue();
// cleanup prior prep
state.removeAttribute(STATE_NUM_MESSAGES);
// are we going next or prev, first or last page?
boolean goNextPage = state.getAttribute(STATE_GO_NEXT_PAGE) != null;
boolean goPrevPage = state.getAttribute(STATE_GO_PREV_PAGE) != null;
boolean goFirstPage = state.getAttribute(STATE_GO_FIRST_PAGE) != null;
boolean goLastPage = state.getAttribute(STATE_GO_LAST_PAGE) != null;
state.removeAttribute(STATE_GO_NEXT_PAGE);
state.removeAttribute(STATE_GO_PREV_PAGE);
state.removeAttribute(STATE_GO_FIRST_PAGE);
state.removeAttribute(STATE_GO_LAST_PAGE);
// are we going next or prev message?
boolean goNext = state.getAttribute(STATE_GO_NEXT) != null;
boolean goPrev = state.getAttribute(STATE_GO_PREV) != null;
state.removeAttribute(STATE_GO_NEXT);
state.removeAttribute(STATE_GO_PREV);
// read all channel messages
List allMessages = readAllResources(state);
if (allMessages == null)
{
return rv;
}
String messageIdAtTheTopOfThePage = null;
Object topMsgId = state.getAttribute(STATE_TOP_PAGE_MESSAGE);
if(topMsgId == null)
{
// do nothing
}
else if(topMsgId instanceof Integer)
{
messageIdAtTheTopOfThePage = ((Integer) topMsgId).toString();
}
else if(topMsgId instanceof String)
{
messageIdAtTheTopOfThePage = (String) topMsgId;
}
// if we have no prev page and do have a top message, then we will stay "pinned" to the top
boolean pinToTop = ( (messageIdAtTheTopOfThePage != null)
&& (state.getAttribute(STATE_PREV_PAGE_EXISTS) == null)
&& !goNextPage && !goPrevPage && !goNext && !goPrev && !goFirstPage && !goLastPage);
// if we have no next page and do have a top message, then we will stay "pinned" to the bottom
boolean pinToBottom = ( (messageIdAtTheTopOfThePage != null)
&& (state.getAttribute(STATE_NEXT_PAGE_EXISTS) == null)
&& !goNextPage && !goPrevPage && !goNext && !goPrev && !goFirstPage && !goLastPage);
// how many messages, total
int numMessages = allMessages.size();
if (numMessages == 0)
{
return rv;
}
// save the number of messges
state.setAttribute(STATE_NUM_MESSAGES, new Integer(numMessages));
// find the position of the message that is the top first on the page
int posStart = 0;
if (messageIdAtTheTopOfThePage != null)
{
// find the next page
posStart = findResourceInList(allMessages, messageIdAtTheTopOfThePage);
// if missing, start at the top
if (posStart == -1)
{
posStart = 0;
}
}
// if going to the next page, adjust
if (goNextPage)
{
posStart += pageSize;
}
// if going to the prev page, adjust
else if (goPrevPage)
{
posStart -= pageSize;
if (posStart < 0) posStart = 0;
}
// if going to the first page, adjust
else if (goFirstPage)
{
posStart = 0;
}
// if going to the last page, adjust
else if (goLastPage)
{
posStart = numMessages - pageSize;
if (posStart < 0) posStart = 0;
}
// pinning
if (pinToTop)
{
posStart = 0;
}
else if (pinToBottom)
{
posStart = numMessages - pageSize;
if (posStart < 0) posStart = 0;
}
// get the last page fully displayed
if (posStart + pageSize > numMessages)
{
posStart = numMessages - pageSize;
if (posStart < 0) posStart = 0;
}
// compute the end to a page size, adjusted for the number of messages available
int posEnd = posStart + (pageSize-1);
if (posEnd >= numMessages) posEnd = numMessages-1;
int numMessagesOnThisPage = (posEnd - posStart) + 1;
// select the messages on this page
for (int i = posStart; i <= posEnd; i++)
{
rv.add(allMessages.get(i));
}
// save which message is at the top of the page
BrowseItem itemAtTheTopOfThePage = (BrowseItem) allMessages.get(posStart);
state.setAttribute(STATE_TOP_PAGE_MESSAGE, itemAtTheTopOfThePage.getId());
state.setAttribute(STATE_TOP_MESSAGE_INDEX, new Integer(posStart));
// which message starts the next page (if any)
int next = posStart + pageSize;
if (next < numMessages)
{
state.setAttribute(STATE_NEXT_PAGE_EXISTS, "");
}
else
{
state.removeAttribute(STATE_NEXT_PAGE_EXISTS);
}
// which message ends the prior page (if any)
int prev = posStart - 1;
if (prev >= 0)
{
state.setAttribute(STATE_PREV_PAGE_EXISTS, "");
}
else
{
state.removeAttribute(STATE_PREV_PAGE_EXISTS);
}
if (state.getAttribute(STATE_VIEW_ID) != null)
{
int viewPos = findResourceInList(allMessages, (String) state.getAttribute(STATE_VIEW_ID));
// are we moving to the next message
if (goNext)
{
// advance
viewPos++;
if (viewPos >= numMessages) viewPos = numMessages-1;
}
// are we moving to the prev message
if (goPrev)
{
// retreat
viewPos--;
if (viewPos < 0) viewPos = 0;
}
// update the view message
state.setAttribute(STATE_VIEW_ID, ((BrowseItem) allMessages.get(viewPos)).getId());
// if the view message is no longer on the current page, adjust the page
// Note: next time through this will get processed
if (viewPos < posStart)
{
state.setAttribute(STATE_GO_PREV_PAGE, "");
}
else if (viewPos > posEnd)
{
state.setAttribute(STATE_GO_NEXT_PAGE, "");
}
if (viewPos > 0)
{
state.setAttribute(STATE_PREV_EXISTS,"");
}
else
{
state.removeAttribute(STATE_PREV_EXISTS);
}
if (viewPos < numMessages-1)
{
state.setAttribute(STATE_NEXT_EXISTS,"");
}
else
{
state.removeAttribute(STATE_NEXT_EXISTS);
}
}
return rv;
} // prepPage
/**
* Find the resource with this id in the list.
* @param messages The list of messages.
* @param id The message id.
* @return The index position in the list of the message with this id, or -1 if not found.
*/
protected static int findResourceInList(List resources, String id)
{
for (int i = 0; i < resources.size(); i++)
{
// if this is the one, return this index
if (((BrowseItem) (resources.get(i))).getId().equals(id)) return i;
}
// not found
return -1;
} // findResourceInList
protected static User getUserProperty(ResourceProperties props, String name)
{
String id = props.getProperty(name);
if (id != null)
{
try
{
return UserDirectoryService.getUser(id);
}
catch (UserNotDefinedException e)
{
}
}
return null;
}
/**
* Find the resource name of a given resource id or filepath.
*
* @param id
* The resource id.
* @return the resource name.
*/
protected static String isolateName(String id)
{
if (id == null) return null;
if (id.length() == 0) return null;
// take after the last resource path separator, not counting one at the very end if there
boolean lastIsSeparator = id.charAt(id.length() - 1) == '/';
return id.substring(id.lastIndexOf('/', id.length() - 2) + 1, (lastIsSeparator ? id.length() - 1 : id.length()));
} // isolateName
} // ResourcesAction
|
diff --git a/srcj/com/sun/electric/tool/user/ui/WindowFrame.java b/srcj/com/sun/electric/tool/user/ui/WindowFrame.java
index 1f845576b..2effec4da 100755
--- a/srcj/com/sun/electric/tool/user/ui/WindowFrame.java
+++ b/srcj/com/sun/electric/tool/user/ui/WindowFrame.java
@@ -1,789 +1,793 @@
/* -*- tab-width: 4 -*-
*
* Electric(tm) VLSI Design System
*
* File: WindowFrame.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 2 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.ui;
import java.awt.Dimension;
import java.awt.GraphicsConfiguration;
import java.awt.Rectangle;
import java.awt.Cursor;
import java.awt.event.*;
import java.lang.ref.WeakReference;
import java.lang.reflect.Constructor;
import java.util.ArrayList;
import java.util.EventListener;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import javax.swing.*;
import javax.swing.event.InternalFrameAdapter;
import javax.swing.event.InternalFrameEvent;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreePath;
import com.sun.electric.database.hierarchy.Cell;
import com.sun.electric.database.hierarchy.Library;
import com.sun.electric.tool.Job;
import com.sun.electric.tool.io.input.Simulate;
import com.sun.electric.tool.simulation.Simulation;
import com.sun.electric.tool.user.ErrorLogger;
import com.sun.electric.tool.user.Resources;
import com.sun.electric.tool.user.menus.FileMenu;
import com.sun.electric.database.variable.VarContext;
/**
* This class defines an edit window, with a cell explorer on the left side.
*/
public class WindowFrame
{
/** the nature of the main window part (from above) */ private WindowContent content;
/** the text edit window part */ private JTextArea textWnd;
// /** the text edit window component. */ private JScrollPane textPanel;
/** the split pane that shows explorer and edit. */ private JSplitPane js;
/** the internal frame (if MDI). */ private JInternalFrame jif = null;
/** the top-level frame (if SDI). */ private TopLevel jf = null;
/** the internalframe listener */ private InternalWindowsEvents internalWindowsEvents;
/** the window event listener */ private WindowsEvents windowsEvents;
/** the tree view part */ public ExplorerTree tree;
/** the explorer part of a frame. */ public DefaultMutableTreeNode rootNode;
/** the library explorer part. */ public DefaultMutableTreeNode libraryExplorerNode;
/** the job explorer part. */ public DefaultMutableTreeNode jobExplorerNode;
/** the error explorer part. */ public DefaultMutableTreeNode errorExplorerNode;
/** the signal explorer part. */ public DefaultMutableTreeNode signalExplorerNode;
/** the explorer part of a frame. */ private DefaultTreeModel treeModel;
/** the offset of each new windows from the last */ private static int windowOffset = 0;
/** the list of all windows on the screen */ private static List windowList = new ArrayList();
/** the current windows. */ private static WindowFrame curWindowFrame = null;
/** current mouse listener */ public static MouseListener curMouseListener = ClickZoomWireListener.theOne;
/** current mouse motion listener */ public static MouseMotionListener curMouseMotionListener = ClickZoomWireListener.theOne;
/** current mouse wheel listener */ public static MouseWheelListener curMouseWheelListener = ClickZoomWireListener.theOne;
/** current key listener */ public static KeyListener curKeyListener = ClickZoomWireListener.theOne;
//******************************** CONSTRUCTION ********************************
// constructor
private WindowFrame()
{
}
/**
* Method to create a new circuit-editing window on the screen that displays a Cell.
* @param cell the cell to display.
* @return the WindowFrame that shows the Cell.
*/
public static WindowFrame createEditWindow(Cell cell)
{
WindowFrame frame = new WindowFrame();
if (cell != null && cell.getView().isTextView())
{
TextWindow tWnd = new TextWindow(cell, frame);
frame.buildWindowStructure(tWnd, cell, null);
setCurrentWindowFrame(frame);
frame.populateJFrame();
tWnd.fillScreen();
} else
{
EditWindow eWnd = EditWindow.CreateElectricDoc(cell, frame);
frame.buildWindowStructure(eWnd, cell, null);
setCurrentWindowFrame(frame);
frame.populateJFrame();
eWnd.fillScreen();
}
removeUIBinding(frame.js, KeyStroke.getKeyStroke(KeyEvent.VK_F6, 0));
removeUIBinding(frame.js, KeyStroke.getKeyStroke(KeyEvent.VK_F8, 0));
return frame;
}
/**
* Method to create a new 3D view window on the screen for the given cell
* @param cell the cell to display.
* @return the WindowFrame that shows the Cell.
*/
public static WindowFrame create3DViewtWindow(Cell cell)
{
WindowFrame frame = new WindowFrame();
/*
WindowContent vWnd = new View3DWindow(cell, frame);
frame.buildWindowStructure((WindowContent)vWnd, cell, null);
setCurrentWindowFrame(frame);
frame.populateJFrame();
*/
Class view3DClass;
try
{
view3DClass = Class.forName("com.sun.electric.plugins.j3d.View3DWindow");
} catch (ClassNotFoundException e)
{
System.out.println("Can't find 3D View plugin: " + e.getMessage());
return frame;
+ } catch (Error e)
+ {
+ System.out.println("Java3D not installed: " + e.getMessage());
+ return frame;
}
Constructor constructor = null;
try
{
constructor = view3DClass.getDeclaredConstructor(new Class[] {Cell.class, WindowFrame.class}) ;
Object vWnd = constructor.newInstance(new Object[] {cell, frame});
frame.buildWindowStructure((WindowContent)vWnd, cell, null);
setCurrentWindowFrame(frame);
frame.populateJFrame();
} catch (Exception e) {
System.out.println("Can't open 3D View window: " + e.getMessage());
e.printStackTrace();
}
return frame;
}
/**
* Method to create a new waveform window on the screen given the simulation data.
* @param sd the simulation data to use in the waveform window.
* @return the WindowFrame that shows the waveforms.
*/
public static WindowFrame createWaveformWindow(Simulation.SimData sd)
{
WindowFrame frame = new WindowFrame();
WaveformWindow wWnd = new WaveformWindow(sd, frame);
frame.buildWindowStructure(wWnd, sd.getCell(), null);
setCurrentWindowFrame(frame);
frame.populateJFrame();
wWnd.fillScreen();
return frame;
}
private void buildWindowStructure(WindowContent content, Cell cell, GraphicsConfiguration gc)
{
this.content = content;
// the left half: an explorer tree in a scroll pane
rootNode = new DefaultMutableTreeNode("Explorer");
content.loadExplorerTree(rootNode);
treeModel = new DefaultTreeModel(rootNode);
tree = ExplorerTree.CreateExplorerTree(rootNode, treeModel);
wantToRedoLibraryTree();
JScrollPane scrolledTree = new JScrollPane(tree);
// put them together into the split pane
js = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT);
js.setRightComponent(content.getPanel());
js.setLeftComponent(scrolledTree);
js.setDividerLocation(0.2);
// initialize the frame
String cellDescription = (cell == null) ? "no cell" : cell.describe();
createJFrame(cellDescription, gc);
windowOffset += 70;
if (windowOffset > 300) windowOffset = 0;
// Put everything into the frame
// js.requestFocusInWindow();
// accumulate a list of current windows
synchronized(windowList) {
windowList.add(this);
}
}
/**
* Create the JFrame that will hold all the Components in
* this WindowFrame.
*/
private void createJFrame(String title, GraphicsConfiguration gc)
{
Dimension scrnSize = TopLevel.getScreenSize();
Dimension frameSize = new Dimension(scrnSize.width * 4 / 5, scrnSize.height * 6 / 8);
if (TopLevel.isMDIMode())
{
jif = new JInternalFrame(title, true, true, true, true);
jif.setSize(frameSize);
jif.setLocation(windowOffset+150, windowOffset);
jif.setAutoscrolls(true);
jif.setFrameIcon(Resources.getResource(WindowFrame.class, "IconElectric.gif"));
} else
{
jf = new TopLevel("Electric - " + title, new Rectangle(frameSize), this, gc);
jf.setSize(frameSize);
jf.setLocation(windowOffset+150, windowOffset);
}
}
/**
* Populate the JFrame with the Components
*/
private void populateJFrame()
{
if (TopLevel.isMDIMode())
{
jif.getContentPane().add(js);
internalWindowsEvents = new InternalWindowsEvents(this);
jif.addInternalFrameListener(internalWindowsEvents);
jif.show();
TopLevel.addToDesktop(jif);
// add tool bar as listener so it can find out state of cell history in EditWindow
jif.addInternalFrameListener(TopLevel.getCurrentJFrame().getToolBar());
//content.getPanel().addPropertyChangeListener(TopLevel.getTopLevel().getToolBar());
content.getPanel().addPropertyChangeListener(EditWindow.propGoBackEnabled, TopLevel.getCurrentJFrame().getToolBar());
content.getPanel().addPropertyChangeListener(EditWindow.propGoForwardEnabled, TopLevel.getCurrentJFrame().getToolBar());
// frame.jif.moveToFront();
try
{
jif.setSelected(true);
} catch (java.beans.PropertyVetoException e) {}
} else
{
jf.getContentPane().add(js);
windowsEvents = new WindowsEvents(this);
jf.addWindowListener(windowsEvents);
jf.addWindowFocusListener(windowsEvents);
jf.setWindowFrame(this);
// add tool bar as listener so it can find out state of cell history in EditWindow
content.getPanel().addPropertyChangeListener(EditWindow.propGoBackEnabled, ((TopLevel)jf).getToolBar());
content.getPanel().addPropertyChangeListener(EditWindow.propGoForwardEnabled, ((TopLevel)jf).getToolBar());
jf.show();
}
}
/**
* Depopulate the JFrame. Currently this is only used in SDI mode when
* moving a WindowFrame from one display to another. A new JFrame on the
* new display must be created and populated with the WindowFrame Components.
* To do so, those components must first be removed from the old frame.
*/
private void depopulateJFrame()
{
if (TopLevel.isMDIMode()) {
jif.getContentPane().remove(js);
jif.removeInternalFrameListener(internalWindowsEvents);
jif.removeInternalFrameListener(TopLevel.getCurrentJFrame().getToolBar());
// TopLevel.removeFromDesktop(jif);
content.getPanel().removePropertyChangeListener(TopLevel.getCurrentJFrame().getToolBar());
} else {
jf.getContentPane().remove(js);
jf.removeWindowListener(windowsEvents);
jf.removeWindowFocusListener(windowsEvents);
jf.setWindowFrame(null);
content.getPanel().removePropertyChangeListener(EditWindow.propGoBackEnabled, ((TopLevel)jf).getToolBar());
content.getPanel().removePropertyChangeListener(EditWindow.propGoForwardEnabled, ((TopLevel)jf).getToolBar());
}
}
//******************************** WINDOW CONTROL ********************************
/**
* Method to show a cell in the right-part of this WindowFrame.
* Handles both circuit cells and text cells.
* @param cell the Cell to display.
*/
public void setCellWindow(Cell cell)
{
if (cell != null && cell.getView().isTextView())
{
// want a TextWindow here
if (!(getContent() instanceof TextWindow))
{
getContent().finished();
content = new TextWindow(cell, this);
int i = js.getDividerLocation();
js.setRightComponent(content.getPanel());
js.setDividerLocation(i);
content.fillScreen();
return;
}
} else
{
// want an EditWindow here
if (!(getContent() instanceof EditWindow))
{
getContent().finished();
content = EditWindow.CreateElectricDoc(cell, this);
int i = js.getDividerLocation();
js.setRightComponent(content.getPanel());
js.setDividerLocation(i);
content.fillScreen();
return;
}
}
content.setCell(cell, VarContext.globalContext);
}
public void moveEditWindow(GraphicsConfiguration gc) {
if (TopLevel.isMDIMode()) return; // only valid in SDI mode
jf.hide(); // hide old Frame
//jf.getFocusOwner().setFocusable(false);
//System.out.println("Set unfocasable: "+jf.getFocusOwner());
depopulateJFrame(); // remove all components from old Frame
TopLevel oldFrame = jf;
oldFrame.finished(); // clear and garbage collect old Frame
Cell cell = content.getCell(); // get current cell
String cellDescription = (cell == null) ? "no cell" : cell.describe(); // new title
createJFrame(cellDescription, gc); // create new Frame
populateJFrame(); // populate new Frame
content.fireCellHistoryStatus(); // update tool bar history buttons
}
//******************************** EXPLORER PART ********************************
private boolean wantToRedoLibraryTree = false;
private boolean wantToRedoJobTree = false;
private boolean wantToRedoErrorTree = false;
private boolean wantToRedoSignalTree = false;
public static void wantToRedoLibraryTree()
{
for(Iterator it = WindowFrame.getWindows(); it.hasNext(); )
{
WindowFrame wf = (WindowFrame)it.next();
wf.wantToRedoLibraryTree = true;
wf.getContent().repaint();
}
}
public static void wantToRedoJobTree()
{
for(Iterator it = WindowFrame.getWindows(); it.hasNext(); )
{
WindowFrame wf = (WindowFrame)it.next();
wf.wantToRedoJobTree = true;
wf.getContent().repaint();
}
}
public static void wantToRedoErrorTree()
{
for(Iterator it = WindowFrame.getWindows(); it.hasNext(); )
{
WindowFrame wf = (WindowFrame)it.next();
wf.wantToRedoErrorTree = true;
wf.getContent().repaint();
}
}
public void wantToRedoSignalTree()
{
wantToRedoSignalTree = true;
content.loadExplorerTree(rootNode);
redoExplorerTreeIfRequested();
}
public void redoExplorerTreeIfRequested()
{
if (!wantToRedoLibraryTree && !wantToRedoJobTree && !wantToRedoErrorTree && !wantToRedoSignalTree) return;
// remember the state of the tree
HashMap expanded = new HashMap();
recursivelyCache(expanded, new TreePath(rootNode), true);
// get the new library tree part
if (wantToRedoLibraryTree)
libraryExplorerNode = ExplorerTree.makeLibraryTree();
if (wantToRedoJobTree)
jobExplorerNode = Job.getExplorerTree();
if (wantToRedoErrorTree)
errorExplorerNode = ErrorLogger.getExplorerTree();
wantToRedoLibraryTree = wantToRedoJobTree = wantToRedoErrorTree = wantToRedoSignalTree = false;
// rebuild the tree
rootNode.removeAllChildren();
if (libraryExplorerNode != null) rootNode.add(libraryExplorerNode);
if (signalExplorerNode != null) rootNode.add(signalExplorerNode);
rootNode.add(jobExplorerNode);
rootNode.add(errorExplorerNode);
tree.treeDidChange();
treeModel.reload();
recursivelyCache(expanded, new TreePath(rootNode), false);
}
private void recursivelyCache(HashMap expanded, TreePath path, boolean cache)
{
DefaultMutableTreeNode node = (DefaultMutableTreeNode)path.getLastPathComponent();
Object obj = node.getUserObject();
int numChildren = node.getChildCount();
if (numChildren == 0) return;
if (cache)
{
if (tree.isExpanded(path)) expanded.put(obj, obj);
} else
{
if (expanded.get(obj) != null) tree.expandPath(path);
}
// now recurse
for(int i=0; i<numChildren; i++)
{
DefaultMutableTreeNode child = (DefaultMutableTreeNode)node.getChildAt(i);
TreePath descentPath = path.pathByAddingChild(child);
if (descentPath == null) continue;
recursivelyCache(expanded, descentPath, cache);
}
}
//******************************** INTERFACE ********************************
/**
* Method to set the content of this window.
* The content is the object in the right side (EditWindow, WaveformWindow, etc.)
* @param content the new content object.
*/
// public void setContent(WindowContent content)
// {
// this.content = content;
//
// rootNode.removeAllChildren();
// content.loadExplorerTree(rootNode);
// js.setRightComponent(content.getPanel());
// }
/**
* Method to get the content of this window.
* The content is the object in the right side (EditWindow, WaveformWindow, etc.)
* @return the content of this window.
*/
public WindowContent getContent() { return content; }
/**
* Method to get the current WindowFrame.
* @return the current WindowFrame.
*/
public static WindowFrame getCurrentWindowFrame() { synchronized(windowList) { return curWindowFrame; } }
/**
* Method to set the current listener that responds to clicks in any window.
* There is a single listener in effect everywhere, usually controlled by the toolbar.
* @param listener the new lister to be in effect.
*/
public static void setListener(EventListener listener)
{
curMouseListener = (MouseListener)listener;
curMouseMotionListener = (MouseMotionListener)listener;
curMouseWheelListener = (MouseWheelListener)listener;
curKeyListener = (KeyListener)listener;
}
/**
* Method to get the current listener that responds to clicks in any window.
* There is a single listener in effect everywhere, usually controlled by the toolbar.
* @return the current listener.
*/
public static EventListener getListener() { return curMouseListener; }
/**
* Method to return the current Cell.
*/
public static Cell getCurrentCell()
{
WindowFrame wf = WindowFrame.getCurrentWindowFrame();
if (wf == null) return null;
return wf.getContent().getCell();
}
/**
* Method to insist on a current Cell.
* Prints an error message if there is no current Cell.
* @return the current Cell in the current Library.
* Returns NULL if there is no current Cell.
*/
public static Cell needCurCell()
{
Cell curCell = getCurrentCell();
if (curCell == null)
{
System.out.println("There is no current cell for this operation");
}
return curCell;
}
/**
* Method to set the cursor that is displayed in the WindowFrame.
* @param cursor the cursor to display here.
*/
public void setCursor(Cursor cursor)
{
content.getPanel().setCursor(cursor);
}
public static void removeLibraryReferences(Library lib)
{
for (Iterator it = getWindows(); it.hasNext(); )
{
WindowFrame wf = (WindowFrame)it.next();
WindowContent content = wf.getContent();
Cell cell = content.getCell();
if (cell != null && cell.getLibrary() == lib)
content.setCell(null, null);
content.fullRepaint();
}
}
/**
* Method to set the current WindowFrame.
* @param wf the WindowFrame to make current.
*/
public static void setCurrentWindowFrame(WindowFrame wf)
{
synchronized(windowList) {
//if (curWindowFrame == wf) return;
curWindowFrame = wf;
}
if (wf != null)
{
Cell cell = wf.getContent().getCell();
if (cell != null)
{
cell.getLibrary().setCurCell(cell);
// if auto-switching technology, do it
PaletteFrame.autoTechnologySwitch(cell);
}
}
wantToRedoTitleNames();
}
public static void wantToRedoTitleNames()
{
// rebuild window titles
for (Iterator it = getWindows(); it.hasNext(); )
{
WindowFrame w = (WindowFrame)it.next();
WindowContent content = w.getContent();
if (content != null) content.setWindowTitle();
}
}
public void setWindowSize(Rectangle frameRect)
{
Dimension frameSize = new Dimension(frameRect.width, frameRect.height);
if (TopLevel.isMDIMode())
{
jif.setSize(frameSize);
jif.setLocation(frameRect.x, frameRect.y);
} else
{
jf.setSize(frameSize);
jf.setLocation(frameRect.x, frameRect.y);
jf.validate();
}
}
/**
* Method to record that this WindowFrame has been closed.
* This method is called from the event handlers on the windows.
*/
public void finished()
{
// remove references to this
synchronized(windowList) {
if (windowList.size() <= 1 && !TopLevel.isMDIMode() &&
TopLevel.getOperatingSystem() != TopLevel.OS.MACINTOSH)
{
FileMenu.quitCommand();
//JOptionPane.showMessageDialog(TopLevel.getCurrentJFrame(),
// "Cannot close the last window");
return;
}
windowList.remove(this);
if (curWindowFrame == this) curWindowFrame = null;
}
// tell EditWindow it's finished
content.finished();
if (!TopLevel.isMDIMode()) {
// if SDI mode, TopLevel enclosing frame is closing, dispose of it
((TopLevel)jf).finished();
}
}
/**
* Method to return the WaveformWindow associated with this frame.
* @return the WaveformWindow associated with this frame.
*/
public WaveformWindow getWaveformWindow() { return (WaveformWindow)content; }
/**
* Method to return the text edit window associated with this frame.
* @return the text edit window associated with this frame.
*/
public JTextArea getTextEditWindow() { return textWnd; }
/**
* Method to return the ExplorerTree associated with this frame.
* @return the ExplorerTree associated with this frame.
*/
public ExplorerTree getExplorerTree() { return tree; }
/**
* Method to return the TopLevel associated with this WindowFrame.
* In SDI mode this returns this WindowFrame's TopLevel Frame.
* In MDI mode there is only one TopLevel frame, so this method will
* return that Frame.
* @return the TopLevel associated with this WindowFrame.
*/
public TopLevel getFrame() {
if (TopLevel.isMDIMode()) {
return TopLevel.getCurrentJFrame();
}
return jf;
}
/**
* Returns true if this window frame or it's components generated
* this event.
* @param e the event generated
* @return true if this window frame or it's components generated this
* event, false otherwise.
*/
public boolean generatedEvent(java.awt.AWTEvent e) {
if (e instanceof InternalFrameEvent) {
JInternalFrame source = ((InternalFrameEvent)e).getInternalFrame();
if (source == jif) return true;
else return false;
}
return false;
}
/**
* Method to return the number of WindowFrames.
* @return the number of WindowFrames.
*/
public static int getNumWindows() {
synchronized(windowList) {
return windowList.size();
}
}
/**
* Method to return an Iterator over all WindowFrames.
* @return an Iterator over all WindowFrames.
*/
public static Iterator getWindows() { return windowList.iterator(); }
/**
* Centralized version of naming windows! Might move it to class
* that would replace WindowContext
* @param cell
* @param prefix
*/
public String composeTitle(Cell cell, String prefix)
{
// StringBuffer should be more efficient
StringBuffer title = new StringBuffer();
if (cell != null)
{
title.append(prefix + cell.describe());
if (cell.getLibrary() != Library.getCurrent())
title.append(" - Current library: " + Library.getCurrent().getName());
}
else
title.append("***NONE***");
return (title.toString());
}
/**
* Method to set the description on the window frame
*/
public void setTitle(String title)
{
if (TopLevel.isMDIMode()) {
if (jif != null) jif.setTitle(title);
} else {
if (jf != null) jf.setTitle(title);
}
}
private static void removeUIBinding(JComponent comp, KeyStroke key) {
removeUIBinding(comp.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT), key);
removeUIBinding(comp.getInputMap(JComponent.WHEN_FOCUSED), key);
removeUIBinding(comp.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW), key);
}
private static void removeUIBinding(InputMap map, KeyStroke key) {
if (map == null) return;
map.remove(key);
removeUIBinding(map.getParent(), key);
}
//******************************** HANDLERS FOR WINDOW EVENTS ********************************
/**
* This class handles activation and close events for JFrame objects (used in SDI mode).
*/
static class WindowsEvents extends WindowAdapter
{
/** A weak reference to the WindowFrame */
WeakReference wf;
WindowsEvents(WindowFrame wf)
{
super();
this.wf = new WeakReference(wf);
}
public void windowActivated(WindowEvent evt)
{
WindowFrame.setCurrentWindowFrame((WindowFrame)wf.get());
}
public void windowClosing(WindowEvent evt)
{
((WindowFrame)wf.get()).finished();
}
}
/**
* This class handles activation and close events for JInternalFrame objects (used in MDI mode).
*/
static class InternalWindowsEvents extends InternalFrameAdapter
{
/** A weak reference to the WindowFrame */
WeakReference wf;
InternalWindowsEvents(WindowFrame wf)
{
super();
this.wf = new WeakReference(wf);
}
public void internalFrameClosing(InternalFrameEvent evt)
{
((WindowFrame)wf.get()).finished();
}
public void internalFrameActivated(InternalFrameEvent evt)
{
WindowFrame.setCurrentWindowFrame((WindowFrame)wf.get());
}
}
}
| true | true | public static WindowFrame create3DViewtWindow(Cell cell)
{
WindowFrame frame = new WindowFrame();
/*
WindowContent vWnd = new View3DWindow(cell, frame);
frame.buildWindowStructure((WindowContent)vWnd, cell, null);
setCurrentWindowFrame(frame);
frame.populateJFrame();
*/
Class view3DClass;
try
{
view3DClass = Class.forName("com.sun.electric.plugins.j3d.View3DWindow");
} catch (ClassNotFoundException e)
{
System.out.println("Can't find 3D View plugin: " + e.getMessage());
return frame;
}
Constructor constructor = null;
try
{
constructor = view3DClass.getDeclaredConstructor(new Class[] {Cell.class, WindowFrame.class}) ;
Object vWnd = constructor.newInstance(new Object[] {cell, frame});
frame.buildWindowStructure((WindowContent)vWnd, cell, null);
setCurrentWindowFrame(frame);
frame.populateJFrame();
} catch (Exception e) {
System.out.println("Can't open 3D View window: " + e.getMessage());
e.printStackTrace();
}
return frame;
}
| public static WindowFrame create3DViewtWindow(Cell cell)
{
WindowFrame frame = new WindowFrame();
/*
WindowContent vWnd = new View3DWindow(cell, frame);
frame.buildWindowStructure((WindowContent)vWnd, cell, null);
setCurrentWindowFrame(frame);
frame.populateJFrame();
*/
Class view3DClass;
try
{
view3DClass = Class.forName("com.sun.electric.plugins.j3d.View3DWindow");
} catch (ClassNotFoundException e)
{
System.out.println("Can't find 3D View plugin: " + e.getMessage());
return frame;
} catch (Error e)
{
System.out.println("Java3D not installed: " + e.getMessage());
return frame;
}
Constructor constructor = null;
try
{
constructor = view3DClass.getDeclaredConstructor(new Class[] {Cell.class, WindowFrame.class}) ;
Object vWnd = constructor.newInstance(new Object[] {cell, frame});
frame.buildWindowStructure((WindowContent)vWnd, cell, null);
setCurrentWindowFrame(frame);
frame.populateJFrame();
} catch (Exception e) {
System.out.println("Can't open 3D View window: " + e.getMessage());
e.printStackTrace();
}
return frame;
}
|
diff --git a/GeeksNearby-mobile/android/src/me/outof/geeksnearby/GeeksNearbyActivity.java b/GeeksNearby-mobile/android/src/me/outof/geeksnearby/GeeksNearbyActivity.java
index afc34d5..32407dc 100644
--- a/GeeksNearby-mobile/android/src/me/outof/geeksnearby/GeeksNearbyActivity.java
+++ b/GeeksNearby-mobile/android/src/me/outof/geeksnearby/GeeksNearbyActivity.java
@@ -1,36 +1,36 @@
/*
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 me.outof.geeksnearby;
import org.apache.cordova.DroidGap;
import android.os.Bundle;
public class GeeksNearbyActivity extends DroidGap
{
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
super.setIntegerProperty("splashscreen", R.drawable.splash);
- super.loadUrl("file:///android_asset/www/index-android.html", 2000);
+ super.loadUrl("file:///android_asset/www/index-android.html", 5000);
}
}
| true | true | public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
super.setIntegerProperty("splashscreen", R.drawable.splash);
super.loadUrl("file:///android_asset/www/index-android.html", 2000);
}
| public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
super.setIntegerProperty("splashscreen", R.drawable.splash);
super.loadUrl("file:///android_asset/www/index-android.html", 5000);
}
|
diff --git a/jdbc/src/test/java/org/javaz/test/jdbc/JdbcCachedTest.java b/jdbc/src/test/java/org/javaz/test/jdbc/JdbcCachedTest.java
index 54029c4..bad6d31 100644
--- a/jdbc/src/test/java/org/javaz/test/jdbc/JdbcCachedTest.java
+++ b/jdbc/src/test/java/org/javaz/test/jdbc/JdbcCachedTest.java
@@ -1,319 +1,323 @@
package org.javaz.test.jdbc;
import junit.framework.Assert;
import org.hsqldb.server.Server;
import org.javaz.jdbc.queues.GenericDbUpdater;
import org.javaz.jdbc.queues.SqlRecordsFetcher;
import org.javaz.jdbc.replicate.ReplicateTables;
import org.javaz.jdbc.util.*;
import org.javaz.queues.iface.RecordsRotatorI;
import org.javaz.queues.impl.RotatorsHolder;
import org.junit.BeforeClass;
import org.junit.Test;
import java.io.File;
import java.io.PrintWriter;
import java.util.*;
/**
*
*/
public class JdbcCachedTest
{
public static JdbcHelperI test = null;
public static JdbcHelperI test2 = null;
public static String address = null;
public static String address2 = null;
public static ConnectionProviderI provider = null;
public static int testPort = 31234;
@BeforeClass
public static void testPrepare() throws Exception
{
new UnsafeSqlHelper();
new JdbcCachedHelper();
address = "jdbc:hsqldb:hsql://localhost:" + testPort + "/mydb1;username=SA";
address2 = "jdbc:hsqldb:hsql://localhost:" + testPort + "/mydb2;username=SA";
// address = "jdbc:hsqldb:mem:test1;username=SA";
test = JdbcCachedHelper.getInstance(address);
test2 = JdbcCachedHelper.getInstance(address2);
Assert.assertEquals(address, test.getJdbcAddress());
provider = test.getProvider();
test.setProvider(provider);
long ttl = test.getListRecordsTtl();
test.setListRecordsTtl(ttl);
Server server = new Server();
server.setAddress("localhost");
server.setDatabaseName(0, "mydb1");
server.setDatabaseName(1, "mydb2");
File tempFile1 = File.createTempFile("jdbc-junit-test1", "hsqldb");
tempFile1.deleteOnExit();
server.setDatabasePath(0, tempFile1.getCanonicalPath());
File tempFile2 = File.createTempFile("jdbc-junit-test2", "hsqldb");
tempFile2.deleteOnExit();
server.setDatabasePath(1, tempFile2.getCanonicalPath());
server.setPort(testPort);
server.setTrace(true);
server.setLogWriter(new PrintWriter(System.out));
server.start();
try
{
Class.forName("org.hsqldb.jdbc.JDBCDriver");
}
catch (ClassNotFoundException e)
{
e.printStackTrace(System.out);
}
}
@Test
public void testCache() throws Exception
{
test.runUpdate("drop table test", null);
test.runUpdate("create table test (id integer, name varchar(250))", null);
test.runUpdate("insert into test values (1,'a'),(2,'b'),(3,'c')", null);
HashMap params = new HashMap();
UnsafeSqlHelper.addArrayParameters(params, new Object[]{1, 2});
ArrayList id3 = new ArrayList();
id3.add(3);
UnsafeSqlHelper.addArrayParameters(params, id3);
List list =
test.getRecordList("select * from test where id in (" + UnsafeSqlHelper.repeatQuestionMark(params.size()) + ")", params);
Assert.assertEquals(list.size(), 3);
ArrayList updates = new ArrayList();
updates.add(new Object[]{"insert into test values (101,'a')", null});
updates.add(new Object[]{"insert into test values (102,'b')", null});
updates.add(new Object[]{"insert into test values (103,'c')", null});
test.runMassUpdate(updates);
list = test.getRecordList("select * from test", null, false);
Assert.assertEquals(list.size(), 6);
test.runUpdate("drop table test", null);
list = test.getRecordList("select * from test", null, false);
Assert.assertEquals(list.size(), 0);
List list2 =
test.getRecordList("select * from test where id in (" + UnsafeSqlHelper.repeatQuestionMark(params.size()) + ")", params);
Assert.assertEquals(list2.size(), 3);
}
@Test
public void testMassUpdate() throws Exception
{
test.runUpdate("drop table test2", null);
test.runUpdate("create table test2 (id INTEGER GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY, dt timestamp)", null);
long millis = System.currentTimeMillis();
HashMap params = new HashMap();
params.clear();
params.put(1, new Date(millis));
ArrayList updates = new ArrayList();
updates.clear();
updates.add(new Object[]{"insert into test2 (dt) values (?)", params});
updates.add(new Object[]{"insert into test2 (dt) values (?)", params});
updates.add(new Object[]{"insert into test2 (dt) values (?)", params});
ArrayList<List> massUpdate = test.runMassUpdate(updates);
Assert.assertEquals(massUpdate.size(), 3);
Assert.assertEquals(((List) massUpdate.get(0)).size(), 2);
ArrayList metadata = UnsafeSqlHelper.runSqlUnsafe(provider, address,
"select id from test2", JdbcConstants.ACTION_COMPLEX_LIST_METADATA, null);
Assert.assertEquals(metadata.size(), 4);
Assert.assertTrue(((List) metadata.get(0)).get(0).getClass().getName().contains("String"));
ArrayList nometadata = UnsafeSqlHelper.runSqlUnsafe(provider, address,
"select id from test2", JdbcConstants.ACTION_COMPLEX_LIST_NO_METADATA, null);
Assert.assertEquals(nometadata.size(), 3);
Assert.assertTrue(((List) nometadata.get(0)).get(0) instanceof Number);
ArrayList ids = UnsafeSqlHelper.runSqlUnsafe(provider, address,
"select id from test2", JdbcConstants.ACTION_LIST_FIRST_OBJECTS, null);
Assert.assertTrue(ids.get(0) instanceof Number);
test.runUpdate("drop table test2", null);
}
@Test
public void testGenericUpdater() throws Exception
{
test.runUpdate("drop table test3", null);
test.runUpdate("create table test3 (id integer, name varchar(250))", null);
test.runUpdate("insert into test3 values (1,'a'),(2,'b'),(3,'c')", null);
String query = "update test3 set name='x' where id";
GenericDbUpdater dbUpdater = GenericDbUpdater.getInstance(query, address);
Assert.assertEquals(dbUpdater.getQuery(), query);
Assert.assertEquals(dbUpdater.getDb(), address);
dbUpdater.addToQueue(1);
Thread.sleep(GenericDbUpdater.LONG_SEND_PERIOD);
List list = test.getRecordList("select * from test3 where name='x'", null, false);
Assert.assertEquals(list.size(), 1);
ArrayList collection = new ArrayList();
collection.add(2);
collection.add(3);
dbUpdater.addToQueueAll(collection);
int tries = 3;
list = test.getRecordList("select * from test3 where name='x'", null, false);
while (tries-- > 0 && list.size() != 3)
{
Thread.sleep(GenericDbUpdater.LONG_SEND_PERIOD);
list = test.getRecordList("select * from test3 where name='x'", null, false);
}
Assert.assertEquals(list.size(), 3);
test.runUpdate("drop table test3", null);
}
@Test
public void testSqlFetcher() throws Exception
{
test.runUpdate("drop table test4", null);
test.runUpdate("create table test4 (idx integer, name varchar(250))", null);
test.runUpdate("insert into test4 values (1,'a'),(2,'b'),(300000,'c')", null);
SqlRecordsFetcher nullFetcher = new SqlRecordsFetcher(null,
"idx, name", "test4", "idx > 0");
RecordsRotatorI rotaterNull = RotatorsHolder.getRotater(nullFetcher);
SqlRecordsFetcher recordsFetcher = new SqlRecordsFetcher(address,
"idx, name", "test4", "idx > 0");
recordsFetcher.setIdColumn("idx");
recordsFetcher.setSelectType(JdbcConstants.ACTION_MAP_RESULTS_SET);
System.out.println("recordsFetcher.getDescriptiveName() = " + recordsFetcher.getDescriptiveName());
recordsFetcher.setFieldsClause(recordsFetcher.getFieldsClause());
recordsFetcher.setWhereClause(recordsFetcher.getWhereClause());
recordsFetcher.setProviderI(recordsFetcher.getProviderI());
RecordsRotatorI rotater = RotatorsHolder.getRotater(recordsFetcher);
SqlRecordsFetcher recordsFetcher2 = new SqlRecordsFetcher(address,
"idx, name", "test4", "idx > 0");
Assert.assertEquals(recordsFetcher2.getIdColumn(), "id");
Assert.assertEquals(recordsFetcher2.getSelectType(), JdbcConstants.ACTION_MAP_RESULTS_SET);
recordsFetcher2.setIdColumn("idx");
Assert.assertTrue(recordsFetcher.equals(recordsFetcher2));
recordsFetcher2.setSelectType(JdbcConstants.ACTION_COMPLEX_LIST_NO_METADATA);
Assert.assertFalse(recordsFetcher.equals(recordsFetcher2));
RecordsRotatorI rotater2 = RotatorsHolder.getRotater(recordsFetcher2);
int totalSteps = 100;
int steps = totalSteps;
while (rotater.getCurrentQueueSize() < 3 && steps-- > 0)
{
Thread.sleep(rotater.getFetchDelay() / totalSteps);
}
//after this sleeps, rotaters MUST fetch all data, since the reported count less than minSize
Collection elements = rotater.getManyElements(100);
Assert.assertEquals(elements.size(), 3);
Collection elements2 = rotater2.getManyElements(100);
Assert.assertEquals(elements2.size(), 3);
Assert.assertTrue(elements.iterator().next() instanceof Map);
Assert.assertTrue(elements2.iterator().next() instanceof List);
test.runUpdate("drop table test4", null);
}
@Test
public void testReplicator() throws Exception
{
test.runUpdate("drop table test5", null);
test2.runUpdate("drop table test6", null);
test.runUpdate("create table test5 (id integer, name varchar(250), dt timestamp)", null);
test2.runUpdate("create table test6 (id integer, name varchar(250), dt timestamp)", null);
test.runUpdate("drop table test8", null);
test2.runUpdate("drop table test8", null);
test.runUpdate("create table test8 (id integer, name varchar(250), dt timestamp)", null);
test2.runUpdate("create table test8 (id integer, name varchar(250), dt varchar(45), moreone integer)", null);
test.runUpdate("insert into test5 values (0,'X', NULL), (1, 'a', '2013-01-01 00:06:00.101'), (2, NULL, '2011-01-01 00:06:00.103'),(300000,'c', '2011-01-01 00:06:00')", null);
test2.runUpdate("insert into test6 values (0,'Y', NULL), (1, 'not A', '2013-01-01 00:06:00.103'), (2, NULL, '2013-01-01 00:06:00.103'),(40,'b', '2013-01-01 00:06:00')", null);
List list = test.getRecordList("select * from test5 order by id", null, false);
Assert.assertEquals(list.size(), 4);
List list2 = test2.getRecordList("select * from test6", null, false);
Assert.assertEquals(list2.size(), 4);
ReplicateTables replicator = new ReplicateTables();
replicator.init(null);
replicator.dbFrom = address;
replicator.dbTo = address2;
replicator.dbToType = "hsqldb";
HashMap<String, String> tableInfo = new HashMap<String, String>();
tableInfo.put("name", "test5");
tableInfo.put("name2", "test6");
tableInfo.put("where1", " AND id > 0 ");
tableInfo.put("where2", " AND id > 0 ");
replicator.tables.add(tableInfo);
replicator.runReplicate();
list2 = test2.getRecordList("select * from test6 order by id", null, false);
Assert.assertEquals(list2.size(), 4);
for (int i = 0; i < list.size(); i++)
{
Map m1 = (Map) list.get(i);
Map m2 = (Map) list2.get(i);
Object id = m1.get("ID");
+ if(id == null)
+ {
+ id = m1.get("id");
+ }
if (id.equals(0))
{
Assert.assertNotSame(m1, m2);
}
else
{
Assert.assertEquals(m1, m2);
}
}
test2.runUpdate("delete from test6", null);
replicator.runReplicate();
list2 = test2.getRecordList("select * from test6 order by id", null, false);
Assert.assertEquals(list2.size(), 3);
test.runUpdate("drop table test5", null);
test2.runUpdate("drop table test6", null);
tableInfo = new HashMap<String, String>();
tableInfo.put("name", "test8");
tableInfo.put("name2", "test8");
tableInfo.put("where1", "");
tableInfo.put("where2", "");
replicator.tables.clear();
replicator.tables.add(tableInfo);
replicator.clearLog();
replicator.runReplicate();
String log = replicator.getLog();
Assert.assertTrue(log.contains("ERROR: Meta data"));
test.runUpdate("drop table test8", null);
test2.runUpdate("drop table test8", null);
}
}
| true | true | public void testReplicator() throws Exception
{
test.runUpdate("drop table test5", null);
test2.runUpdate("drop table test6", null);
test.runUpdate("create table test5 (id integer, name varchar(250), dt timestamp)", null);
test2.runUpdate("create table test6 (id integer, name varchar(250), dt timestamp)", null);
test.runUpdate("drop table test8", null);
test2.runUpdate("drop table test8", null);
test.runUpdate("create table test8 (id integer, name varchar(250), dt timestamp)", null);
test2.runUpdate("create table test8 (id integer, name varchar(250), dt varchar(45), moreone integer)", null);
test.runUpdate("insert into test5 values (0,'X', NULL), (1, 'a', '2013-01-01 00:06:00.101'), (2, NULL, '2011-01-01 00:06:00.103'),(300000,'c', '2011-01-01 00:06:00')", null);
test2.runUpdate("insert into test6 values (0,'Y', NULL), (1, 'not A', '2013-01-01 00:06:00.103'), (2, NULL, '2013-01-01 00:06:00.103'),(40,'b', '2013-01-01 00:06:00')", null);
List list = test.getRecordList("select * from test5 order by id", null, false);
Assert.assertEquals(list.size(), 4);
List list2 = test2.getRecordList("select * from test6", null, false);
Assert.assertEquals(list2.size(), 4);
ReplicateTables replicator = new ReplicateTables();
replicator.init(null);
replicator.dbFrom = address;
replicator.dbTo = address2;
replicator.dbToType = "hsqldb";
HashMap<String, String> tableInfo = new HashMap<String, String>();
tableInfo.put("name", "test5");
tableInfo.put("name2", "test6");
tableInfo.put("where1", " AND id > 0 ");
tableInfo.put("where2", " AND id > 0 ");
replicator.tables.add(tableInfo);
replicator.runReplicate();
list2 = test2.getRecordList("select * from test6 order by id", null, false);
Assert.assertEquals(list2.size(), 4);
for (int i = 0; i < list.size(); i++)
{
Map m1 = (Map) list.get(i);
Map m2 = (Map) list2.get(i);
Object id = m1.get("ID");
if (id.equals(0))
{
Assert.assertNotSame(m1, m2);
}
else
{
Assert.assertEquals(m1, m2);
}
}
test2.runUpdate("delete from test6", null);
replicator.runReplicate();
list2 = test2.getRecordList("select * from test6 order by id", null, false);
Assert.assertEquals(list2.size(), 3);
test.runUpdate("drop table test5", null);
test2.runUpdate("drop table test6", null);
tableInfo = new HashMap<String, String>();
tableInfo.put("name", "test8");
tableInfo.put("name2", "test8");
tableInfo.put("where1", "");
tableInfo.put("where2", "");
replicator.tables.clear();
replicator.tables.add(tableInfo);
replicator.clearLog();
replicator.runReplicate();
String log = replicator.getLog();
Assert.assertTrue(log.contains("ERROR: Meta data"));
test.runUpdate("drop table test8", null);
test2.runUpdate("drop table test8", null);
}
| public void testReplicator() throws Exception
{
test.runUpdate("drop table test5", null);
test2.runUpdate("drop table test6", null);
test.runUpdate("create table test5 (id integer, name varchar(250), dt timestamp)", null);
test2.runUpdate("create table test6 (id integer, name varchar(250), dt timestamp)", null);
test.runUpdate("drop table test8", null);
test2.runUpdate("drop table test8", null);
test.runUpdate("create table test8 (id integer, name varchar(250), dt timestamp)", null);
test2.runUpdate("create table test8 (id integer, name varchar(250), dt varchar(45), moreone integer)", null);
test.runUpdate("insert into test5 values (0,'X', NULL), (1, 'a', '2013-01-01 00:06:00.101'), (2, NULL, '2011-01-01 00:06:00.103'),(300000,'c', '2011-01-01 00:06:00')", null);
test2.runUpdate("insert into test6 values (0,'Y', NULL), (1, 'not A', '2013-01-01 00:06:00.103'), (2, NULL, '2013-01-01 00:06:00.103'),(40,'b', '2013-01-01 00:06:00')", null);
List list = test.getRecordList("select * from test5 order by id", null, false);
Assert.assertEquals(list.size(), 4);
List list2 = test2.getRecordList("select * from test6", null, false);
Assert.assertEquals(list2.size(), 4);
ReplicateTables replicator = new ReplicateTables();
replicator.init(null);
replicator.dbFrom = address;
replicator.dbTo = address2;
replicator.dbToType = "hsqldb";
HashMap<String, String> tableInfo = new HashMap<String, String>();
tableInfo.put("name", "test5");
tableInfo.put("name2", "test6");
tableInfo.put("where1", " AND id > 0 ");
tableInfo.put("where2", " AND id > 0 ");
replicator.tables.add(tableInfo);
replicator.runReplicate();
list2 = test2.getRecordList("select * from test6 order by id", null, false);
Assert.assertEquals(list2.size(), 4);
for (int i = 0; i < list.size(); i++)
{
Map m1 = (Map) list.get(i);
Map m2 = (Map) list2.get(i);
Object id = m1.get("ID");
if(id == null)
{
id = m1.get("id");
}
if (id.equals(0))
{
Assert.assertNotSame(m1, m2);
}
else
{
Assert.assertEquals(m1, m2);
}
}
test2.runUpdate("delete from test6", null);
replicator.runReplicate();
list2 = test2.getRecordList("select * from test6 order by id", null, false);
Assert.assertEquals(list2.size(), 3);
test.runUpdate("drop table test5", null);
test2.runUpdate("drop table test6", null);
tableInfo = new HashMap<String, String>();
tableInfo.put("name", "test8");
tableInfo.put("name2", "test8");
tableInfo.put("where1", "");
tableInfo.put("where2", "");
replicator.tables.clear();
replicator.tables.add(tableInfo);
replicator.clearLog();
replicator.runReplicate();
String log = replicator.getLog();
Assert.assertTrue(log.contains("ERROR: Meta data"));
test.runUpdate("drop table test8", null);
test2.runUpdate("drop table test8", null);
}
|
diff --git a/org.eclipse.search/search/org/eclipse/search/internal/core/text/TextSearchVisitor.java b/org.eclipse.search/search/org/eclipse/search/internal/core/text/TextSearchVisitor.java
index 65a006bce..415d91992 100644
--- a/org.eclipse.search/search/org/eclipse/search/internal/core/text/TextSearchVisitor.java
+++ b/org.eclipse.search/search/org/eclipse/search/internal/core/text/TextSearchVisitor.java
@@ -1,201 +1,201 @@
/*******************************************************************************
* 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.search.internal.core.text;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IResourceProxy;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.MultiStatus;
import org.eclipse.core.runtime.OperationCanceledException;
import org.eclipse.core.runtime.Platform;
import org.eclipse.core.runtime.Status;
import org.eclipse.search.internal.core.ISearchScope;
import org.eclipse.search.internal.ui.SearchMessages;
import org.eclipse.search.internal.ui.SearchPlugin;
import org.eclipse.search.ui.SearchUI;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IEditorReference;
import org.eclipse.ui.IFileEditorInput;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.texteditor.ITextEditor;
/**
* The visitor that does the actual work.
*/
public class TextSearchVisitor extends TypedResourceVisitor {
protected static final int fgLF= '\n';
protected static final int fgCR= '\r';
private ISearchScope fScope;
private ITextSearchResultCollector fCollector;
private IEditorPart[] fEditors;
private MatchLocator fLocator;
private IProgressMonitor fProgressMonitor;
private Integer[] fMessageFormatArgs;
private int fNumberOfScannedFiles;
private int fNumberOfFilesToScan;
private long fLastUpdateTime;
public TextSearchVisitor(MatchLocator locator, ISearchScope scope, ITextSearchResultCollector collector, MultiStatus status, int fileCount) {
super(status);
fScope= scope;
fCollector= collector;
fProgressMonitor= collector.getProgressMonitor();
fLocator= locator;
fNumberOfScannedFiles= 0;
fNumberOfFilesToScan= fileCount;
fMessageFormatArgs= new Integer[] { new Integer(0), new Integer(fileCount) };
}
public void process(Collection projects) {
Iterator i= projects.iterator();
while(i.hasNext()) {
IProject project= (IProject)i.next();
try {
project.accept(this, IResource.NONE);
} catch (CoreException ex) {
addToStatus(ex);
}
}
}
/**
* Returns an array of all editors that have an unsaved content. If the identical content is
* presented in more than one editor, only one of those editor parts is part of the result.
*
* @return an array of all editor parts.
*/
public static IEditorPart[] getEditors() {
Set inputs= new HashSet();
List result= new ArrayList(0);
IWorkbench workbench= SearchPlugin.getDefault().getWorkbench();
IWorkbenchWindow[] windows= workbench.getWorkbenchWindows();
for (int i= 0; i < windows.length; i++) {
IWorkbenchPage[] pages= windows[i].getPages();
for (int x= 0; x < pages.length; x++) {
IEditorReference[] editorRefs= pages[x].getEditorReferences();
for (int z= 0; z < editorRefs.length; z++) {
IEditorPart ep= editorRefs[z].getEditor(false);
if (ep != null) {
IEditorInput input= ep.getEditorInput();
if (!inputs.contains(input)) {
inputs.add(input);
result.add(ep);
}
}
}
}
}
return (IEditorPart[])result.toArray(new IEditorPart[result.size()]);
}
protected boolean visitFile(IResourceProxy proxy) throws CoreException {
if (! fScope.encloses(proxy))
return false;
// Exclude to derived resources
if (proxy.isDerived())
return false;
if (fLocator.isEmtpy()) {
fCollector.accept(proxy, "", -1, 0, -1); //$NON-NLS-1$
updateProgressMonitor();
return true;
}
IFile file= (IFile)proxy.requestResource();
try {
BufferedReader reader= null;
ITextEditor editor= findEditorFor(file);
if (editor != null) {
String s= editor.getDocumentProvider().getDocument(editor.getEditorInput()).get();
reader= new BufferedReader(new StringReader(s));
} else {
InputStream stream= file.getContents(false);
- reader= new BufferedReader(new InputStreamReader(stream, ResourcesPlugin.getEncoding()));
+ reader= new BufferedReader(new InputStreamReader(stream, file.getCharset()));
}
try {
fLocator.locateMatches(fProgressMonitor, reader, new FileMatchCollector(fCollector, proxy));
} catch (InvocationTargetException e1) {
throw ((CoreException)e1.getCause());
}
} catch (IOException e) {
String message= SearchMessages.getFormattedString("TextSearchVisitor.error", file.getFullPath()); //$NON-NLS-1$
throw new CoreException(new Status(IStatus.ERROR, SearchUI.PLUGIN_ID, Platform.PLUGIN_ERROR, message, e));
}
finally {
updateProgressMonitor();
}
return true;
}
private void updateProgressMonitor() {
fNumberOfScannedFiles++;
if (fNumberOfScannedFiles < fNumberOfFilesToScan) {
if (System.currentTimeMillis() - fLastUpdateTime > 1000) {
fMessageFormatArgs[0]= new Integer(fNumberOfScannedFiles+1);
fProgressMonitor.setTaskName(SearchMessages.getFormattedString("TextSearchVisitor.scanning", fMessageFormatArgs)); //$NON-NLS-1$
fLastUpdateTime= System.currentTimeMillis();
}
}
fProgressMonitor.worked(1);
if (fProgressMonitor.isCanceled())
throw new OperationCanceledException(SearchMessages.getString("TextSearchVisitor.canceled")); //$NON-NLS-1$
}
private ITextEditor findEditorFor(IFile file) {
int i= 0;
while (i < fEditors.length) {
IEditorPart editor= fEditors[i];
IEditorInput input= editor.getEditorInput();
if (input instanceof IFileEditorInput && editor instanceof ITextEditor)
if (((IFileEditorInput)input).getFile().equals(file))
return (ITextEditor)editor;
i++;
}
return null;
}
/*
* @see IResourceProxyVisitor#visit(IResourceProxy)
*/
public boolean visit(IResourceProxy proxy) {
fEditors= getEditors();
return super.visit(proxy);
}
}
| true | true | protected boolean visitFile(IResourceProxy proxy) throws CoreException {
if (! fScope.encloses(proxy))
return false;
// Exclude to derived resources
if (proxy.isDerived())
return false;
if (fLocator.isEmtpy()) {
fCollector.accept(proxy, "", -1, 0, -1); //$NON-NLS-1$
updateProgressMonitor();
return true;
}
IFile file= (IFile)proxy.requestResource();
try {
BufferedReader reader= null;
ITextEditor editor= findEditorFor(file);
if (editor != null) {
String s= editor.getDocumentProvider().getDocument(editor.getEditorInput()).get();
reader= new BufferedReader(new StringReader(s));
} else {
InputStream stream= file.getContents(false);
reader= new BufferedReader(new InputStreamReader(stream, ResourcesPlugin.getEncoding()));
}
try {
fLocator.locateMatches(fProgressMonitor, reader, new FileMatchCollector(fCollector, proxy));
} catch (InvocationTargetException e1) {
throw ((CoreException)e1.getCause());
}
} catch (IOException e) {
String message= SearchMessages.getFormattedString("TextSearchVisitor.error", file.getFullPath()); //$NON-NLS-1$
throw new CoreException(new Status(IStatus.ERROR, SearchUI.PLUGIN_ID, Platform.PLUGIN_ERROR, message, e));
}
finally {
updateProgressMonitor();
}
return true;
}
| protected boolean visitFile(IResourceProxy proxy) throws CoreException {
if (! fScope.encloses(proxy))
return false;
// Exclude to derived resources
if (proxy.isDerived())
return false;
if (fLocator.isEmtpy()) {
fCollector.accept(proxy, "", -1, 0, -1); //$NON-NLS-1$
updateProgressMonitor();
return true;
}
IFile file= (IFile)proxy.requestResource();
try {
BufferedReader reader= null;
ITextEditor editor= findEditorFor(file);
if (editor != null) {
String s= editor.getDocumentProvider().getDocument(editor.getEditorInput()).get();
reader= new BufferedReader(new StringReader(s));
} else {
InputStream stream= file.getContents(false);
reader= new BufferedReader(new InputStreamReader(stream, file.getCharset()));
}
try {
fLocator.locateMatches(fProgressMonitor, reader, new FileMatchCollector(fCollector, proxy));
} catch (InvocationTargetException e1) {
throw ((CoreException)e1.getCause());
}
} catch (IOException e) {
String message= SearchMessages.getFormattedString("TextSearchVisitor.error", file.getFullPath()); //$NON-NLS-1$
throw new CoreException(new Status(IStatus.ERROR, SearchUI.PLUGIN_ID, Platform.PLUGIN_ERROR, message, e));
}
finally {
updateProgressMonitor();
}
return true;
}
|
diff --git a/src/net/vincentpetry/nodereviver/view/ViewContext.java b/src/net/vincentpetry/nodereviver/view/ViewContext.java
index eeed11f..3dbf2c8 100644
--- a/src/net/vincentpetry/nodereviver/view/ViewContext.java
+++ b/src/net/vincentpetry/nodereviver/view/ViewContext.java
@@ -1,81 +1,81 @@
package net.vincentpetry.nodereviver.view;
import net.vincentpetry.nodereviver.model.GameContext;
import android.content.res.Resources;
import android.graphics.Typeface;
import android.util.DisplayMetrics;
public class ViewContext {
private Typeface typeface;
private SpriteManager spriteManager;
private int width;
private int height;
private float fontHeightNormal;
private float fontHeightBig;
private float scaling;
private GameContext gameContext;
public ViewContext(Resources resources, GameContext gameContext){
this.gameContext = gameContext;
this.typeface = Typeface.createFromAsset(resources.getAssets(), "fonts/DejaVuSansMono.ttf");
this.spriteManager = new SpriteManager(resources);
switch (resources.getDisplayMetrics().densityDpi) {
case DisplayMetrics.DENSITY_LOW:
- fontHeightNormal = 9.0f;
- fontHeightBig = 11.0f;
+ fontHeightNormal = 8.0f;
+ fontHeightBig = 10.0f;
scaling = 0.5f;
break;
default:
case DisplayMetrics.DENSITY_MEDIUM:
fontHeightNormal = 12.0f;
fontHeightBig = 15.0f;
scaling = 1.0f;
break;
case DisplayMetrics.DENSITY_HIGH:
fontHeightNormal = 15.0f;
fontHeightBig = 18.0f;
scaling = 1.0f;
break;
}
}
public Typeface getTypeface(){
return typeface;
}
public float getFontHeightBig(){
return fontHeightBig;
}
public float getFontHeightNormal(){
return fontHeightNormal;
}
public SpriteManager getSpriteManager(){
return spriteManager;
}
public void setSize(int width, int height){
this.width = width;
this.height = height;
}
public int getWidth(){
return width;
}
public int getHeight(){
return height;
}
public GameContext getGameContext(){
return gameContext;
}
public float getScaling(){
return scaling;
}
}
| true | true | public ViewContext(Resources resources, GameContext gameContext){
this.gameContext = gameContext;
this.typeface = Typeface.createFromAsset(resources.getAssets(), "fonts/DejaVuSansMono.ttf");
this.spriteManager = new SpriteManager(resources);
switch (resources.getDisplayMetrics().densityDpi) {
case DisplayMetrics.DENSITY_LOW:
fontHeightNormal = 9.0f;
fontHeightBig = 11.0f;
scaling = 0.5f;
break;
default:
case DisplayMetrics.DENSITY_MEDIUM:
fontHeightNormal = 12.0f;
fontHeightBig = 15.0f;
scaling = 1.0f;
break;
case DisplayMetrics.DENSITY_HIGH:
fontHeightNormal = 15.0f;
fontHeightBig = 18.0f;
scaling = 1.0f;
break;
}
}
| public ViewContext(Resources resources, GameContext gameContext){
this.gameContext = gameContext;
this.typeface = Typeface.createFromAsset(resources.getAssets(), "fonts/DejaVuSansMono.ttf");
this.spriteManager = new SpriteManager(resources);
switch (resources.getDisplayMetrics().densityDpi) {
case DisplayMetrics.DENSITY_LOW:
fontHeightNormal = 8.0f;
fontHeightBig = 10.0f;
scaling = 0.5f;
break;
default:
case DisplayMetrics.DENSITY_MEDIUM:
fontHeightNormal = 12.0f;
fontHeightBig = 15.0f;
scaling = 1.0f;
break;
case DisplayMetrics.DENSITY_HIGH:
fontHeightNormal = 15.0f;
fontHeightBig = 18.0f;
scaling = 1.0f;
break;
}
}
|
diff --git a/src/main/java/microDSN/MicroBenchHandler.java b/src/main/java/microDSN/MicroBenchHandler.java
index a78a065..26fa6e5 100644
--- a/src/main/java/microDSN/MicroBenchHandler.java
+++ b/src/main/java/microDSN/MicroBenchHandler.java
@@ -1,327 +1,327 @@
/*
* Copyright (c) 2010 Ecole des Mines de Nantes.
*
* This file is part of Entropy.
*
* Entropy 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.
*
* Entropy 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 Entropy. If not, see <http://www.gnu.org/licenses/>.
*/
package microDSN;
import btrpsl.BtrPlaceVJobBuilder;
import btrpsl.constraint.ConstraintsCatalog;
import btrpsl.constraint.ConstraintsCatalogBuilderFromProperties;
import btrpsl.includes.PathBasedIncludes;
import choco.kernel.common.logging.ChocoLogging;
import choco.kernel.common.logging.Verbosity;
import entropy.PropertiesHelper;
import entropy.configuration.Configuration;
import entropy.configuration.ManagedElementSet;
import entropy.configuration.SimpleManagedElementSet;
import entropy.configuration.VirtualMachine;
import entropy.configuration.parser.FileConfigurationSerializerFactory;
import entropy.jobsManager.Job;
import entropy.jobsManager.JobDispatcher;
import entropy.jobsManager.JobHandler;
import entropy.plan.Plan;
import entropy.plan.choco.CustomizableSplitablePlannerModule;
import entropy.plan.durationEvaluator.DurationEvaluator;
import entropy.plan.durationEvaluator.FastDurationEvaluatorFactory;
import entropy.plan.parser.PlainTextTimedReconfigurationPlanSerializer;
import entropy.template.DefaultVirtualMachineTemplateFactory;
import entropy.template.stub.StubVirtualMachineTemplate;
import entropy.vjob.VJob;
import entropy.vjob.builder.DefaultVJobElementBuilder;
import entropy.vjob.builder.VJobElementBuilder;
import gnu.trove.THashSet;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
/**
* @author Fabien Hermenier
*/
public class MicroBenchHandler {
public static void main(String[] args) {
ChocoLogging.setVerbosity(Verbosity.SILENT);
ChocoLogging.setLoggingMaxDepth(3100);
ChocoLogging.setEveryXNodes(100);
String server = null;
String configs = null;
String vjobs = null;
String props = null;
String output = null;
if (args.length == 0) {
usage();
System.exit(0);
}
boolean remote = false;
for (int i = 0; i < args.length; i++) {
if (args[i].equals("-s")) {
server = args[++i];
remote = true;
} else if (args[i].equals("-cfgs")) {
configs = args[++i];
} else if (args[i].equals("-vjobs")) {
vjobs = args[++i];
} else if (args[i].equals("-props")) {
props = args[++i];
} else if (args[i].equals("-o")) {
output = args[++i];
} else {
fatal("Unknown argument: " + args[i]);
}
}
try {
if (remote) {
benchFromServer(server);
} else {
benchInstance(props, configs, vjobs, output);
}
} catch (Exception e) {
e.printStackTrace();
fatal(e.getMessage());
}
}
private static void benchInstance(String propsF, String configsPath, String vPath, String output) throws Exception {
if (propsF == null || !new File(propsF).isFile()) {
fatal("the properties file must be an existing file. Currently: '" + propsF + "'");
}
PropertiesHelper props = new PropertiesHelper(propsF);
List<Configuration[]> configs = new ArrayList<Configuration[]>();
List<VJob> vjobs = null;
if (!configsPath.contains(",")) {
File base = new File(configsPath);
for (File f : base.listFiles()) {
if (f.isFile()) {
Configuration src = null;
Configuration dst = null;
String name = f.getName().substring(0, f.getName().lastIndexOf('.'));
String parent = f.getParent();
if (name.endsWith("-src")) {
src = FileConfigurationSerializerFactory.getInstance().read(f.getPath());
dst = FileConfigurationSerializerFactory.getInstance().read(parent + name.substring(0, name.length() - 4) + "-dst.pbd");
}
configs.add(new Configuration[]{src, dst});
}
}
} else {
String srcP, dstP;
String[] tokens = configsPath.split(",");
srcP = tokens[0];
dstP = tokens[1];
Configuration src = FileConfigurationSerializerFactory.getInstance().read(srcP);
Configuration dst = FileConfigurationSerializerFactory.getInstance().read(dstP);
configs.add(new Configuration[]{src, dst});
}
vjobs = getVJobs(configs.get(0)[0], new File(vPath), listFiles(vPath, true));
PrintWriter out = null;
try {
if (output != null) {
out = new PrintWriter(output);
}
for (Configuration[] ins : configs) {
BenchResult res = bench(ins[0], ins[1], vjobs, props);
- System.err.println(res);
+ //System.err.println(res.plan);
if (out != null) {
out.println(res.toRaw());
} else {
System.out.println(res.toString());
}
}
} finally {
if (out != null) {
out.close();
}
}
}
public static File storeResource(JobHandler h, String rc, File root) throws Exception {
// String name = rc.substring(rc.lastIndexOf('/') + 1, rc.length());
File f = new File(root + File.separator + rc);
f.getParentFile().mkdirs();
byte[] content = h.getResource(rc);
FileOutputStream out = new FileOutputStream(f);
out.write(content);
out.close();
return f;
}
public static void benchFromServer(String host) throws Exception {
if (host == null) {
fatal("Port and hostname are required");
}
File root = new File("/tmp/" + System.currentTimeMillis());
int port = JobDispatcher.DEFAULT_PORT;
String hostname = host;
if (host.contains(":")) {
port = Integer.parseInt(host.substring(host.indexOf(':') + 1, host.length()));
hostname = host.substring(0, host.indexOf(':'));
}
JobHandler client = new JobHandler(hostname, port, JobHandler.DEFAULT_CACHE_SIZE);
Job j = client.dequeue();
List<File> fs = null;
File incl = null;
while (j != null) {
File fSrc = storeResource(client, PlanJob.getSrcConfigPath(j), root);
File fDst = storeResource(client, PlanJob.getDstConfigPath(j), root);
Configuration src = FileConfigurationSerializerFactory.getInstance().read(fSrc.getPath());
Configuration dst = FileConfigurationSerializerFactory.getInstance().read(fDst.getPath());
Plan.logger.debug("Source conf is " + fSrc.getPath() + "; dst is " + fDst.getPath());
File f = storeResource(client, PlanJob.getPropertiesPath(j), root);
PropertiesHelper props = new PropertiesHelper(f.getPath());
if (fs == null) {
List<String> paths = PlanJob.getVJobPaths(j);
fs = store(client, paths, root);
incl = new File(root.getPath() + File.separator + j.get("incl"));
incl.deleteOnExit();
}
List<VJob> vjobs = getVJobs(src, incl, fs);
Plan.logger.debug("vjobs incl= " + incl.getPath() + " size=" + vjobs.size());
BenchResult res = bench(src, dst, vjobs, props);
res.id = Integer.toString(j.getId());
PlanJob.setMetrics(j, res.toRaw());
File fout = File.createTempFile("foo", "bar");
if (res.plan != null) {
PlainTextTimedReconfigurationPlanSerializer.getInstance().write(res.plan, fout.getPath());
PlanJob.setResultingPlan(j, readContent(fout));
}
client.commit(j);
j = client.dequeue();
}
}
public static BenchResult bench(Configuration src, Configuration dst, List<VJob> vjobs, PropertiesHelper props) throws Exception {
int timeout = props.getRequiredPropertyAsInt("controlLoop.custom.planTimeout");
boolean useRepair = props.getRequiredPropertyAsBoolean("controlLoop.custom.repair");
DurationEvaluator ev = FastDurationEvaluatorFactory.readFromProperties(props);
CustomizableSplitablePlannerModule.PartitioningMode pMode;
pMode = CustomizableSplitablePlannerModule.PartitioningMode.valueOf(props.getRequiredProperty("controlLoop.custom.partitioningMode"));
ReconfigurationProblemBench bench = new ReconfigurationProblemBench(ev, timeout, useRepair, pMode);
bench.doOptimize(false);
return bench.bench(src, dst, vjobs);
}
private static List<File> store(JobHandler client, List<String> rcs, File root) throws Exception {
List<File> files = new ArrayList<File>(rcs.size());
for (String rc : rcs) {
files.add(storeResource(client, rc, root));
}
return files;
}
public static List<VJob> getVJobs(Configuration cfg, File root, List<File> vJobPaths) throws Exception {
BtrPlaceVJobBuilder b = makeVJobBuilder();
PathBasedIncludes incls = new PathBasedIncludes(b, root);
b.setIncludes(incls);
List<VJob> vJobs = new ArrayList<VJob>();
b.getElementBuilder().useConfiguration(cfg);
ManagedElementSet<VirtualMachine> readed = new SimpleManagedElementSet<VirtualMachine>();
for (File path : vJobPaths) {
VJob v = b.build(path);
readed.addAll(v.getVirtualMachines());
vJobs.add(v);
}
return vJobs;
}
public static List<File> listFiles(String root, boolean recursive) {
List<File> res = new ArrayList<File>();
if (root != null) {
File f = new File(root);
if (f.exists() && f.isDirectory()) {
for (File c : f.listFiles()) {
if (c.isFile()) {
res.add(c);
} else if (recursive && c.isDirectory()) {
res.addAll(listFiles(c.getPath(), true));
}
}
}
}
return res;
}
public static String readContent(File f) throws IOException {
BufferedReader in = null;
StringBuilder b = new StringBuilder();
try {
in = new BufferedReader(new FileReader(f));
String line = in.readLine();
while (line != null) {
b.append(line).append('\n');
line = in.readLine();
}
} finally {
if (in != null) {
in.close();
}
}
return b.toString();
}
private static void fatal(String msg) {
System.err.println(msg);
System.exit(1);
}
public static BtrPlaceVJobBuilder makeVJobBuilder() throws Exception {
DefaultVirtualMachineTemplateFactory tplFactory = new DefaultVirtualMachineTemplateFactory();
int[] cpu = {30, 40, 50, 60};
int[] mem = {100, 200, 300};
for (int c : cpu) {
for (int m : mem) {
StubVirtualMachineTemplate st = new StubVirtualMachineTemplate("c" + c + "m" + m, 1, c, m, new THashSet<String>());
tplFactory.add(st);
}
}
VJobElementBuilder eb = new DefaultVJobElementBuilder(tplFactory);
ConstraintsCatalog cat = new ConstraintsCatalogBuilderFromProperties(new PropertiesHelper("config/btrpVjobs.properties")).build();
return new BtrPlaceVJobBuilder(eb, cat, 5000);
}
public static void usage() {
System.out.println("A tool to bench the plan module. Available operation modes:");
System.out.println("microBenchHandler -s server:port");
System.out.println("\tGet the instances to test from a server and send its result\n");
System.out.println("microBenchHandler -props properties -cfgs (cfg1,cfg2|cfg_path) (-vjobs path) (-o output)");
System.out.println("\t read the initial and an optional configuration, an optional folder containing vjobs");
}
}
| true | true | private static void benchInstance(String propsF, String configsPath, String vPath, String output) throws Exception {
if (propsF == null || !new File(propsF).isFile()) {
fatal("the properties file must be an existing file. Currently: '" + propsF + "'");
}
PropertiesHelper props = new PropertiesHelper(propsF);
List<Configuration[]> configs = new ArrayList<Configuration[]>();
List<VJob> vjobs = null;
if (!configsPath.contains(",")) {
File base = new File(configsPath);
for (File f : base.listFiles()) {
if (f.isFile()) {
Configuration src = null;
Configuration dst = null;
String name = f.getName().substring(0, f.getName().lastIndexOf('.'));
String parent = f.getParent();
if (name.endsWith("-src")) {
src = FileConfigurationSerializerFactory.getInstance().read(f.getPath());
dst = FileConfigurationSerializerFactory.getInstance().read(parent + name.substring(0, name.length() - 4) + "-dst.pbd");
}
configs.add(new Configuration[]{src, dst});
}
}
} else {
String srcP, dstP;
String[] tokens = configsPath.split(",");
srcP = tokens[0];
dstP = tokens[1];
Configuration src = FileConfigurationSerializerFactory.getInstance().read(srcP);
Configuration dst = FileConfigurationSerializerFactory.getInstance().read(dstP);
configs.add(new Configuration[]{src, dst});
}
vjobs = getVJobs(configs.get(0)[0], new File(vPath), listFiles(vPath, true));
PrintWriter out = null;
try {
if (output != null) {
out = new PrintWriter(output);
}
for (Configuration[] ins : configs) {
BenchResult res = bench(ins[0], ins[1], vjobs, props);
System.err.println(res);
if (out != null) {
out.println(res.toRaw());
} else {
System.out.println(res.toString());
}
}
} finally {
if (out != null) {
out.close();
}
}
}
| private static void benchInstance(String propsF, String configsPath, String vPath, String output) throws Exception {
if (propsF == null || !new File(propsF).isFile()) {
fatal("the properties file must be an existing file. Currently: '" + propsF + "'");
}
PropertiesHelper props = new PropertiesHelper(propsF);
List<Configuration[]> configs = new ArrayList<Configuration[]>();
List<VJob> vjobs = null;
if (!configsPath.contains(",")) {
File base = new File(configsPath);
for (File f : base.listFiles()) {
if (f.isFile()) {
Configuration src = null;
Configuration dst = null;
String name = f.getName().substring(0, f.getName().lastIndexOf('.'));
String parent = f.getParent();
if (name.endsWith("-src")) {
src = FileConfigurationSerializerFactory.getInstance().read(f.getPath());
dst = FileConfigurationSerializerFactory.getInstance().read(parent + name.substring(0, name.length() - 4) + "-dst.pbd");
}
configs.add(new Configuration[]{src, dst});
}
}
} else {
String srcP, dstP;
String[] tokens = configsPath.split(",");
srcP = tokens[0];
dstP = tokens[1];
Configuration src = FileConfigurationSerializerFactory.getInstance().read(srcP);
Configuration dst = FileConfigurationSerializerFactory.getInstance().read(dstP);
configs.add(new Configuration[]{src, dst});
}
vjobs = getVJobs(configs.get(0)[0], new File(vPath), listFiles(vPath, true));
PrintWriter out = null;
try {
if (output != null) {
out = new PrintWriter(output);
}
for (Configuration[] ins : configs) {
BenchResult res = bench(ins[0], ins[1], vjobs, props);
//System.err.println(res.plan);
if (out != null) {
out.println(res.toRaw());
} else {
System.out.println(res.toString());
}
}
} finally {
if (out != null) {
out.close();
}
}
}
|
diff --git a/tests/src/org/ohmage/activity/test/ResponseListTest.java b/tests/src/org/ohmage/activity/test/ResponseListTest.java
index 665d9cd..4697312 100644
--- a/tests/src/org/ohmage/activity/test/ResponseListTest.java
+++ b/tests/src/org/ohmage/activity/test/ResponseListTest.java
@@ -1,257 +1,259 @@
/*******************************************************************************
* Copyright 2011 The Regents of the University of California
*
* 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.ohmage.activity.test;
import com.jayway.android.robotium.solo.Solo;
import org.ohmage.OhmageApplication;
import org.ohmage.activity.DashboardActivity;
import org.ohmage.activity.ResponseInfoActivity;
import org.ohmage.activity.ResponseListActivity;
import org.ohmage.db.DbContract;
import org.ohmage.db.DbContract.Campaigns;
import org.ohmage.db.Models.Campaign;
import org.ohmage.db.Models.Response;
import org.ohmage.db.Models.Survey;
import org.ohmage.db.test.CampaignCursor;
import org.ohmage.db.test.DelegatingMockContentProvider;
import org.ohmage.db.test.EmptyMockCursor;
import org.ohmage.db.test.OhmageUriMatcher;
import org.ohmage.db.test.ResponseCursor;
import org.ohmage.db.test.SurveyCursor;
import android.content.ContentUris;
import android.database.Cursor;
import android.net.Uri;
import android.test.ActivityInstrumentationTestCase2;
import android.test.mock.MockContentResolver;
import android.text.format.DateUtils;
import java.util.Calendar;
/**
* <p>This class contains tests for the {@link ResponseListActivity}</p>
*
* <h2>The data passed by the content provider</h2>
* <p>for campaigns is always 4 Campaigns with name=Campaign #X and urn=urn:campaign:X</p>
*
* for surveys
* <ul>
* <li>4 Surveys with title=Survey #X and id=Survey #X for all surveys except for Campaign #1</li>
* <li>4 Surveys with title=Campaign 1 S#X for all surveys for Campaign #1</li>
* </ul>
*
* for responses
* <ul>
* <li>8 responses with the first response having no location</li>
* <li>4 responses with the time of today, yesterday, the day before that and the day before that for Campaign #2</li>
* <li>2 responses with the time of today, and yesterday for Campaign #2 with Survey #2</li>
* <li>0 responses for Campaign #3</li>
* </ul>
*
* @author cketcham
*
*/
public class ResponseListTest extends ActivityInstrumentationTestCase2<ResponseListActivity> {
private Solo solo;
private DelegatingMockContentProvider provider;
private final Calendar today = Calendar.getInstance();
private String mLastResponseSelection;
Campaign[] campaigns = new Campaign[4];
{
for(int i=0; i< campaigns.length; i++) {
campaigns[i] = new Campaign();
campaigns[i].mName = "Campaign #" + i;
campaigns[i].mUrn = "urn:campaign:" + i;
}
}
Survey[] surveys = new Survey[4];
{
for(int i=0; i< surveys.length; i++) {
surveys[i] = new Survey();
surveys[i].mTitle = "Survey #" + i;
surveys[i].mSurveyID = "Survey #" + i;
}
}
/** Surveys specifically for Campaign #1 */
Survey[] surveys1 = new Survey[4];
{
for(int i=0; i< surveys.length; i++) {
surveys1[i] = new Survey();
surveys1[i].mTitle = "Campaign 1 S#" + i;
}
}
Response[] responses = new Response[12];
{
for(int i=0; i< responses.length; i++) {
responses[i] = new Response();
responses[i].time = today.getTimeInMillis() - DateUtils.DAY_IN_MILLIS * i;
responses[i].status = statuses[i%statuses.length];
}
}
static int[] statuses = new int[] {
Response.STATUS_DOWNLOADED,
Response.STATUS_QUEUED,
Response.STATUS_STANDBY,
Response.STATUS_UPLOADED,
Response.STATUS_UPLOADING,
Response.STATUS_WAITING_FOR_LOCATION,
Response.STATUS_ERROR_AUTHENTICATION,
Response.STATUS_ERROR_CAMPAIGN_NO_EXIST,
Response.STATUS_ERROR_CAMPAIGN_OUT_OF_DATE,
Response.STATUS_ERROR_CAMPAIGN_STOPPED,
Response.STATUS_ERROR_HTTP,
Response.STATUS_ERROR_INVALID_USER_ROLE,
Response.STATUS_ERROR_OTHER,
};
/** responses specifically for Campaign #2 */
Response[] responses2 = new Response[2];
{
for(int i=0; i< responses2.length; i++) {
responses2[i] = new Response();
responses2[i].time = Calendar.getInstance().getTimeInMillis() - DateUtils.DAY_IN_MILLIS * i;
}
}
/** responses specifically for Survey #2 */
Response[] responses4 = new Response[4];
{
for(int i=0; i< responses4.length; i++) {
responses4[i] = new Response();
responses4[i].time = Calendar.getInstance().getTimeInMillis() - DateUtils.DAY_IN_MILLIS * i;
}
}
public ResponseListTest() {
super(ResponseListActivity.class);
}
@Override
protected void setUp() throws Exception {
super.setUp();
getInstrumentation().waitForIdleSync();
MockContentResolver fake = new MockContentResolver();
provider = new DelegatingMockContentProvider(OhmageApplication.getContext(), DbContract.CONTENT_AUTHORITY) {
@Override
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
switch(OhmageUriMatcher.getMatcher().match(uri)) {
case OhmageUriMatcher.CAMPAIGNS:
return new CampaignCursor(projection, campaigns);
case OhmageUriMatcher.CAMPAIGN_SURVEYS:
if(Campaigns.getCampaignUrn(uri).equals("urn:campaign:1"))
return new SurveyCursor(projection, surveys1);
return new SurveyCursor(projection, surveys);
case OhmageUriMatcher.RESPONSES:
mLastResponseSelection = selection;
if(selectionArgs != null && selectionArgs.length > 0) {
if(selectionArgs[0].equals("urn:campaign:2")) {
if(selectionArgs.length > 1 && selectionArgs[1].equals("Survey #2"))
return new ResponseCursor(projection, responses2);
return new ResponseCursor(projection, responses4);
} else if(selectionArgs[0].contains("urn:campaign:3")) {
return new EmptyMockCursor();
}
}
return new ResponseCursor(projection, responses);
+ case OhmageUriMatcher.RESPONSE_BY_PID:
+ return new ResponseCursor(projection);
default:
return new EmptyMockCursor();
}
}
};
provider.addToContentResolver(fake);
OhmageApplication.setFakeContentResolver(fake);
solo = new Solo(getInstrumentation(), getActivity());
}
@Override
protected void tearDown() throws Exception{
try {
solo.finalize();
} catch (Throwable e) {
e.printStackTrace();
}
getActivity().finish();
super.tearDown();
}
public void testPreconditions() {
solo.assertCurrentActivity("expected response list", ResponseListActivity.class);
}
public void testHomeButton() {
solo.clickOnImageButton(0);
solo.assertCurrentActivity("Expected Dashboard", DashboardActivity.class);
solo.goBack();
}
public void testResponsesWithCorrectStateAreDisplayed() {
// All statuses are shown so we should not see a selection with status in it
assertFalse(mLastResponseSelection.contains("status"));
}
public void testListItemInfoIsCorrect() {
assertTrue(solo.searchText("^Survey Title$"));
assertTrue(solo.searchText("^Campaign Name$"));
assertTrue(solo.searchText(DateUtils.formatDateTime(getActivity(), today.getTimeInMillis(), DateUtils.FORMAT_NUMERIC_DATE)));
assertTrue(solo.searchText(DateUtils.formatDateTime(getActivity(), today.getTimeInMillis(), DateUtils.FORMAT_SHOW_TIME)));
assertTrue(solo.searchText("^\\d{1,2}:\\d{1,2}(am|pm)"));
}
public void testClickListItem() {
solo.clickOnText("Survey Title");
solo.assertCurrentActivity("Expected Response Info", ResponseInfoActivity.class);
assertEquals(0, ContentUris.parseId(solo.getCurrentActivity().getIntent().getData()));
solo.goBack();
}
public void testEmptyList() {
solo.clickOnText("All Campaigns");
solo.clickOnText("Campaign #3");
assertTrue(solo.searchText("^No responses$"));
}
public void testFilterAll() {
solo.searchText("Survey Title");
assertEquals(responses.length, solo.getCurrentListViews().get(0).getCount());
}
public void testFilterWithCampaign() {
solo.clickOnText("All Campaigns");
solo.clickOnText("Campaign #2");
solo.searchText("Survey Title");
assertEquals(responses4.length, solo.getCurrentListViews().get(0).getCount());
}
public void testFilterWithCampaignAndSurvey() {
solo.clickOnText("All Campaigns");
solo.clickOnText("Campaign #2");
solo.clickOnText("All Surveys");
solo.clickOnText("Survey #2");
solo.searchText("Survey Title");
assertEquals(responses2.length, solo.getCurrentListViews().get(0).getCount());
}
}
| true | true | protected void setUp() throws Exception {
super.setUp();
getInstrumentation().waitForIdleSync();
MockContentResolver fake = new MockContentResolver();
provider = new DelegatingMockContentProvider(OhmageApplication.getContext(), DbContract.CONTENT_AUTHORITY) {
@Override
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
switch(OhmageUriMatcher.getMatcher().match(uri)) {
case OhmageUriMatcher.CAMPAIGNS:
return new CampaignCursor(projection, campaigns);
case OhmageUriMatcher.CAMPAIGN_SURVEYS:
if(Campaigns.getCampaignUrn(uri).equals("urn:campaign:1"))
return new SurveyCursor(projection, surveys1);
return new SurveyCursor(projection, surveys);
case OhmageUriMatcher.RESPONSES:
mLastResponseSelection = selection;
if(selectionArgs != null && selectionArgs.length > 0) {
if(selectionArgs[0].equals("urn:campaign:2")) {
if(selectionArgs.length > 1 && selectionArgs[1].equals("Survey #2"))
return new ResponseCursor(projection, responses2);
return new ResponseCursor(projection, responses4);
} else if(selectionArgs[0].contains("urn:campaign:3")) {
return new EmptyMockCursor();
}
}
return new ResponseCursor(projection, responses);
default:
return new EmptyMockCursor();
}
}
};
provider.addToContentResolver(fake);
OhmageApplication.setFakeContentResolver(fake);
solo = new Solo(getInstrumentation(), getActivity());
}
| protected void setUp() throws Exception {
super.setUp();
getInstrumentation().waitForIdleSync();
MockContentResolver fake = new MockContentResolver();
provider = new DelegatingMockContentProvider(OhmageApplication.getContext(), DbContract.CONTENT_AUTHORITY) {
@Override
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
switch(OhmageUriMatcher.getMatcher().match(uri)) {
case OhmageUriMatcher.CAMPAIGNS:
return new CampaignCursor(projection, campaigns);
case OhmageUriMatcher.CAMPAIGN_SURVEYS:
if(Campaigns.getCampaignUrn(uri).equals("urn:campaign:1"))
return new SurveyCursor(projection, surveys1);
return new SurveyCursor(projection, surveys);
case OhmageUriMatcher.RESPONSES:
mLastResponseSelection = selection;
if(selectionArgs != null && selectionArgs.length > 0) {
if(selectionArgs[0].equals("urn:campaign:2")) {
if(selectionArgs.length > 1 && selectionArgs[1].equals("Survey #2"))
return new ResponseCursor(projection, responses2);
return new ResponseCursor(projection, responses4);
} else if(selectionArgs[0].contains("urn:campaign:3")) {
return new EmptyMockCursor();
}
}
return new ResponseCursor(projection, responses);
case OhmageUriMatcher.RESPONSE_BY_PID:
return new ResponseCursor(projection);
default:
return new EmptyMockCursor();
}
}
};
provider.addToContentResolver(fake);
OhmageApplication.setFakeContentResolver(fake);
solo = new Solo(getInstrumentation(), getActivity());
}
|
diff --git a/nuts-and-bolts/src/main/java/ru/hh/nab/health/limits/SimpleLimit.java b/nuts-and-bolts/src/main/java/ru/hh/nab/health/limits/SimpleLimit.java
index 07ae184..72ec401 100644
--- a/nuts-and-bolts/src/main/java/ru/hh/nab/health/limits/SimpleLimit.java
+++ b/nuts-and-bolts/src/main/java/ru/hh/nab/health/limits/SimpleLimit.java
@@ -1,71 +1,71 @@
package ru.hh.nab.health.limits;
import java.util.concurrent.atomic.AtomicInteger;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ru.hh.nab.health.monitoring.LoggingContext;
public class SimpleLimit implements Limit {
private final int max;
private final AtomicInteger current = new AtomicInteger(0);
private final LeakDetector detector;
private final String name;
private final int warnThreshold;
private final static Logger LOGGER = LoggerFactory.getLogger(SimpleLimit.class);
public SimpleLimit(int max, LeakDetector leakDetector, String name, int warnThreshold) {
this.max = max;
this.detector = leakDetector;
this.name = name;
this.warnThreshold = warnThreshold;
}
@Override
public LeaseToken acquire() {
final LoggingContext lc = LoggingContext.fromCurrentContext();
if (current.incrementAndGet() > max) {
current.decrementAndGet();
LOGGER.warn("acquired,limit:{},token:-,max,current:{}", name, current);
return null;
}
- final boolean needWarn = current.get() < warnThreshold;
+ final boolean needWarn = current.get() >= warnThreshold;
LeaseToken token = new LeaseToken() {
@Override
public void release() {
detector.released(this);
current.decrementAndGet();
lc.enter();
log(needWarn, "released,limit:{},token:{},ok,current:{}", objects(name, hashCode(), current));
lc.leave();
}
};
detector.acquired(token);
log(needWarn, "acquired,limit:{},token:{},ok,current:{}", objects(name, token.hashCode(), current));
return token;
}
private void log(boolean needWarn, String msg, Object[] argArray) {
if (needWarn) {
LOGGER.warn(msg, argArray);
} else {
LOGGER.debug(msg, argArray);
}
}
@Override
public int getMax() {
return max;
}
@Override
public String getName() {
return name;
}
private static Object[] objects(Object... args) {
return args;
}
}
| true | true | public LeaseToken acquire() {
final LoggingContext lc = LoggingContext.fromCurrentContext();
if (current.incrementAndGet() > max) {
current.decrementAndGet();
LOGGER.warn("acquired,limit:{},token:-,max,current:{}", name, current);
return null;
}
final boolean needWarn = current.get() < warnThreshold;
LeaseToken token = new LeaseToken() {
@Override
public void release() {
detector.released(this);
current.decrementAndGet();
lc.enter();
log(needWarn, "released,limit:{},token:{},ok,current:{}", objects(name, hashCode(), current));
lc.leave();
}
};
detector.acquired(token);
log(needWarn, "acquired,limit:{},token:{},ok,current:{}", objects(name, token.hashCode(), current));
return token;
}
| public LeaseToken acquire() {
final LoggingContext lc = LoggingContext.fromCurrentContext();
if (current.incrementAndGet() > max) {
current.decrementAndGet();
LOGGER.warn("acquired,limit:{},token:-,max,current:{}", name, current);
return null;
}
final boolean needWarn = current.get() >= warnThreshold;
LeaseToken token = new LeaseToken() {
@Override
public void release() {
detector.released(this);
current.decrementAndGet();
lc.enter();
log(needWarn, "released,limit:{},token:{},ok,current:{}", objects(name, hashCode(), current));
lc.leave();
}
};
detector.acquired(token);
log(needWarn, "acquired,limit:{},token:{},ok,current:{}", objects(name, token.hashCode(), current));
return token;
}
|
diff --git a/src/gwt/src/org/rstudio/studio/client/workbench/views/source/editors/text/AceCompletionAdapter.java b/src/gwt/src/org/rstudio/studio/client/workbench/views/source/editors/text/AceCompletionAdapter.java
index c5abb80918..184bf18ed9 100644
--- a/src/gwt/src/org/rstudio/studio/client/workbench/views/source/editors/text/AceCompletionAdapter.java
+++ b/src/gwt/src/org/rstudio/studio/client/workbench/views/source/editors/text/AceCompletionAdapter.java
@@ -1,71 +1,71 @@
/*
* AceCompletionAdapter.java
*
* Copyright (C) 2009-11 by RStudio, Inc.
*
* This program is licensed to you under the terms of version 3 of the
* GNU Affero General Public License. This program is distributed WITHOUT
* ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
* MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
* AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
*
*/
package org.rstudio.studio.client.workbench.views.source.editors.text;
import com.google.gwt.dom.client.NativeEvent;
import org.rstudio.studio.client.workbench.views.console.shell.assist.CompletionManager;
import org.rstudio.studio.client.workbench.views.source.editors.text.ace.KeyboardHandler;
public class AceCompletionAdapter
{
public AceCompletionAdapter(CompletionManager completionManager)
{
completionManager_ = completionManager;
}
public native final KeyboardHandler getKeyboardHandler() /*-{
var event = $wnd.require("ace/lib/event");
var self = this;
var noop = {command: "null"};
return {
handleKeyboard: $entry(function(data, hashId, keyOrText, keyCode, e) {
- if (hashId != 0 || keyCode != 0) {
+ if (hashId || keyCode) {
if (self.@org.rstudio.studio.client.workbench.views.source.editors.text.AceCompletionAdapter::onKeyDown(Lcom/google/gwt/dom/client/NativeEvent;)(e)) {
event.stopEvent(e);
return noop; // perform a no-op
}
else
return false; // allow default behavior
}
else {
if (self.@org.rstudio.studio.client.workbench.views.source.editors.text.AceCompletionAdapter::onTextInput(Ljava/lang/String;)(keyOrText))
return noop;
else
return false;
}
})
};
}-*/;
private boolean onKeyDown(NativeEvent e)
{
return completionManager_.previewKeyDown(e);
}
private boolean onTextInput(String text)
{
if (text == null)
return false;
// Escape key comes in as a character on desktop builds
if (text.equals("\u001B"))
return true;
for (int i = 0; i < text.length(); i++)
if (completionManager_.previewKeyPress(text.charAt(i)))
return true;
return false;
}
private CompletionManager completionManager_;
}
| true | true | public native final KeyboardHandler getKeyboardHandler() /*-{
var event = $wnd.require("ace/lib/event");
var self = this;
var noop = {command: "null"};
return {
handleKeyboard: $entry(function(data, hashId, keyOrText, keyCode, e) {
if (hashId != 0 || keyCode != 0) {
if (self.@org.rstudio.studio.client.workbench.views.source.editors.text.AceCompletionAdapter::onKeyDown(Lcom/google/gwt/dom/client/NativeEvent;)(e)) {
event.stopEvent(e);
return noop; // perform a no-op
}
else
return false; // allow default behavior
}
else {
if (self.@org.rstudio.studio.client.workbench.views.source.editors.text.AceCompletionAdapter::onTextInput(Ljava/lang/String;)(keyOrText))
return noop;
else
return false;
}
})
};
}-*/;
| public native final KeyboardHandler getKeyboardHandler() /*-{
var event = $wnd.require("ace/lib/event");
var self = this;
var noop = {command: "null"};
return {
handleKeyboard: $entry(function(data, hashId, keyOrText, keyCode, e) {
if (hashId || keyCode) {
if (self.@org.rstudio.studio.client.workbench.views.source.editors.text.AceCompletionAdapter::onKeyDown(Lcom/google/gwt/dom/client/NativeEvent;)(e)) {
event.stopEvent(e);
return noop; // perform a no-op
}
else
return false; // allow default behavior
}
else {
if (self.@org.rstudio.studio.client.workbench.views.source.editors.text.AceCompletionAdapter::onTextInput(Ljava/lang/String;)(keyOrText))
return noop;
else
return false;
}
})
};
}-*/;
|
diff --git a/galileo_openbook_cleaner/src/de/scrum_master/galileo/OpenbookCleaner.java b/galileo_openbook_cleaner/src/de/scrum_master/galileo/OpenbookCleaner.java
index b0293a5..10413e7 100644
--- a/galileo_openbook_cleaner/src/de/scrum_master/galileo/OpenbookCleaner.java
+++ b/galileo_openbook_cleaner/src/de/scrum_master/galileo/OpenbookCleaner.java
@@ -1,209 +1,209 @@
package de.scrum_master.galileo;
import java.io.File;
import java.io.FileFilter;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
import java.io.PrintStream;
import org.xml.sax.SAXException;
import com.sun.org.apache.xalan.internal.xsltc.cmdline.getopt.GetOpt;
import de.scrum_master.galileo.filter.JTidyFilter;
import de.scrum_master.galileo.filter.PreJTidyFilter;
import de.scrum_master.galileo.filter.XOMUnclutterFilter;
import de.scrum_master.util.SimpleLogger;
public class OpenbookCleaner
{
private static File baseDir;
private static BookInfo bookInfo;
private static File[] htmlFiles;
private static boolean SINGLE_THREADED_WITH_INTERMEDIATE_FILES = false;
private final static String USAGE_TEXT =
"Usage: java " + OpenbookCleaner.class.getName() + " [-?] | [options] <book_path>\n\n" +
"Options:\n"+
" -? show this help text\n" +
" -v verbose output\n" +
" -d debug output (implies -v)\n" +
" -s single-threaded mode with intermediate files (for diagnostics)\n\n" +
"Parameters:\n"+
" book_path base path containing the book to be cleaned";
private static final String REGEX_TOC_RUBY = ".*ruby_on_rails.index.htm";
public static void main(String[] args) throws Exception
{
long startTime = System.currentTimeMillis();
processArgs(args);
SimpleLogger.echo("Processing " + baseDir.getName() + "...");
for (File htmlFile : htmlFiles)
cleanHTMLFile(htmlFile);
SimpleLogger.time("Duration for " + baseDir.getName(), System.currentTimeMillis() - startTime);
}
private static void processArgs(String[] args)
{
if (args.length == 0)
displayUsageAndExit(0);
// TODO: GetOpt is poorly documented, hard to use and buggy (getCmdArgs falsely returns options
// if no non-option command-line agrument is given). There are plenty of better free command line
// parsing tools. If it was not for indepencence of yet another external library, I would not use
// JRE's GetOpt.
GetOpt options = new GetOpt(args, "?vds");
try {
int i = options.getNextOption();
while (i != -1) {
SimpleLogger.debug("Option parser: parameter = " + (char) i);
switch ((char) i) {
case '?' :
displayUsageAndExit(0);
break;
case 'v' :
SimpleLogger.VERBOSE = true;
break;
case 'd' :
SimpleLogger.DEBUG= true;
SimpleLogger.VERBOSE = true;
break;
case 's' :
SINGLE_THREADED_WITH_INTERMEDIATE_FILES = true;
break;
}
i = options.getNextOption();
}
baseDir = new File(options.getCmdArgs()[0]);
SimpleLogger.debug("Option parser: book_path = " + baseDir);
// Check if given name corresponds to any predefined BookInfo
try {
bookInfo = BookInfo.valueOf(baseDir.getName().toUpperCase());
}
catch (IllegalArgumentException e) {
- displayUsageAndExit(1, "book_path " + e.getMessage().replaceFirst(".*[.]", "") + " not found.");
+ displayUsageAndExit(1, "illegal book_path " + e.getMessage().replaceFirst(".*[.]", "").toLowerCase());
}
if (! baseDir.isDirectory())
displayUsageAndExit(1, "book base directory '" + baseDir + "' not found\n");
}
catch (Exception e) {
displayUsageAndExit(1);
}
htmlFiles = baseDir.listFiles(
new FileFilter() {
public boolean accept(File file) {
String fileNameLC = file.getName().toLowerCase();
return fileNameLC.endsWith(".htm") || fileNameLC.endsWith(".html");
//return fileNameLC.endsWith("apps_06_005.html");
//return fileNameLC.endsWith("node429.html");
//return fileNameLC.endsWith("index.htm") || fileNameLC.endsWith("index.html");
}
}
);
}
private static void displayUsageAndExit(int exitCode)
{
displayUsageAndExit(exitCode, null);
}
private static void displayUsageAndExit(int exitCode, String errorMessage)
{
PrintStream out = (exitCode == 0) ? System.out : System.err;
out.println(
USAGE_TEXT + "\n\n" +
"List of legal book_path values (case-insensitive):"
);
for (BookInfo md : BookInfo.values())
out.println(" " + md.name().toLowerCase());
if (exitCode != 0 && errorMessage != null)
out.println("\nError: " + errorMessage);
System.exit(exitCode);
}
private static void cleanHTMLFile(File origFile) throws Exception
{
File backupFile = new File(origFile + ".bak");
SimpleLogger.verbose(" " + origFile.getName());
// Backups are useful if we want to re-run the application later
createBackupIfNotExists(origFile, backupFile);
doConversion(origFile, new FileInputStream(backupFile), new FileOutputStream(origFile));
}
private static void createBackupIfNotExists(File origFile, File backupFile)
throws IOException
{
if (!backupFile.exists())
origFile.renameTo(backupFile);
}
private static void doConversion(File origFile, InputStream rawInput, OutputStream finalOutput)
throws FileNotFoundException, SAXException, IOException
{
// Conversion steps for both modes (single-/multi-threaded):
// 1. Clean up raw HTML where necessary to make it parseable by JTidy
// 2. Convert raw HTML into valid XHTML using JTidy
// 3. Remove clutter (header, footer, navigation, ads) using XOM
// 4. Pretty-print XOM output again using JTidy (optional)
final boolean needsPreJTidy = origFile.getAbsolutePath().matches(REGEX_TOC_RUBY) ? true : false;
if (SINGLE_THREADED_WITH_INTERMEDIATE_FILES) {
// Single-threaded mode is slower (~40%), but good for diagnostic purposes:
// - It creates files for each intermediate processing step.
// - Log output is in (chrono)logical order.
// Set up intermediate files
File preJTidyFile = new File(origFile + ".pretidy");
File jTidyFile = new File(origFile + ".tidy");
File xomFile = new File(origFile + ".xom");
// Run conversion steps, using output of step (n) as input of step (n+1)
if (needsPreJTidy) {
new PreJTidyFilter(rawInput, new FileOutputStream(preJTidyFile), origFile).run();
new JTidyFilter(new FileInputStream(preJTidyFile), new FileOutputStream(jTidyFile), origFile).run();
}
else {
new JTidyFilter(rawInput, new FileOutputStream(jTidyFile), origFile).run();
}
new XOMUnclutterFilter(new FileInputStream(jTidyFile), new FileOutputStream(xomFile), origFile).run();
new JTidyFilter(new FileInputStream(xomFile), finalOutput, origFile).run();
}
else {
// Multi-threaded mode is faster, but not so good for diagnostic purposes:
// - There are no files for intermediate processing steps.
// - Log output is garbled because of multi-threading.
// Set up pipes
PipedOutputStream preJTidyOutput = new PipedOutputStream();
PipedInputStream preJTidyInput = new PipedInputStream(preJTidyOutput);
PipedOutputStream jTidyOutput = new PipedOutputStream();
PipedInputStream jTidyInput = new PipedInputStream(jTidyOutput);
PipedOutputStream unclutteredOutput = new PipedOutputStream();
PipedInputStream unclutteredInput = new PipedInputStream(unclutteredOutput);
// Run threads, piping output of thread (n) into input of thread (n+1)
if (needsPreJTidy) {
new Thread(new PreJTidyFilter(rawInput, preJTidyOutput, origFile)).start();
new Thread(new JTidyFilter(preJTidyInput, jTidyOutput, origFile)).start();
}
else {
new Thread(new JTidyFilter(rawInput, jTidyOutput, origFile)).start();
}
new Thread (new XOMUnclutterFilter(jTidyInput, unclutteredOutput, origFile)).start();
new Thread (new JTidyFilter(unclutteredInput, finalOutput, origFile)).start();
}
}
}
| true | true | private static void processArgs(String[] args)
{
if (args.length == 0)
displayUsageAndExit(0);
// TODO: GetOpt is poorly documented, hard to use and buggy (getCmdArgs falsely returns options
// if no non-option command-line agrument is given). There are plenty of better free command line
// parsing tools. If it was not for indepencence of yet another external library, I would not use
// JRE's GetOpt.
GetOpt options = new GetOpt(args, "?vds");
try {
int i = options.getNextOption();
while (i != -1) {
SimpleLogger.debug("Option parser: parameter = " + (char) i);
switch ((char) i) {
case '?' :
displayUsageAndExit(0);
break;
case 'v' :
SimpleLogger.VERBOSE = true;
break;
case 'd' :
SimpleLogger.DEBUG= true;
SimpleLogger.VERBOSE = true;
break;
case 's' :
SINGLE_THREADED_WITH_INTERMEDIATE_FILES = true;
break;
}
i = options.getNextOption();
}
baseDir = new File(options.getCmdArgs()[0]);
SimpleLogger.debug("Option parser: book_path = " + baseDir);
// Check if given name corresponds to any predefined BookInfo
try {
bookInfo = BookInfo.valueOf(baseDir.getName().toUpperCase());
}
catch (IllegalArgumentException e) {
displayUsageAndExit(1, "book_path " + e.getMessage().replaceFirst(".*[.]", "") + " not found.");
}
if (! baseDir.isDirectory())
displayUsageAndExit(1, "book base directory '" + baseDir + "' not found\n");
}
catch (Exception e) {
displayUsageAndExit(1);
}
htmlFiles = baseDir.listFiles(
new FileFilter() {
public boolean accept(File file) {
String fileNameLC = file.getName().toLowerCase();
return fileNameLC.endsWith(".htm") || fileNameLC.endsWith(".html");
//return fileNameLC.endsWith("apps_06_005.html");
//return fileNameLC.endsWith("node429.html");
//return fileNameLC.endsWith("index.htm") || fileNameLC.endsWith("index.html");
}
}
);
}
| private static void processArgs(String[] args)
{
if (args.length == 0)
displayUsageAndExit(0);
// TODO: GetOpt is poorly documented, hard to use and buggy (getCmdArgs falsely returns options
// if no non-option command-line agrument is given). There are plenty of better free command line
// parsing tools. If it was not for indepencence of yet another external library, I would not use
// JRE's GetOpt.
GetOpt options = new GetOpt(args, "?vds");
try {
int i = options.getNextOption();
while (i != -1) {
SimpleLogger.debug("Option parser: parameter = " + (char) i);
switch ((char) i) {
case '?' :
displayUsageAndExit(0);
break;
case 'v' :
SimpleLogger.VERBOSE = true;
break;
case 'd' :
SimpleLogger.DEBUG= true;
SimpleLogger.VERBOSE = true;
break;
case 's' :
SINGLE_THREADED_WITH_INTERMEDIATE_FILES = true;
break;
}
i = options.getNextOption();
}
baseDir = new File(options.getCmdArgs()[0]);
SimpleLogger.debug("Option parser: book_path = " + baseDir);
// Check if given name corresponds to any predefined BookInfo
try {
bookInfo = BookInfo.valueOf(baseDir.getName().toUpperCase());
}
catch (IllegalArgumentException e) {
displayUsageAndExit(1, "illegal book_path " + e.getMessage().replaceFirst(".*[.]", "").toLowerCase());
}
if (! baseDir.isDirectory())
displayUsageAndExit(1, "book base directory '" + baseDir + "' not found\n");
}
catch (Exception e) {
displayUsageAndExit(1);
}
htmlFiles = baseDir.listFiles(
new FileFilter() {
public boolean accept(File file) {
String fileNameLC = file.getName().toLowerCase();
return fileNameLC.endsWith(".htm") || fileNameLC.endsWith(".html");
//return fileNameLC.endsWith("apps_06_005.html");
//return fileNameLC.endsWith("node429.html");
//return fileNameLC.endsWith("index.htm") || fileNameLC.endsWith("index.html");
}
}
);
}
|
diff --git a/src/com/dzebsu/acctrip/settings/dialogs/BackupViaEmailDialogPreference.java b/src/com/dzebsu/acctrip/settings/dialogs/BackupViaEmailDialogPreference.java
index df88b0c..eed5462 100644
--- a/src/com/dzebsu/acctrip/settings/dialogs/BackupViaEmailDialogPreference.java
+++ b/src/com/dzebsu/acctrip/settings/dialogs/BackupViaEmailDialogPreference.java
@@ -1,44 +1,44 @@
package com.dzebsu.acctrip.settings.dialogs;
import java.util.Calendar;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences.Editor;
import android.net.Uri;
import android.text.format.DateFormat;
import android.util.AttributeSet;
import com.dzebsu.acctrip.R;
public class BackupViaEmailDialogPreference extends BaseBackupConfirmDialogPreference {
private static final String KEY_DEVICE_BACKUP = "pref_backup_device_last";
public BackupViaEmailDialogPreference(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
protected Integer performConfirmedAction() {
Intent sendIntent = new Intent(Intent.ACTION_SEND);
sendIntent.setType("plain/text");
sendIntent.putExtra(Intent.EXTRA_SUBJECT, cxt.getString(R.string.backup_subject));
String s = makeBackupDBToDeviceExternalMemory();
Editor ed = findPreferenceInHierarchy(KEY_DEVICE_BACKUP).getEditor();
ed.putString(KEY_DEVICE_BACKUP, DateFormat.format("dd/MM/yy", Calendar.getInstance()).toString() + "@" + s);
ed.commit();
try {
- sendIntent.putExtra(Intent.EXTRA_STREAM, Uri.parse(s));
+ sendIntent.putExtra(Intent.EXTRA_STREAM, Uri.parse("file:" + s));
} catch (Exception e) {
return null;
}
sendIntent.putExtra(Intent.EXTRA_TEXT, cxt.getString(R.string.backup_text));
Editor ed2 = this.getEditor();
ed2.putString(this.getKey(), DateFormat.format("dd/MM/yy", Calendar.getInstance()).toString());
ed2.commit();
cxt.startActivity(Intent.createChooser(sendIntent, "Backup:"));
return R.string.assum_sent;
}
}
| true | true | protected Integer performConfirmedAction() {
Intent sendIntent = new Intent(Intent.ACTION_SEND);
sendIntent.setType("plain/text");
sendIntent.putExtra(Intent.EXTRA_SUBJECT, cxt.getString(R.string.backup_subject));
String s = makeBackupDBToDeviceExternalMemory();
Editor ed = findPreferenceInHierarchy(KEY_DEVICE_BACKUP).getEditor();
ed.putString(KEY_DEVICE_BACKUP, DateFormat.format("dd/MM/yy", Calendar.getInstance()).toString() + "@" + s);
ed.commit();
try {
sendIntent.putExtra(Intent.EXTRA_STREAM, Uri.parse(s));
} catch (Exception e) {
return null;
}
sendIntent.putExtra(Intent.EXTRA_TEXT, cxt.getString(R.string.backup_text));
Editor ed2 = this.getEditor();
ed2.putString(this.getKey(), DateFormat.format("dd/MM/yy", Calendar.getInstance()).toString());
ed2.commit();
cxt.startActivity(Intent.createChooser(sendIntent, "Backup:"));
return R.string.assum_sent;
}
| protected Integer performConfirmedAction() {
Intent sendIntent = new Intent(Intent.ACTION_SEND);
sendIntent.setType("plain/text");
sendIntent.putExtra(Intent.EXTRA_SUBJECT, cxt.getString(R.string.backup_subject));
String s = makeBackupDBToDeviceExternalMemory();
Editor ed = findPreferenceInHierarchy(KEY_DEVICE_BACKUP).getEditor();
ed.putString(KEY_DEVICE_BACKUP, DateFormat.format("dd/MM/yy", Calendar.getInstance()).toString() + "@" + s);
ed.commit();
try {
sendIntent.putExtra(Intent.EXTRA_STREAM, Uri.parse("file:" + s));
} catch (Exception e) {
return null;
}
sendIntent.putExtra(Intent.EXTRA_TEXT, cxt.getString(R.string.backup_text));
Editor ed2 = this.getEditor();
ed2.putString(this.getKey(), DateFormat.format("dd/MM/yy", Calendar.getInstance()).toString());
ed2.commit();
cxt.startActivity(Intent.createChooser(sendIntent, "Backup:"));
return R.string.assum_sent;
}
|
diff --git a/src/client/Client.java b/src/client/Client.java
index e2dfb5a..36e3f13 100644
--- a/src/client/Client.java
+++ b/src/client/Client.java
@@ -1,53 +1,53 @@
package client;
import gui.GUI;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import model.Picture;
public class Client {
private GUI gui;
private Picture picture;
public Client(String host, int port, boolean sendMode) {
Socket s = null;
try {
- if (!sendMode) {
- System.out.println("Listening for connection");
- ServerSocket ss = new ServerSocket(port);
- s = ss.accept();
- System.out.println("Connection accepted");
- } else {
+// if (sendMode) {
+// System.out.println("Listening for connection");
+// ServerSocket ss = new ServerSocket(port);
+// s = ss.accept();
+// System.out.println("Connection accepted");
+// } else {
s = new Socket(host, port);
- }
+// }
} catch (IOException e) {
}
try {
DrawingMonitor monitor = new DrawingMonitor(s.getOutputStream());
picture = new Picture(monitor, sendMode);
gui = new GUI(picture);
new ReceiverThread(picture, s.getInputStream()).start();
new SendThread(monitor).start();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
if (args.length != 3) {
System.exit(1);
}
boolean sendMode = Integer.parseInt(args[2]) == 1;
String s = args[0];
int port = Integer.parseInt(args[1]);
new Client(s, port, sendMode);
}
}
| false | true | public Client(String host, int port, boolean sendMode) {
Socket s = null;
try {
if (!sendMode) {
System.out.println("Listening for connection");
ServerSocket ss = new ServerSocket(port);
s = ss.accept();
System.out.println("Connection accepted");
} else {
s = new Socket(host, port);
}
} catch (IOException e) {
}
try {
DrawingMonitor monitor = new DrawingMonitor(s.getOutputStream());
picture = new Picture(monitor, sendMode);
gui = new GUI(picture);
new ReceiverThread(picture, s.getInputStream()).start();
new SendThread(monitor).start();
} catch (IOException e) {
e.printStackTrace();
}
}
| public Client(String host, int port, boolean sendMode) {
Socket s = null;
try {
// if (sendMode) {
// System.out.println("Listening for connection");
// ServerSocket ss = new ServerSocket(port);
// s = ss.accept();
// System.out.println("Connection accepted");
// } else {
s = new Socket(host, port);
// }
} catch (IOException e) {
}
try {
DrawingMonitor monitor = new DrawingMonitor(s.getOutputStream());
picture = new Picture(monitor, sendMode);
gui = new GUI(picture);
new ReceiverThread(picture, s.getInputStream()).start();
new SendThread(monitor).start();
} catch (IOException e) {
e.printStackTrace();
}
}
|
diff --git a/src/no/ntnu/tdt4215/group7/indexer/ICDIndexer.java b/src/no/ntnu/tdt4215/group7/indexer/ICDIndexer.java
index cce3056..91f544b 100755
--- a/src/no/ntnu/tdt4215/group7/indexer/ICDIndexer.java
+++ b/src/no/ntnu/tdt4215/group7/indexer/ICDIndexer.java
@@ -1,94 +1,94 @@
package no.ntnu.tdt4215.group7.indexer;
import java.io.File;
import java.io.IOException;
import java.util.List;
import no.ntnu.tdt4215.group7.entity.ICD;
import org.apache.lucene.analysis.no.NorwegianAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.FieldType;
import org.apache.lucene.document.StringField;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.util.Version;
/**
* Index icd codes in Lucene
* */
public class ICDIndexer implements Indexer {
/**
* path where to store the index
* */
private String filePath;
/**
* list of icd codes to be indexed
* */
private List<ICD> icds;
public ICDIndexer(String filePath, List<ICD> icds) {
this.filePath = filePath;
this.icds = icds;
}
/*
* Index ICD objects on Lucene
*/
public Directory createIndex() throws IOException {
NorwegianAnalyzer analyzer = new NorwegianAnalyzer(Version.LUCENE_40);
Directory index = FSDirectory.open(new File(filePath)); // disk index
IndexWriterConfig config = new IndexWriterConfig(Version.LUCENE_40, analyzer);
IndexWriter w = new IndexWriter(index, config);
// add ICD codes
for (ICD icd : this.icds) {
this.addICDDoc(w, icd);
}
w.close();
return index;
}
/**
* In the Lucene doc relative to the icd file we index and stem the label
* together with the extra information like synonyms The extra information
* is used for query expansion
**/
private void addICDDoc(IndexWriter w, ICD icd) throws IOException {
String codecompacted = icd.getCode_compacted();
String label = icd.getLabel();
// at the momemnt the extra information is given by the underterm and by
// the synonyms
String extraInformation = icd.getUnderterm();
for (String syn : icd.getSynonyms()) {
extraInformation += " " + syn;
}
Document doc = new Document();
FieldType type = new FieldType();
type.setIndexed(true);
type.setStored(true);
type.setStoreTermVectors(true);
type.setTokenized(true);
Field fieldLabel = new Field("label", label, type);
Field fieldExtra = new Field("extra", label + " " + extraInformation, type);
doc.add(fieldLabel);
// use a string field for because we don't want it tokenized
doc.add(new StringField("code_compacted", codecompacted, Field.Store.YES));
- if (extraInformation != null || !extraInformation.equals("")) {
+ if (extraInformation != null && !extraInformation.equals("")) {
doc.add(fieldExtra);
}
w.addDocument(doc);
}
@Override
public Directory call() throws Exception {
return createIndex();
}
}
| true | true | private void addICDDoc(IndexWriter w, ICD icd) throws IOException {
String codecompacted = icd.getCode_compacted();
String label = icd.getLabel();
// at the momemnt the extra information is given by the underterm and by
// the synonyms
String extraInformation = icd.getUnderterm();
for (String syn : icd.getSynonyms()) {
extraInformation += " " + syn;
}
Document doc = new Document();
FieldType type = new FieldType();
type.setIndexed(true);
type.setStored(true);
type.setStoreTermVectors(true);
type.setTokenized(true);
Field fieldLabel = new Field("label", label, type);
Field fieldExtra = new Field("extra", label + " " + extraInformation, type);
doc.add(fieldLabel);
// use a string field for because we don't want it tokenized
doc.add(new StringField("code_compacted", codecompacted, Field.Store.YES));
if (extraInformation != null || !extraInformation.equals("")) {
doc.add(fieldExtra);
}
w.addDocument(doc);
}
| private void addICDDoc(IndexWriter w, ICD icd) throws IOException {
String codecompacted = icd.getCode_compacted();
String label = icd.getLabel();
// at the momemnt the extra information is given by the underterm and by
// the synonyms
String extraInformation = icd.getUnderterm();
for (String syn : icd.getSynonyms()) {
extraInformation += " " + syn;
}
Document doc = new Document();
FieldType type = new FieldType();
type.setIndexed(true);
type.setStored(true);
type.setStoreTermVectors(true);
type.setTokenized(true);
Field fieldLabel = new Field("label", label, type);
Field fieldExtra = new Field("extra", label + " " + extraInformation, type);
doc.add(fieldLabel);
// use a string field for because we don't want it tokenized
doc.add(new StringField("code_compacted", codecompacted, Field.Store.YES));
if (extraInformation != null && !extraInformation.equals("")) {
doc.add(fieldExtra);
}
w.addDocument(doc);
}
|
diff --git a/kovu/teamstats/api/TeamStatsAPI.java b/kovu/teamstats/api/TeamStatsAPI.java
index ced3aa9..0e822d2 100644
--- a/kovu/teamstats/api/TeamStatsAPI.java
+++ b/kovu/teamstats/api/TeamStatsAPI.java
@@ -1,611 +1,611 @@
package kovu.teamstats.api;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import java.util.logging.Logger;
import kovu.teamstats.api.exception.CreationNotCompleteException;
import kovu.teamstats.api.exception.ServerConnectionLostException;
import kovu.teamstats.api.exception.ServerOutdatedException;
import kovu.teamstats.api.exception.ServerRejectionException;
import kovu.teamstats.api.list.TSAList;
import net.ae97.teamstats.ClientRequest;
import net.ae97.teamstats.networking.Packet;
import net.ae97.teamstats.networking.PacketListener;
import net.ae97.teamstats.networking.PacketSender;
/**
* The TeamStats API class. This handles all the server-related requests. This
* should be used to get info from the server.
*
* @author Lord_Ralex
* @version 0.3
* @since 0.1
*/
public final class TeamStatsAPI {
private static TeamStatsAPI api;
private static final String MAIN_SERVER_URL;
private static final int SERVER_PORT;
private final String name;
private String session;
private Socket connection;
private final PacketListener packetListener;
private final PacketSender packetSender;
private final List<String> friendList = new TSAList<String>();
private final Map<String, Map<String, Object>> friendStats = new ConcurrentHashMap<String, Map<String, Object>>();
private final List<String> friendRequests = new TSAList<String>();
private final UpdaterThread updaterThread = new UpdaterThread();
private final Map<String, Object> stats = new ConcurrentHashMap<String, Object>();
private final List<String> newFriends = new TSAList<String>();
private final List<String> newRequests = new TSAList<String>();
private final List<String> newlyRemovedFriends = new TSAList<String>();
private final List<String> onlineFriends = new TSAList<String>();
private final int UPDATE_TIMER = 60; //time this means is set when sent to executor service
private boolean online = false;
private static final short API_VERSION = 3;
private boolean was_set_up = false;
private final ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor();
private final ScheduledFuture task;
static {
//enter the server url here where the main bouncer is
MAIN_SERVER_URL = "teamstats.ae97.net";
//enter the port the bouncer runs off of here
SERVER_PORT = 19325;
}
public TeamStatsAPI(String aName, String aSession) throws ServerRejectionException, IOException, ClassNotFoundException {
name = aName;
session = aSession;
connection = new Socket(MAIN_SERVER_URL, SERVER_PORT);
PacketSender tempSender = new PacketSender(connection.getOutputStream());
PacketListener tempListener = new PacketListener(connection.getInputStream());
tempListener.start();
Packet getServer = new Packet(ClientRequest.GETSERVER);
tempSender.sendPacket(getServer);
Packet p = tempListener.getNextPacket(ClientRequest.SIMPLEREPLYPACKET);
tempListener.interrupt();
String SERVER_URL = null;
Object o = p.getData("ip");
if (o instanceof String) {
SERVER_URL = (String) o;
}
connection.close();
if (SERVER_URL == null || SERVER_URL.equalsIgnoreCase("NONODE")) {
throw new ServerRejectionException("There is no node open");
}
String link = (String) p.getData("ip");
int port = (Integer) p.getData("port");
short server_version = (Short) p.getData("version");
if (server_version != API_VERSION) {
throw new ServerOutdatedException();
}
connection = new Socket(link, port);
packetListener = new PacketListener(connection.getInputStream());
packetSender = new PacketSender(connection.getOutputStream());
packetListener.start();
Packet pac = new Packet(ClientRequest.OPENCONNECTION);
pac.addData("name", name).addData("session", session);
packetSender.sendPacket(pac);
Packet response = packetListener.getNextPacket(ClientRequest.SIMPLEREPLYPACKET);
boolean isAccepted = (Boolean) response.getData("reply");
if (!isAccepted) {
throw new ServerRejectionException();
}
task = service.scheduleAtFixedRate(updaterThread, UPDATE_TIMER, UPDATE_TIMER, TimeUnit.SECONDS);
online = true;
was_set_up = true;
}
/**
* Gets the stats for each friend that is registered by the server. This can
* throw an IOException if the server rejects the client communication or an
* issue occurs when reading the data.
*
* @return Mapping of friends and their stats
* @throws IOException Thrown when server fails to send data or if server
* rejects communication
*/
public Map<String, Map<String, Object>> getFriendStats() throws IOException {
wasSetup();
return friendStats;
}
/**
* Returns the map's toString form of the friend's stats. THIS IS
* DEPRECATED, REFER TO NOTES FOR NEW METHOD
*
* @param friendName Name of friend
* @return String version of the stats
* @throws IOException
*/
public String getFriendState(String friendName) throws IOException {
wasSetup();
return friendStats.get(friendName).toString();
}
/**
* Gets the stats for a single friend. If the friend requested is not an
* actual friend, this will return null.
*
* @param friendName The friend to get the stats for
* @return The stats in a map
* @throws IOException Thrown when server fails to send data or if server
* rejects communication
*/
public Map<String, Object> getFriendStat(String friendName) throws IOException {
wasSetup();
return friendStats.get(friendName);
}
/**
* Gets the specific value for a certain stat for a friend. The key is the
* stat name.
*
* @param friendName Name of friend
* @param key Key of stat
* @return Value of the friend's key, or null if not one
* @throws IOException
*/
public Object getFriendStat(String friendName, String key) throws IOException {
wasSetup();
key = key.toLowerCase();
Map<String, Object> stat = friendStats.get(friendName);
if (stat == null) {
return null;
} else {
return stat.get(key);
}
}
/**
* Gets all accepted friends.
*
* @return An array of all friends accepted
* @throws IOException Thrown when server fails to send data or if server
* rejects communication
*/
public String[] getFriends() throws IOException {
wasSetup();
return friendList.toArray(new String[0]);
}
/**
* Sends the stats to the server. This will never return false. If the
* connection is rejected, this will throw an IOException.
*
* @param key Key to set
* @param value The value for this key
* @return True if connection was successful.
* @throws IOException Thrown when server fails to send data or if server
* rejects communication
*/
public boolean updateStats(String key, Object value) throws IOException {
wasSetup();
stats.put(key.toLowerCase().trim(), value);
return true;
}
/**
* Sends the stats to the server. This will never return false. If the
* connection is rejected, this will throw an IOException.
*
* @param map Map of values to set
* @return True if connection was successful.
* @throws IOException Thrown when server fails to send data or if server
* rejects communication
*/
public boolean updateStats(Map<String, ? extends Object> map) throws IOException {
for (String key : map.keySet()) {
updateStats(key, map.get(key));
}
return true;
}
/**
* Gets a list of friend requests the user has. This will return names of
* those that want to friend this user.
*
* @return Array of friend requests to the user
* @throws IOException Thrown when server fails to send data or if server
* rejects communication
*/
public String[] getFriendRequests() throws IOException {
wasSetup();
return friendRequests.toArray(new String[0]);
}
/**
* Requests a friend addition. This will not add them, just request that the
* person add them. The return is just for the connection, not for the
* friend request.
*
* @param name Name of friend to add/request
* @return True if request was successful
* @throws IOException Thrown when server fails to send data or if server
* rejects communication
*/
public boolean addFriend(String name) throws IOException {
wasSetup();
return friendList.add(name);
}
/**
* Removes a friend. This will take place once used and any friend list will
* be updated.
*
* @param name Name of friend to remove
* @return True if connection was successful
* @throws IOException Thrown when server fails to send data or if server
* rejects communication
*/
public boolean removeFriend(String name) throws IOException {
wasSetup();
return friendList.remove(name);
}
/**
* Gets the list of new requests to this user. This will also clear the list
* if true is passed.
*
* @param reset Whether to clear the list. True will remove the list after
* returning it.
* @return Names of new friend requests
*/
public String[] getNewFriendRequests(boolean reset) throws IOException {
wasSetup();
String[] newFriendsToReturn = newRequests.toArray(new String[0]);
if (reset) {
newRequests.clear();
}
return newFriendsToReturn;
}
/**
* Gets the list of removed friends to this user. This will also clear the
* list if true is passed.
*
* @param reset Whether to clear the list. True will remove the list after
* returning it.
* @return Names of newly removed friends
*/
public String[] getRemovedFriends(boolean reset) throws IOException {
wasSetup();
String[] newFriendsToReturn = newlyRemovedFriends.toArray(new String[0]);
if (reset) {
newlyRemovedFriends.clear();
}
return newFriendsToReturn;
}
/**
* Gets the list of new friends to this user. This will also clear the list
* if true is passed.
*
* @param reset Whether to clear the list. True will remove the list after
* returning it.
* @return Names of new friends
*/
public String[] getNewFriends(boolean reset) throws IOException {
wasSetup();
String[] newFriendsToReturn = newFriends.toArray(new String[0]);
if (reset) {
newFriends.clear();
}
return newFriendsToReturn;
}
/**
* Gets the list of new requests to this user. This will also clear the
* list.
*
* @return Names of new friend requests
*/
public String[] getNewFriendRequests() throws IOException {
wasSetup();
return getNewFriendRequests(true);
}
/**
* Gets the list of removed friends to this user. This will also clear the
* list.
*
* @return Names of newly removed friends
*/
public String[] getRemovedFriends() throws IOException {
wasSetup();
return getRemovedFriends(true);
}
/**
* Gets the list of new friends to this user. This will also clear the list.
*
* @return Names of new friends
*/
public String[] getNewFriends() throws IOException {
wasSetup();
return getNewFriends(true);
}
/**
* Returns an array of friends that are online based on the cache.
*
* @return Array of friends who are online
*/
public String[] getOnlineFriends() throws IOException {
wasSetup();
return onlineFriends.toArray(new String[0]);
}
/**
* Checks to see if a particular friend is online.
*
* @param name Name of friend
* @return True if they are online, false otherwise
*/
public boolean isFriendOnline(String name) throws IOException {
wasSetup();
return onlineFriends.contains(name);
}
/**
* Forces the client to update the stats and such. This forces the update
* thread to run.
*
* @throws IOException
*/
public void forceUpdate() throws IOException {
wasSetup();
synchronized (task) {
if (!task.isDone()) {
task.notify();
} else {
throw new ServerConnectionLostException();
}
}
}
/**
* Checks to see if the client is still connected to the server and if the
* update thread is running.
*
* @return True if the update thread is alive, false otherwise.
* @throws IOException
*/
public boolean isChecking() throws IOException {
wasSetup();
boolean done;
synchronized (task) {
done = task.isDone();
}
return !done;
}
/**
* Changes the online status of the client. This is instant to the server
* and tells the server to turn the client offline.
*
* @param newStatus New online status
* @return The new online status
* @throws IOException
*/
public boolean changeOnlineStatus(boolean newStatus) throws IOException {
wasSetup();
online = newStatus;
Packet packet = new Packet(ClientRequest.CHANGEONLINE);
packet.addData("online", online);
packetSender.sendPacket(packet);
Packet reply = packetListener.getNextPacket(ClientRequest.SIMPLEREPLYPACKET);
if ((Boolean) reply.getData("reply")) {
return online;
} else {
throw new ServerRejectionException();
}
}
/**
* Changes the online status of the client. This is instant to the server
* and tells the server to turn the client offline.
*
* @return The new online status
* @throws IOException
*/
public boolean changeOnlineStatus() throws IOException {
wasSetup();
return changeOnlineStatus(!online);
}
/**
* Returns a boolean where true means the API was completely setup and
* connections were successful, otherwise an exception is thrown. This only
* checks the initial connection, not the later connections. Use
* isChecking() for that.
*
* @return True if API was set up.
* @throws IOException If api was not created right, exception thrown
*/
public boolean wasSetup() throws IOException {
if (was_set_up) {
return true;
} else {
throw new CreationNotCompleteException();
}
}
public static void setAPI(TeamStatsAPI apiTemp) throws IllegalAccessException {
if (apiTemp == null) {
throw new IllegalAccessException("The API instance cannot be null");
}
if (api != null) {
if (api == apiTemp) {
return;
} else {
throw new IllegalAccessException("Cannot change the API once it is set");
}
}
api = apiTemp;
}
public static TeamStatsAPI getAPI() {
return api;
}
private class UpdaterThread implements Runnable {
@Override
public void run() {
if (online) {
try {
Packet packet = new Packet(ClientRequest.GETFRIENDS);
packetSender.sendPacket(packet);
String[] friends;
Packet reply = packetListener.getNextPacket(ClientRequest.SIMPLEREPLYPACKET);
if (!(Boolean) reply.getData("reply")) {
- throw new ServerRejectionException();
+ throw new ServerRejectionException((String) reply.getData("reason"));
}
friends = ((String) packet.getData("names")).split(" ");
//check current friend list, removing and adding name differences
List<String> addFriend = new TSAList<String>();
addFriend.addAll(friendList);
for (String existing : friends) {
addFriend.remove(existing);
}
for (String name : addFriend) {
packet = new Packet(ClientRequest.ADDFRIEND);
packet.addData("name", name);
packetSender.sendPacket(packet);
reply = packetListener.getNextPacket(ClientRequest.SIMPLEREPLYPACKET);
if (!(Boolean) reply.getData("reply")) {
throw new ServerRejectionException();
}
}
List<String> removeFriend = new ArrayList<String>();
removeFriend.addAll(Arrays.asList(friends));
for (String existing : friendList) {
removeFriend.remove(existing);
}
for (String name : removeFriend) {
packet = new Packet(ClientRequest.REMOVEFRIEND);
packet.addData("name", name);
packetSender.sendPacket(packet);
reply = packetListener.getNextPacket(ClientRequest.SIMPLEREPLYPACKET);
if (!(Boolean) reply.getData("reply")) {
throw new ServerRejectionException();
}
}
//send new stats for this person
String pStats = "";
for (String key : stats.keySet()) {
pStats += key + ":" + stats.get(key) + " ";
}
pStats = pStats.trim();
packet = new Packet(ClientRequest.UPDATESTATS);
packet.addData("stats", pStats);
reply = packetListener.getNextPacket(ClientRequest.SIMPLEREPLYPACKET);
if (!(Boolean) reply.getData("reply")) {
throw new ServerRejectionException();
}
//check friend requests
packet = new Packet(ClientRequest.GETREQUESTS);
packetSender.sendPacket(packet);
reply = packetListener.getNextPacket(ClientRequest.SIMPLEREPLYPACKET);
if (!(Boolean) reply.getData("reply")) {
throw new ServerRejectionException();
}
String names = (String) reply.getData("names");
String[] old = friendRequests.toArray(new String[0]);
friendRequests.clear();
friendRequests.addAll(Arrays.asList(names.split(" ")));
if (newRequests.containsAll(Arrays.asList(old))) {
}
for (String name : old) {
if (!newRequests.contains(name)) {
newRequests.add(name);
}
}
packet = new Packet(ClientRequest.GETFRIENDS);
packetSender.sendPacket(packet);
reply = packetListener.getNextPacket(ClientRequest.SIMPLEREPLYPACKET);
if (!(Boolean) reply.getData("reply")) {
throw new ServerRejectionException();
}
List<String> updateFriends = Arrays.asList(((String) reply.getData("names")).split(" "));
for (String name : updateFriends) {
if (friendList.contains(name)) {
continue;
}
newFriends.add(name);
}
for (String name : friendList) {
if (updateFriends.contains(name)) {
continue;
}
newlyRemovedFriends.add(name);
}
friendList.clear();
friendList.addAll(updateFriends);
//get stats for friends in list
friendStats.clear();
onlineFriends.clear();
for (String friendName : friendList) {
Packet send = new Packet(ClientRequest.GETSTATS);
send.addData("name", friendName);
packetSender.sendPacket(send);
reply = packetListener.getNextPacket(ClientRequest.SIMPLEREPLYPACKET);
if (!(Boolean) reply.getData("reply")) {
throw new ServerRejectionException();
}
String stat = (String) reply.getData("stats");
Map<String, Object> friendS = new HashMap<String, Object>();
String[] parts = stat.split(" ");
for (String string : parts) {
friendS.put(string.split(":")[0].toLowerCase().trim(), string.split(":")[1]);
}
friendStats.put(friendName, friendS);
Packet send2 = new Packet(ClientRequest.GETONLINESTATUS);
send2.addData("name", friendName);
packetSender.sendPacket(send2);
reply = packetListener.getNextPacket(ClientRequest.SIMPLEREPLYPACKET);
if (!(Boolean) reply.getData("reply")) {
throw new ServerRejectionException();
}
boolean isOnline = (Boolean) reply.getData("online");
if (isOnline) {
onlineFriends.add(friendName);
}
}
} catch (IOException ex) {
ex.printStackTrace(System.err);
online = false;
}
} else {
new ServerConnectionLostException().printStackTrace(System.err);
online = false;
}
}
}
}
| true | true | public void run() {
if (online) {
try {
Packet packet = new Packet(ClientRequest.GETFRIENDS);
packetSender.sendPacket(packet);
String[] friends;
Packet reply = packetListener.getNextPacket(ClientRequest.SIMPLEREPLYPACKET);
if (!(Boolean) reply.getData("reply")) {
throw new ServerRejectionException();
}
friends = ((String) packet.getData("names")).split(" ");
//check current friend list, removing and adding name differences
List<String> addFriend = new TSAList<String>();
addFriend.addAll(friendList);
for (String existing : friends) {
addFriend.remove(existing);
}
for (String name : addFriend) {
packet = new Packet(ClientRequest.ADDFRIEND);
packet.addData("name", name);
packetSender.sendPacket(packet);
reply = packetListener.getNextPacket(ClientRequest.SIMPLEREPLYPACKET);
if (!(Boolean) reply.getData("reply")) {
throw new ServerRejectionException();
}
}
List<String> removeFriend = new ArrayList<String>();
removeFriend.addAll(Arrays.asList(friends));
for (String existing : friendList) {
removeFriend.remove(existing);
}
for (String name : removeFriend) {
packet = new Packet(ClientRequest.REMOVEFRIEND);
packet.addData("name", name);
packetSender.sendPacket(packet);
reply = packetListener.getNextPacket(ClientRequest.SIMPLEREPLYPACKET);
if (!(Boolean) reply.getData("reply")) {
throw new ServerRejectionException();
}
}
//send new stats for this person
String pStats = "";
for (String key : stats.keySet()) {
pStats += key + ":" + stats.get(key) + " ";
}
pStats = pStats.trim();
packet = new Packet(ClientRequest.UPDATESTATS);
packet.addData("stats", pStats);
reply = packetListener.getNextPacket(ClientRequest.SIMPLEREPLYPACKET);
if (!(Boolean) reply.getData("reply")) {
throw new ServerRejectionException();
}
//check friend requests
packet = new Packet(ClientRequest.GETREQUESTS);
packetSender.sendPacket(packet);
reply = packetListener.getNextPacket(ClientRequest.SIMPLEREPLYPACKET);
if (!(Boolean) reply.getData("reply")) {
throw new ServerRejectionException();
}
String names = (String) reply.getData("names");
String[] old = friendRequests.toArray(new String[0]);
friendRequests.clear();
friendRequests.addAll(Arrays.asList(names.split(" ")));
if (newRequests.containsAll(Arrays.asList(old))) {
}
for (String name : old) {
if (!newRequests.contains(name)) {
newRequests.add(name);
}
}
packet = new Packet(ClientRequest.GETFRIENDS);
packetSender.sendPacket(packet);
reply = packetListener.getNextPacket(ClientRequest.SIMPLEREPLYPACKET);
if (!(Boolean) reply.getData("reply")) {
throw new ServerRejectionException();
}
List<String> updateFriends = Arrays.asList(((String) reply.getData("names")).split(" "));
for (String name : updateFriends) {
if (friendList.contains(name)) {
continue;
}
newFriends.add(name);
}
for (String name : friendList) {
if (updateFriends.contains(name)) {
continue;
}
newlyRemovedFriends.add(name);
}
friendList.clear();
friendList.addAll(updateFriends);
//get stats for friends in list
friendStats.clear();
onlineFriends.clear();
for (String friendName : friendList) {
Packet send = new Packet(ClientRequest.GETSTATS);
send.addData("name", friendName);
packetSender.sendPacket(send);
reply = packetListener.getNextPacket(ClientRequest.SIMPLEREPLYPACKET);
if (!(Boolean) reply.getData("reply")) {
throw new ServerRejectionException();
}
String stat = (String) reply.getData("stats");
Map<String, Object> friendS = new HashMap<String, Object>();
String[] parts = stat.split(" ");
for (String string : parts) {
friendS.put(string.split(":")[0].toLowerCase().trim(), string.split(":")[1]);
}
friendStats.put(friendName, friendS);
Packet send2 = new Packet(ClientRequest.GETONLINESTATUS);
send2.addData("name", friendName);
packetSender.sendPacket(send2);
reply = packetListener.getNextPacket(ClientRequest.SIMPLEREPLYPACKET);
if (!(Boolean) reply.getData("reply")) {
throw new ServerRejectionException();
}
boolean isOnline = (Boolean) reply.getData("online");
if (isOnline) {
onlineFriends.add(friendName);
}
}
} catch (IOException ex) {
ex.printStackTrace(System.err);
online = false;
}
} else {
new ServerConnectionLostException().printStackTrace(System.err);
online = false;
}
}
| public void run() {
if (online) {
try {
Packet packet = new Packet(ClientRequest.GETFRIENDS);
packetSender.sendPacket(packet);
String[] friends;
Packet reply = packetListener.getNextPacket(ClientRequest.SIMPLEREPLYPACKET);
if (!(Boolean) reply.getData("reply")) {
throw new ServerRejectionException((String) reply.getData("reason"));
}
friends = ((String) packet.getData("names")).split(" ");
//check current friend list, removing and adding name differences
List<String> addFriend = new TSAList<String>();
addFriend.addAll(friendList);
for (String existing : friends) {
addFriend.remove(existing);
}
for (String name : addFriend) {
packet = new Packet(ClientRequest.ADDFRIEND);
packet.addData("name", name);
packetSender.sendPacket(packet);
reply = packetListener.getNextPacket(ClientRequest.SIMPLEREPLYPACKET);
if (!(Boolean) reply.getData("reply")) {
throw new ServerRejectionException();
}
}
List<String> removeFriend = new ArrayList<String>();
removeFriend.addAll(Arrays.asList(friends));
for (String existing : friendList) {
removeFriend.remove(existing);
}
for (String name : removeFriend) {
packet = new Packet(ClientRequest.REMOVEFRIEND);
packet.addData("name", name);
packetSender.sendPacket(packet);
reply = packetListener.getNextPacket(ClientRequest.SIMPLEREPLYPACKET);
if (!(Boolean) reply.getData("reply")) {
throw new ServerRejectionException();
}
}
//send new stats for this person
String pStats = "";
for (String key : stats.keySet()) {
pStats += key + ":" + stats.get(key) + " ";
}
pStats = pStats.trim();
packet = new Packet(ClientRequest.UPDATESTATS);
packet.addData("stats", pStats);
reply = packetListener.getNextPacket(ClientRequest.SIMPLEREPLYPACKET);
if (!(Boolean) reply.getData("reply")) {
throw new ServerRejectionException();
}
//check friend requests
packet = new Packet(ClientRequest.GETREQUESTS);
packetSender.sendPacket(packet);
reply = packetListener.getNextPacket(ClientRequest.SIMPLEREPLYPACKET);
if (!(Boolean) reply.getData("reply")) {
throw new ServerRejectionException();
}
String names = (String) reply.getData("names");
String[] old = friendRequests.toArray(new String[0]);
friendRequests.clear();
friendRequests.addAll(Arrays.asList(names.split(" ")));
if (newRequests.containsAll(Arrays.asList(old))) {
}
for (String name : old) {
if (!newRequests.contains(name)) {
newRequests.add(name);
}
}
packet = new Packet(ClientRequest.GETFRIENDS);
packetSender.sendPacket(packet);
reply = packetListener.getNextPacket(ClientRequest.SIMPLEREPLYPACKET);
if (!(Boolean) reply.getData("reply")) {
throw new ServerRejectionException();
}
List<String> updateFriends = Arrays.asList(((String) reply.getData("names")).split(" "));
for (String name : updateFriends) {
if (friendList.contains(name)) {
continue;
}
newFriends.add(name);
}
for (String name : friendList) {
if (updateFriends.contains(name)) {
continue;
}
newlyRemovedFriends.add(name);
}
friendList.clear();
friendList.addAll(updateFriends);
//get stats for friends in list
friendStats.clear();
onlineFriends.clear();
for (String friendName : friendList) {
Packet send = new Packet(ClientRequest.GETSTATS);
send.addData("name", friendName);
packetSender.sendPacket(send);
reply = packetListener.getNextPacket(ClientRequest.SIMPLEREPLYPACKET);
if (!(Boolean) reply.getData("reply")) {
throw new ServerRejectionException();
}
String stat = (String) reply.getData("stats");
Map<String, Object> friendS = new HashMap<String, Object>();
String[] parts = stat.split(" ");
for (String string : parts) {
friendS.put(string.split(":")[0].toLowerCase().trim(), string.split(":")[1]);
}
friendStats.put(friendName, friendS);
Packet send2 = new Packet(ClientRequest.GETONLINESTATUS);
send2.addData("name", friendName);
packetSender.sendPacket(send2);
reply = packetListener.getNextPacket(ClientRequest.SIMPLEREPLYPACKET);
if (!(Boolean) reply.getData("reply")) {
throw new ServerRejectionException();
}
boolean isOnline = (Boolean) reply.getData("online");
if (isOnline) {
onlineFriends.add(friendName);
}
}
} catch (IOException ex) {
ex.printStackTrace(System.err);
online = false;
}
} else {
new ServerConnectionLostException().printStackTrace(System.err);
online = false;
}
}
|
diff --git a/org.eclipse.mylyn.wikitext.tests/src/org/eclipse/mylyn/wikitext/tests/ClassTraversal.java b/org.eclipse.mylyn.wikitext.tests/src/org/eclipse/mylyn/wikitext/tests/ClassTraversal.java
index 1cad0275..e39fefd0 100644
--- a/org.eclipse.mylyn.wikitext.tests/src/org/eclipse/mylyn/wikitext/tests/ClassTraversal.java
+++ b/org.eclipse.mylyn.wikitext.tests/src/org/eclipse/mylyn/wikitext/tests/ClassTraversal.java
@@ -1,137 +1,137 @@
/*******************************************************************************
* Copyright (c) 2007, 2010 David Green 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:
* David Green - initial API and implementation
*******************************************************************************/
package org.eclipse.mylyn.wikitext.tests;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLDecoder;
import java.util.Enumeration;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.eclipse.mylyn.internal.wikitext.core.WikiTextPlugin;
import org.osgi.framework.Bundle;
/**
* A utility for visiting Mylyn classes available on the classpath.
*
* @author David Green
*/
public class ClassTraversal {
private static final Pattern BUNDLE_RESOURCE_35 = Pattern.compile("(\\d+)\\..*");;
public void visitClasses(Visitor visitor) {
visitClasses(ClassTraversal.class, visitor);
}
private void visitClasses(Class<ClassTraversal> classOnClasspath, Visitor visitor) {
ClassLoader loader = classOnClasspath.getClassLoader();
String resourceOfClass = classOnClasspath.getCanonicalName().replace('.', '/') + ".class";
Enumeration<URL> resources;
try {
resources = loader.getResources(resourceOfClass);
} catch (IOException e) {
throw new IllegalStateException(e);
}
while (resources.hasMoreElements()) {
URL url = resources.nextElement();
String protocol = url.getProtocol();
if (protocol.equals("file")) {
String file = url.getFile();
try {
- file = URLDecoder.decode(file, "utf-8").substring(0, file.indexOf(resourceOfClass));
+ file = URLDecoder.decode(file.substring(0, file.indexOf(resourceOfClass)), "utf-8");
} catch (UnsupportedEncodingException e) {
throw new IllegalStateException(e);
}
visitClasses(loader, new File(file), new File(file), visitor);
} else if (protocol.equals("bundleresource")) {
String host = url.getHost();
// bug 266767 see http://dev.eclipse.org/mhonarc/lists/equinox-dev/msg05209.html
Matcher bundle35Matcher = BUNDLE_RESOURCE_35.matcher(host);
if (bundle35Matcher.matches()) {
host = bundle35Matcher.group(1);
}
long bundleId = Long.parseLong(host);
Bundle bundle = WikiTextPlugin.getDefault().getBundle().getBundleContext().getBundle(bundleId);
if (bundle == null) {
throw new IllegalStateException("Cannot get bundle " + bundleId);
}
String path = url.getFile();
path = path.substring(0, path.indexOf(resourceOfClass));
visitClasses(bundle, path, visitor);
} else {
throw new IllegalStateException("Unimplemented protocol: " + protocol);
}
}
}
private void visitClasses(ClassLoader loader, File root, File file, Visitor visitor) {
File[] files = file.listFiles();
if (files != null) {
for (File child : files) {
if (child.isDirectory()) {
visitClasses(loader, root, child, visitor);
} else {
String path = child.getPath();
if (path.endsWith(".class")) {
String fqn = path.substring(root.getPath().length() + 1, path.length() - ".class".length());
fqn = fqn.replace('/', '.').replace('\\', '.');
Class<?> clazz;
try {
clazz = Class.forName(fqn, true, loader);
} catch (LinkageError e) {
// see bug 255568 comment 11
// can't load the class, so skip it.
continue;
} catch (Exception e) {
// can't load the class, so skip it.
continue;
}
visitor.visit(clazz);
}
}
}
}
}
@SuppressWarnings("unchecked")
private void visitClasses(Bundle bundle, String path, Visitor visitor) {
Enumeration<URL> entries = bundle.findEntries(path, "*.class", true);
while (entries.hasMoreElements()) {
URL element = entries.nextElement();
String filePath = element.getFile();
if (filePath.indexOf("org/eclipse/mylyn") != -1) {
filePath = filePath.substring(filePath.indexOf("org/eclipse/mylyn"));
} else {
continue;
}
String fqn = filePath.substring(0, filePath.length() - ".class".length()).replace('/', '.');
Class<?> clazz;
try {
clazz = bundle.loadClass(fqn);
} catch (Exception e) {
// can't laod the class, so skip it.
continue;
}
visitor.visit(clazz);
}
}
public interface Visitor {
public void visit(Class<?> clazz);
}
}
| true | true | private void visitClasses(Class<ClassTraversal> classOnClasspath, Visitor visitor) {
ClassLoader loader = classOnClasspath.getClassLoader();
String resourceOfClass = classOnClasspath.getCanonicalName().replace('.', '/') + ".class";
Enumeration<URL> resources;
try {
resources = loader.getResources(resourceOfClass);
} catch (IOException e) {
throw new IllegalStateException(e);
}
while (resources.hasMoreElements()) {
URL url = resources.nextElement();
String protocol = url.getProtocol();
if (protocol.equals("file")) {
String file = url.getFile();
try {
file = URLDecoder.decode(file, "utf-8").substring(0, file.indexOf(resourceOfClass));
} catch (UnsupportedEncodingException e) {
throw new IllegalStateException(e);
}
visitClasses(loader, new File(file), new File(file), visitor);
} else if (protocol.equals("bundleresource")) {
String host = url.getHost();
// bug 266767 see http://dev.eclipse.org/mhonarc/lists/equinox-dev/msg05209.html
Matcher bundle35Matcher = BUNDLE_RESOURCE_35.matcher(host);
if (bundle35Matcher.matches()) {
host = bundle35Matcher.group(1);
}
long bundleId = Long.parseLong(host);
Bundle bundle = WikiTextPlugin.getDefault().getBundle().getBundleContext().getBundle(bundleId);
if (bundle == null) {
throw new IllegalStateException("Cannot get bundle " + bundleId);
}
String path = url.getFile();
path = path.substring(0, path.indexOf(resourceOfClass));
visitClasses(bundle, path, visitor);
} else {
throw new IllegalStateException("Unimplemented protocol: " + protocol);
}
}
}
| private void visitClasses(Class<ClassTraversal> classOnClasspath, Visitor visitor) {
ClassLoader loader = classOnClasspath.getClassLoader();
String resourceOfClass = classOnClasspath.getCanonicalName().replace('.', '/') + ".class";
Enumeration<URL> resources;
try {
resources = loader.getResources(resourceOfClass);
} catch (IOException e) {
throw new IllegalStateException(e);
}
while (resources.hasMoreElements()) {
URL url = resources.nextElement();
String protocol = url.getProtocol();
if (protocol.equals("file")) {
String file = url.getFile();
try {
file = URLDecoder.decode(file.substring(0, file.indexOf(resourceOfClass)), "utf-8");
} catch (UnsupportedEncodingException e) {
throw new IllegalStateException(e);
}
visitClasses(loader, new File(file), new File(file), visitor);
} else if (protocol.equals("bundleresource")) {
String host = url.getHost();
// bug 266767 see http://dev.eclipse.org/mhonarc/lists/equinox-dev/msg05209.html
Matcher bundle35Matcher = BUNDLE_RESOURCE_35.matcher(host);
if (bundle35Matcher.matches()) {
host = bundle35Matcher.group(1);
}
long bundleId = Long.parseLong(host);
Bundle bundle = WikiTextPlugin.getDefault().getBundle().getBundleContext().getBundle(bundleId);
if (bundle == null) {
throw new IllegalStateException("Cannot get bundle " + bundleId);
}
String path = url.getFile();
path = path.substring(0, path.indexOf(resourceOfClass));
visitClasses(bundle, path, visitor);
} else {
throw new IllegalStateException("Unimplemented protocol: " + protocol);
}
}
}
|
diff --git a/source/de/tuclausthal/submissioninterface/servlets/view/ShowLectureStudentView.java b/source/de/tuclausthal/submissioninterface/servlets/view/ShowLectureStudentView.java
index 852795b..75c9d54 100644
--- a/source/de/tuclausthal/submissioninterface/servlets/view/ShowLectureStudentView.java
+++ b/source/de/tuclausthal/submissioninterface/servlets/view/ShowLectureStudentView.java
@@ -1,125 +1,129 @@
/*
* Copyright 2009 - 2010 Sven Strickroth <[email protected]>
*
* This file is part of the SubmissionInterface.
*
* SubmissionInterface is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 3 as
* published by the Free Software Foundation.
*
* SubmissionInterface 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 SubmissionInterface. If not, see <http://www.gnu.org/licenses/>.
*/
package de.tuclausthal.submissioninterface.servlets.view;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import de.tuclausthal.submissioninterface.authfilter.SessionAdapter;
import de.tuclausthal.submissioninterface.persistence.dao.DAOFactory;
import de.tuclausthal.submissioninterface.persistence.datamodel.Group;
import de.tuclausthal.submissioninterface.persistence.datamodel.Lecture;
import de.tuclausthal.submissioninterface.persistence.datamodel.Participation;
import de.tuclausthal.submissioninterface.persistence.datamodel.ParticipationRole;
import de.tuclausthal.submissioninterface.persistence.datamodel.Submission;
import de.tuclausthal.submissioninterface.persistence.datamodel.Task;
import de.tuclausthal.submissioninterface.template.Template;
import de.tuclausthal.submissioninterface.template.TemplateFactory;
import de.tuclausthal.submissioninterface.util.HibernateSessionHelper;
import de.tuclausthal.submissioninterface.util.Util;
/**
* View-Servlet for displaying a lecture in student view
* @author Sven Strickroth
*/
public class ShowLectureStudentView extends HttpServlet {
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
Template template = TemplateFactory.getTemplate(request, response);
PrintWriter out = response.getWriter();
Participation participation = (Participation) request.getAttribute("participation");
Lecture lecture = participation.getLecture();
List<Group> joinAbleGroups = (List<Group>) request.getAttribute("joinAbleGroups");
SessionAdapter sessionAdapter = new SessionAdapter(request);
// list all tasks for a lecture
template.printTemplateHeader(lecture);
out.println("<div class=mid>");
if (participation.getGroup() != null) {
out.println("Meine Gruppe: " + Util.mknohtml(participation.getGroup().getName()));
if (participation.getGroup().getTutors() != null && participation.getGroup().getTutors().size() > 0) {
- out.println("<br>Meine Tutoren: ");
+ if (participation.getGroup().getTutors().size() > 1) {
+ out.println("<br>Meine Tutoren: ");
+ } else {
+ out.println("<br>Mein Tutor: ");
+ }
boolean isFirst = true;
for (Participation tutor : participation.getGroup().getTutors()) {
if (!isFirst) {
out.print(", ");
}
isFirst = false;
out.print("<a href=\"mailto:" + Util.mknohtml(tutor.getUser().getFullEmail()) + "\">" + Util.mknohtml(tutor.getUser().getFullName()) + "</a>");
}
}
}
if (joinAbleGroups != null && joinAbleGroups.size() > 0) {
out.println("<form action=\"" + response.encodeURL("JoinGroup") + "\">");
out.println("<select name=groupid>");
for (Group group : joinAbleGroups) {
out.println("<option value=" + group.getGid() + ">" + Util.mknohtml(group.getName()));
}
out.println("</select>");
out.println("<input type=submit value=\"Gruppe wechseln\">");
out.println("</form>");
}
out.println("</div><p>");
// todo: wenn keine abrufbaren tasks da sind, nichts anzeigen
Iterator<Task> taskIterator = lecture.getTasks().iterator();
if (taskIterator.hasNext()) {
out.println("<table class=border>");
out.println("<tr>");
out.println("<th>Aufgabe</th>");
out.println("<th>Max. Punkte</th>");
out.println("<th>Meine Punkte</th>");
out.println("</tr>");
while (taskIterator.hasNext()) {
Task task = taskIterator.next();
if (task.getStart().before(Util.correctTimezone(new Date())) || participation.getRoleType().compareTo(ParticipationRole.TUTOR) >= 0) {
out.println("<tr>");
out.println("<td><a href=\"" + response.encodeURL("ShowTask?taskid=" + task.getTaskid()) + "\">" + Util.mknohtml(task.getTitle()) + "</a></td>");
out.println("<td class=points>" + Util.showPoints(task.getMaxPoints()) + "</td>");
Submission submission = DAOFactory.SubmissionDAOIf(HibernateSessionHelper.getSessionFactory().openSession()).getSubmission(task, sessionAdapter.getUser(HibernateSessionHelper.getSession()));
if (submission != null && submission.getPoints() != null && submission.getTask().getShowPoints().before(Util.correctTimezone(new Date()))) {
if (submission.getPoints().getPointsOk()) {
out.println("<td class=points>" + Util.showPoints(submission.getPoints().getPoints()) + "</td>");
} else {
out.println("<td class=points>0, nicht abgenommen</td>");
}
} else {
out.println("<td class=points>n/a</td>");
}
out.println("</tr>");
}
}
out.println("</table>");
} else {
out.println("<div class=mid>keine Aufgaben gefunden.</div>");
}
template.printTemplateFooter();
}
}
| true | true | public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
Template template = TemplateFactory.getTemplate(request, response);
PrintWriter out = response.getWriter();
Participation participation = (Participation) request.getAttribute("participation");
Lecture lecture = participation.getLecture();
List<Group> joinAbleGroups = (List<Group>) request.getAttribute("joinAbleGroups");
SessionAdapter sessionAdapter = new SessionAdapter(request);
// list all tasks for a lecture
template.printTemplateHeader(lecture);
out.println("<div class=mid>");
if (participation.getGroup() != null) {
out.println("Meine Gruppe: " + Util.mknohtml(participation.getGroup().getName()));
if (participation.getGroup().getTutors() != null && participation.getGroup().getTutors().size() > 0) {
out.println("<br>Meine Tutoren: ");
boolean isFirst = true;
for (Participation tutor : participation.getGroup().getTutors()) {
if (!isFirst) {
out.print(", ");
}
isFirst = false;
out.print("<a href=\"mailto:" + Util.mknohtml(tutor.getUser().getFullEmail()) + "\">" + Util.mknohtml(tutor.getUser().getFullName()) + "</a>");
}
}
}
if (joinAbleGroups != null && joinAbleGroups.size() > 0) {
out.println("<form action=\"" + response.encodeURL("JoinGroup") + "\">");
out.println("<select name=groupid>");
for (Group group : joinAbleGroups) {
out.println("<option value=" + group.getGid() + ">" + Util.mknohtml(group.getName()));
}
out.println("</select>");
out.println("<input type=submit value=\"Gruppe wechseln\">");
out.println("</form>");
}
out.println("</div><p>");
// todo: wenn keine abrufbaren tasks da sind, nichts anzeigen
Iterator<Task> taskIterator = lecture.getTasks().iterator();
if (taskIterator.hasNext()) {
out.println("<table class=border>");
out.println("<tr>");
out.println("<th>Aufgabe</th>");
out.println("<th>Max. Punkte</th>");
out.println("<th>Meine Punkte</th>");
out.println("</tr>");
while (taskIterator.hasNext()) {
Task task = taskIterator.next();
if (task.getStart().before(Util.correctTimezone(new Date())) || participation.getRoleType().compareTo(ParticipationRole.TUTOR) >= 0) {
out.println("<tr>");
out.println("<td><a href=\"" + response.encodeURL("ShowTask?taskid=" + task.getTaskid()) + "\">" + Util.mknohtml(task.getTitle()) + "</a></td>");
out.println("<td class=points>" + Util.showPoints(task.getMaxPoints()) + "</td>");
Submission submission = DAOFactory.SubmissionDAOIf(HibernateSessionHelper.getSessionFactory().openSession()).getSubmission(task, sessionAdapter.getUser(HibernateSessionHelper.getSession()));
if (submission != null && submission.getPoints() != null && submission.getTask().getShowPoints().before(Util.correctTimezone(new Date()))) {
if (submission.getPoints().getPointsOk()) {
out.println("<td class=points>" + Util.showPoints(submission.getPoints().getPoints()) + "</td>");
} else {
out.println("<td class=points>0, nicht abgenommen</td>");
}
} else {
out.println("<td class=points>n/a</td>");
}
out.println("</tr>");
}
}
out.println("</table>");
} else {
out.println("<div class=mid>keine Aufgaben gefunden.</div>");
}
template.printTemplateFooter();
}
| public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
Template template = TemplateFactory.getTemplate(request, response);
PrintWriter out = response.getWriter();
Participation participation = (Participation) request.getAttribute("participation");
Lecture lecture = participation.getLecture();
List<Group> joinAbleGroups = (List<Group>) request.getAttribute("joinAbleGroups");
SessionAdapter sessionAdapter = new SessionAdapter(request);
// list all tasks for a lecture
template.printTemplateHeader(lecture);
out.println("<div class=mid>");
if (participation.getGroup() != null) {
out.println("Meine Gruppe: " + Util.mknohtml(participation.getGroup().getName()));
if (participation.getGroup().getTutors() != null && participation.getGroup().getTutors().size() > 0) {
if (participation.getGroup().getTutors().size() > 1) {
out.println("<br>Meine Tutoren: ");
} else {
out.println("<br>Mein Tutor: ");
}
boolean isFirst = true;
for (Participation tutor : participation.getGroup().getTutors()) {
if (!isFirst) {
out.print(", ");
}
isFirst = false;
out.print("<a href=\"mailto:" + Util.mknohtml(tutor.getUser().getFullEmail()) + "\">" + Util.mknohtml(tutor.getUser().getFullName()) + "</a>");
}
}
}
if (joinAbleGroups != null && joinAbleGroups.size() > 0) {
out.println("<form action=\"" + response.encodeURL("JoinGroup") + "\">");
out.println("<select name=groupid>");
for (Group group : joinAbleGroups) {
out.println("<option value=" + group.getGid() + ">" + Util.mknohtml(group.getName()));
}
out.println("</select>");
out.println("<input type=submit value=\"Gruppe wechseln\">");
out.println("</form>");
}
out.println("</div><p>");
// todo: wenn keine abrufbaren tasks da sind, nichts anzeigen
Iterator<Task> taskIterator = lecture.getTasks().iterator();
if (taskIterator.hasNext()) {
out.println("<table class=border>");
out.println("<tr>");
out.println("<th>Aufgabe</th>");
out.println("<th>Max. Punkte</th>");
out.println("<th>Meine Punkte</th>");
out.println("</tr>");
while (taskIterator.hasNext()) {
Task task = taskIterator.next();
if (task.getStart().before(Util.correctTimezone(new Date())) || participation.getRoleType().compareTo(ParticipationRole.TUTOR) >= 0) {
out.println("<tr>");
out.println("<td><a href=\"" + response.encodeURL("ShowTask?taskid=" + task.getTaskid()) + "\">" + Util.mknohtml(task.getTitle()) + "</a></td>");
out.println("<td class=points>" + Util.showPoints(task.getMaxPoints()) + "</td>");
Submission submission = DAOFactory.SubmissionDAOIf(HibernateSessionHelper.getSessionFactory().openSession()).getSubmission(task, sessionAdapter.getUser(HibernateSessionHelper.getSession()));
if (submission != null && submission.getPoints() != null && submission.getTask().getShowPoints().before(Util.correctTimezone(new Date()))) {
if (submission.getPoints().getPointsOk()) {
out.println("<td class=points>" + Util.showPoints(submission.getPoints().getPoints()) + "</td>");
} else {
out.println("<td class=points>0, nicht abgenommen</td>");
}
} else {
out.println("<td class=points>n/a</td>");
}
out.println("</tr>");
}
}
out.println("</table>");
} else {
out.println("<div class=mid>keine Aufgaben gefunden.</div>");
}
template.printTemplateFooter();
}
|
diff --git a/rse/plugins/org.eclipse.dltk.ssh.core/src/org/eclipse/dltk/ssh/internal/core/ChannelPool.java b/rse/plugins/org.eclipse.dltk.ssh.core/src/org/eclipse/dltk/ssh/internal/core/ChannelPool.java
index 73317ada0..932c232f9 100644
--- a/rse/plugins/org.eclipse.dltk.ssh.core/src/org/eclipse/dltk/ssh/internal/core/ChannelPool.java
+++ b/rse/plugins/org.eclipse.dltk.ssh.core/src/org/eclipse/dltk/ssh/internal/core/ChannelPool.java
@@ -1,383 +1,383 @@
/*******************************************************************************
* Copyright (c) 2009 xored software, Inc.
*
* 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:
* xored software, Inc. - initial API and Implementation (Alex Panchenko)
*******************************************************************************/
package org.eclipse.dltk.ssh.internal.core;
import java.util.ArrayList;
import java.util.IdentityHashMap;
import java.util.List;
import java.util.Map;
import org.eclipse.jsch.core.IJSchService;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
import com.jcraft.jsch.UIKeyboardInteractive;
import com.jcraft.jsch.UserInfo;
public class ChannelPool {
private final long inactivityTimeout;
private final String userName;
private final int port;
private final String hostName;
private String password;
private Session session;
private final List<ChannelSftp> freeChannels = new ArrayList<ChannelSftp>();
private final Map<ChannelSftp, ChannelUsageInfo> usedChannels = new IdentityHashMap<ChannelSftp, ChannelUsageInfo>();
private static class ChannelUsageInfo {
final Object context;
final long timestamp;
public ChannelUsageInfo(Object context) {
this.context = context;
this.timestamp = System.currentTimeMillis();
}
}
/**
* @param userName
* @param hostName
* @param port
*/
public ChannelPool(String userName, String hostName, int port,
long inactivityTimeout) {
this.userName = userName;
this.hostName = hostName;
this.port = port;
this.inactivityTimeout = inactivityTimeout;
}
public void setPassword(String password) {
this.password = password;
}
public String getPassword() {
return password;
}
private final class LocalUserInfo implements UserInfo,
UIKeyboardInteractive {
public void showMessage(String arg0) {
}
public boolean promptYesNo(String arg0) {
return false;
}
public boolean promptPassword(String arg0) {
return true;
}
public boolean promptPassphrase(String arg0) {
return false;
}
public String getPassword() {
return password;
}
public String getPassphrase() {
return ""; //$NON-NLS-1$
}
public String[] promptKeyboardInteractive(String destination,
String name, String instruction, String[] prompt, boolean[] echo) {
final String p = password;
return p != null ? new String[] { p } : null;
}
}
private static boolean DEBUG = false;
protected void connectSession() throws JSchException {
synchronized (lock) {
if (session == null) {
IJSchService service = Activator.getDefault().getJSch();
session = service.createSession(hostName, port, userName);
session.setTimeout(0);
session.setServerAliveInterval(300000);
session.setServerAliveCountMax(6);
session.setPassword(password); // Set password
// directly
UserInfo ui = new LocalUserInfo();
session.setUserInfo(ui);
}
if (!session.isConnected()) {
// Connect with default timeout
if (DEBUG) {
log("session.connect()"); //$NON-NLS-1$
}
session.connect(60 * 1000);
if (DEBUG) {
log("...connected"); //$NON-NLS-1$
}
}
}
}
private final Object channelNotifier = new Object();
private final Object lock = new Object();
protected ChannelSftp acquireChannel(final Object context, long timeout) {
final long start = System.currentTimeMillis();
for (;;) {
try {
return acquireChannel(context);
} catch (JSchException e) {
if (isOutOfChannels(e)) {
if (tryCloseOldChannels()) {
continue;
}
}
if (System.currentTimeMillis() - start > timeout) {
Activator.error("Failed to create direct connection", e); //$NON-NLS-1$
return null;
}
if (DEBUG) {
log(" <sleep>"); //$NON-NLS-1$
}
try {
synchronized (channelNotifier) {
channelNotifier.wait(1000);
}
} catch (InterruptedException e1) {
return null;
}
}
}
}
private boolean isOutOfChannels(JSchException e) {
return CHANNEL_IS_NOT_OPENED.equals(e.getMessage());
}
private static final String CHANNEL_IS_NOT_OPENED = "channel is not opened."; //$NON-NLS-1$
protected ChannelSftp acquireChannel(Object context) throws JSchException {
connectSession();
if (DEBUG) {
log("<acquireChannel> " + context); //$NON-NLS-1$
}
synchronized (lock) {
while (!freeChannels.isEmpty()) {
final ChannelSftp channel = freeChannels.remove(freeChannels
.size() - 1);
if (channel.isConnected()) {
usedChannels.put(channel, createUsageInfo(context));
return channel;
}
}
}
final ChannelSftp channel = (ChannelSftp) session.openChannel("sftp"); //$NON-NLS-1$
if (!channel.isConnected()) {
if (DEBUG) {
log("channel.connect()"); //$NON-NLS-1$
}
- channel.connect();
+ channel.connect(10000);
}
synchronized (lock) {
usedChannels.put(channel, createUsageInfo(context));
}
return channel;
// String eToStr = e.toString();
// if (eToStr.indexOf("Auth cancel") >= 0 || eToStr.indexOf("Auth fail") >= 0 || eToStr.indexOf("session is down") >= 0) { //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
// if (session.isConnected()) {
// session.disconnect();
// session = null;
// }
// }
// if (needLog) {
// Activator.error("Failed to create direct connection", e); //$NON-NLS-1$
// }
// if (session != null) {
// session.disconnect();
// session = null;
// }
}
/**
* @return
*/
private ChannelUsageInfo createUsageInfo(Object context) {
return new ChannelUsageInfo(context);
}
protected void releaseChannel(ChannelSftp channel) {
if (DEBUG) {
log("<releaseChannel>"); //$NON-NLS-1$
}
synchronized (lock) {
if (usedChannels.remove(channel) != null) {
freeChannels.add(channel);
} else {
channel.disconnect();
}
}
synchronized (channelNotifier) {
channelNotifier.notifyAll();
}
}
protected void destroyChannel(ChannelSftp channel) {
if (DEBUG) {
log("<destroyChannel>"); //$NON-NLS-1$
}
synchronized (lock) {
usedChannels.remove(channel);
}
channel.disconnect();
}
private boolean tryCloseOldChannels() {
synchronized (lock) {
if (!usedChannels.isEmpty()) {
ChannelSftp selectedChannel = null;
ChannelUsageInfo selectedUsageInfo = null;
long selectedLastActivity = 0;
for (Map.Entry<ChannelSftp, ChannelUsageInfo> entry : usedChannels
.entrySet()) {
final ChannelUsageInfo usageInfo = entry.getValue();
if (canClose(usageInfo.context)) {
final long lastActivity = getLastActivity(usageInfo.context);
if (lastActivity != Long.MIN_VALUE) {
if (selectedChannel == null
|| lastActivity < selectedLastActivity) {
selectedChannel = entry.getKey();
selectedUsageInfo = usageInfo;
selectedLastActivity = lastActivity;
}
}
}
}
if (selectedChannel != null) {
final long currentTime = System.currentTimeMillis();
if (currentTime - selectedLastActivity > inactivityTimeout) {
Activator
.warn("Close active channel \"" + selectedUsageInfo.context + "\" created " + (currentTime - selectedUsageInfo.timestamp) + "ms ago, lastActivity=" + (currentTime - selectedLastActivity) + "ms ago"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
if (DEBUG) {
log(" channel.disconnect() " + selectedUsageInfo.context); //$NON-NLS-1$
}
selectedChannel.disconnect();
usedChannels.remove(selectedChannel);
return true;
}
}
}
}
return false;
}
/**
* Tests if channel allocated for this context could be closed.
*
* @param context
* @return
*/
protected boolean canClose(Object context) {
return false;
}
/**
* Returns the time of last activity in the channel allocated for this
* context.
*
* @param context
* @return
*/
protected long getLastActivity(Object context) {
return Long.MIN_VALUE;
}
public void disconnect() {
synchronized (lock) {
for (ChannelSftp channel : freeChannels) {
if (DEBUG) {
log("channel.disconnect()"); //$NON-NLS-1$
}
channel.disconnect();
}
freeChannels.clear();
for (Map.Entry<ChannelSftp, ChannelUsageInfo> entry : usedChannels
.entrySet()) {
final ChannelUsageInfo usageInfo = entry.getValue();
Activator
.warn("Close active channel \"" + usageInfo.context + "\" created " + (System.currentTimeMillis() - usageInfo.timestamp) + "ms ago"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
if (DEBUG) {
log(" channel.disconnect() " + usageInfo.context); //$NON-NLS-1$
}
entry.getKey().disconnect();
}
usedChannels.clear();
if (session != null) {
if (DEBUG) {
log("session.disconnect()"); //$NON-NLS-1$
}
session.disconnect();
session = null;
}
}
}
private static final long loadedAt = System.currentTimeMillis();
protected void log(Object message) {
System.out
.println("[" + (System.currentTimeMillis() - loadedAt) + "] " + message); //$NON-NLS-1$ //$NON-NLS-2$
}
public boolean isConnected() {
return session != null && session.isConnected();
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result
+ ((hostName == null) ? 0 : hostName.hashCode());
result = prime * result + port;
result = prime * result
+ ((userName == null) ? 0 : userName.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
ChannelPool other = (ChannelPool) obj;
if (hostName == null) {
if (other.hostName != null)
return false;
} else if (!hostName.equals(other.hostName))
return false;
if (port != other.port)
return false;
if (userName == null) {
if (other.userName != null)
return false;
} else if (!userName.equals(other.userName))
return false;
return true;
}
}
| true | true | protected ChannelSftp acquireChannel(Object context) throws JSchException {
connectSession();
if (DEBUG) {
log("<acquireChannel> " + context); //$NON-NLS-1$
}
synchronized (lock) {
while (!freeChannels.isEmpty()) {
final ChannelSftp channel = freeChannels.remove(freeChannels
.size() - 1);
if (channel.isConnected()) {
usedChannels.put(channel, createUsageInfo(context));
return channel;
}
}
}
final ChannelSftp channel = (ChannelSftp) session.openChannel("sftp"); //$NON-NLS-1$
if (!channel.isConnected()) {
if (DEBUG) {
log("channel.connect()"); //$NON-NLS-1$
}
channel.connect();
}
synchronized (lock) {
usedChannels.put(channel, createUsageInfo(context));
}
return channel;
// String eToStr = e.toString();
// if (eToStr.indexOf("Auth cancel") >= 0 || eToStr.indexOf("Auth fail") >= 0 || eToStr.indexOf("session is down") >= 0) { //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
// if (session.isConnected()) {
// session.disconnect();
// session = null;
// }
// }
// if (needLog) {
// Activator.error("Failed to create direct connection", e); //$NON-NLS-1$
// }
// if (session != null) {
// session.disconnect();
// session = null;
// }
}
| protected ChannelSftp acquireChannel(Object context) throws JSchException {
connectSession();
if (DEBUG) {
log("<acquireChannel> " + context); //$NON-NLS-1$
}
synchronized (lock) {
while (!freeChannels.isEmpty()) {
final ChannelSftp channel = freeChannels.remove(freeChannels
.size() - 1);
if (channel.isConnected()) {
usedChannels.put(channel, createUsageInfo(context));
return channel;
}
}
}
final ChannelSftp channel = (ChannelSftp) session.openChannel("sftp"); //$NON-NLS-1$
if (!channel.isConnected()) {
if (DEBUG) {
log("channel.connect()"); //$NON-NLS-1$
}
channel.connect(10000);
}
synchronized (lock) {
usedChannels.put(channel, createUsageInfo(context));
}
return channel;
// String eToStr = e.toString();
// if (eToStr.indexOf("Auth cancel") >= 0 || eToStr.indexOf("Auth fail") >= 0 || eToStr.indexOf("session is down") >= 0) { //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
// if (session.isConnected()) {
// session.disconnect();
// session = null;
// }
// }
// if (needLog) {
// Activator.error("Failed to create direct connection", e); //$NON-NLS-1$
// }
// if (session != null) {
// session.disconnect();
// session = null;
// }
}
|
diff --git a/ui/webui/src/eu/sqooss/webui/view/TimelineView.java b/ui/webui/src/eu/sqooss/webui/view/TimelineView.java
index 6d0e3842..7e70d45c 100644
--- a/ui/webui/src/eu/sqooss/webui/view/TimelineView.java
+++ b/ui/webui/src/eu/sqooss/webui/view/TimelineView.java
@@ -1,648 +1,653 @@
/*
* This file is part of the Alitheia system, developed by the SQO-OSS
* consortium as part of the IST FP6 SQO-OSS project, number 033331.
*
* Copyright 2007-2008 by the SQO-OSS consortium members <[email protected]>
* Copyright 2007-2008-2008 by Sebastian Kuegler <[email protected]>
*
* 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.
*
* 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 eu.sqooss.webui.view;
import java.awt.Color;
import java.io.IOException;
import java.text.DateFormatSymbols;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartUtilities;
import org.jfree.chart.JFreeChart;
import org.jfree.data.time.Day;
import org.jfree.data.time.TimePeriodValues;
import org.jfree.data.time.TimePeriodValuesCollection;
import org.jfree.ui.RectangleInsets;
import eu.sqooss.webui.Functions;
import eu.sqooss.webui.Project;
import eu.sqooss.webui.datatype.Version;
import eu.sqooss.webui.util.VersionsList;
public class TimelineView extends AbstractDataView {
VersionsList versions = new VersionsList();
/**
* Instantiates a new <code>TimelineView</code> object, and initializes
* it with the given project object.
*
* @param project the project object
*/
public TimelineView(Project project) {
super();
this.project = project;
supportedCharts = TABLE_CHART + LINE_CHART;
viewDependencies = DEP_OTHER;
}
/**
* Loads all the necessary information, that is associated with the
* resources presented in this view.
*/
private void loadData() {
if ((project != null) && (project.isValid())) {
/*
* Load the list of versions referenced by events which occurred
* within the selected time period.
*/
if ((terrier != null)
&& (settings.getTvDateFrom() != null)
&& (settings.getTvDateFrom() != null))
versions.addAll(terrier.getVersionsTimeline(project.getId(),
settings.getTvDateFrom(), settings.getTvDateTill()));
}
}
private List<Version> getVersionsInPeriod(Calendar from, Calendar till) {
ArrayList<Version> result = new ArrayList<Version>();
for (Long timestamp : versions.sortByTimestamp().keySet()) {
if (timestamp != null) {
if (timestamp < from.getTimeInMillis()) continue;
if (timestamp >= till.getTimeInMillis()) break;
result.add(versions.getVersionByTimestamp(timestamp));
}
}
return result;
}
/* (non-Javadoc)
* @see eu.sqooss.webui.ListView#getHtml(long)
*/
public String getHtml(long in) {
if ((project == null) || (project.isValid() == false))
return(sp(in) + Functions.error("Invalid project!"));
// Hold the accumulated HTML content
StringBuffer b = new StringBuffer("");
// Load the selected versions' data
loadData();
if ((settings.getTvDateFrom() != null)
&& (settings.getTvDateFrom() != null)) {
int viewRange = settings.getTvViewRange() != null
? settings.getTvViewRange().intValue() : 1;
Calendar calLow = Calendar.getInstance();
calLow.setTimeInMillis(settings.getTvDateFrom());
calLow.set(Calendar.HOUR, 0);
calLow.set(Calendar.MINUTE, 0);
calLow.set(Calendar.SECOND, 0);
calLow.set(Calendar.MILLISECOND, 0);
Calendar calHigh;
switch (viewRange) {
case 1:
calHigh = (Calendar) calLow.clone();
calHigh.add(Calendar.DATE, 1);
break;
case 2:
while (calLow.get(Calendar.DAY_OF_WEEK) != Calendar.MONDAY)
calLow.add(Calendar.DATE, -1);
calHigh = (Calendar) calLow.clone();
calHigh.add(Calendar.DATE, 7);
break;
case 3:
calLow.set(Calendar.DATE, 1);
calHigh = (Calendar) calLow.clone();
calHigh.add(Calendar.MONTH, 1);
calHigh.set(Calendar.DATE, 1);
break;
case 4:
calLow.set(Calendar.DATE, 1);
calHigh = (Calendar) calLow.clone();
calHigh.add(Calendar.YEAR, 1);
calHigh.set(Calendar.DATE, 1);
calHigh.set(Calendar.MONTH, Calendar.JANUARY);
break;
default:
calHigh = (Calendar) calLow.clone();
calHigh.add(Calendar.DATE, 1);
break;
}
switch (chartType) {
case TABLE_CHART:
b.append(tableChart(in, calLow, calHigh));
break;
case LINE_CHART:
String chartFile = lineChart(calLow, calHigh);
if (chartFile != null) {
chartFile = "/tmp/" + chartFile;
b.append(sp(in++) + "<table>\n");
b.append(sp(in++) + "</tr>\n");
b.append(sp(in) + "<td"
+ " class=\"dvChartImage\""
+ "<a class=\"dvChartImage\""
+ " href=\"/fullscreen.jsp?"
+ "chartfile=" + chartFile.replace("thb", "img") + "\">"
+ "<img src=\"" + chartFile + "\">"
+ "</a>"
+ "</td>\n");
b.append(sp(--in) + "</tr>\n");
b.append(sp(--in) + "</table>\n");
}
else
b.append(Functions.information(
"Inapplicable results."));
break;
default:
b.append(tableChart(in, calLow, calHigh));
break;
}
}
else {
b.append(sp(in)
+ "Select the time period for which you want to display results.");
}
return b.toString();
}
/**
* Renders a control panel, that can be used for displaying various
* information related to this view.
*
* @param in the indentation depth
*
* @return The generated HTML content.
*/
public String getInfo (long in) {
if ((project == null) || (project.isValid() == false))
return(sp(in) + Functions.error("Invalid project!"));
// Hold the accumulated HTML content
StringBuilder b = new StringBuilder("");
// Create the "Info" table
b.append(sp(in++) + "<table>\n");
// Project versions
b.append(sp(in++) + "<tr>\n");
b.append(sp(in) + "<td><b>Versions:</b></td>"
+ "<td>"
+ "<a href=\"/versions.jsp\">"
+ project.getVersionsCount()
+ "</a>"
+ "</td>\n");
b.append(sp(--in) + "</tr>\n");
// First and last version timestamps
SimpleDateFormat dateFormat = new SimpleDateFormat(
"dd MMM yyyy", settings.getUserLocale());
b.append(sp(in++) + "<tr>\n");
b.append(sp(in) + "<td><b>First:</b></td>"
+ "<td>"
+ dateFormat.format(project.getFirstVersion().getTimestamp())
+ "</td>\n");
b.append(sp(--in) + "</tr>\n");
b.append(sp(in++) + "<tr>\n");
b.append(sp(in) + "<td><b>Last:</b></td>"
+ "<td>"
+ dateFormat.format(project.getLastVersion().getTimestamp())
+ "</td>\n");
b.append(sp(--in) + "</tr>\n");
// Close the "Info" table
b.append(sp(--in) + "</table>\n");
return b.toString();
}
private String renderMonthSelect(long in, int selected, String idSuffix) {
// Hold the accumulated HTML content
StringBuilder b = new StringBuilder("");
// Used to retrieve a localized date token names
DateFormatSymbols dateLocalised =
new DateFormatSymbols(settings.getUserLocale());
// Create the select box
b.append(sp(in++) + "<select id=\"month" + idSuffix + "\""
+ " class=\"icoTextInput\""
+ " onChange=\"javascript:"
+ " updateCalendar('" + idSuffix + "');\">\n");
for (int i=0 ; i<12 ; i++) {
if (selected != i)
b.append(sp(in) + "<option value=\"" + i + "\">"
+ dateLocalised.getShortMonths()[i] + "</option>\n");
else
b.append(sp(in) + "<option value=\"" + i + "\" selected>"
+ dateLocalised.getShortMonths()[i] + "</option>\n");
}
b.append(sp(--in) + "</select>\n");
return b.toString();
}
private String renderYearSelect(
long in, long first, long last, long selected, String idSuffix) {
// Hold the accumulated HTML content
StringBuilder b = new StringBuilder("");
// Create the select box
b.append(sp(in++) + "<select id=\"year" + idSuffix + "\""
+ " class=\"icoTextInput\""
+ " onChange=\"javascript:"
+ " updateCalendar('" + idSuffix + "');\">\n");
for (long i=first ; i<=last ; i++) {
if (selected != i)
b.append(sp(in) + "<option value=\"" + i + "\">"
+ i + "</option>\n");
else
b.append(sp(in) + "<option value=\"" + i + "\" selected>"
+ i + "</option>\n");
}
b.append(sp(--in) + "</select>\n");
return b.toString();
}
/**
* Renders a control panel, that can be used for controlling various
* rendering features of this view.
*
* @param in the indentation depth
*
* @return The generated HTML content.
*/
public String getControls (long in) {
if ((project == null) || (project.isValid() == false))
return(sp(in) + Functions.error("Invalid project!"));
// Hold the accumulated HTML content
StringBuilder b = new StringBuilder("");
// Initialize both calendar objects
Calendar projectStart = Calendar.getInstance();
Calendar rangeStart = Calendar.getInstance();
projectStart.setTimeInMillis(project.getFirstVersion().getTimestamp());
if (settings.getTvDateFrom() != null)
rangeStart.setTimeInMillis(settings.getTvDateFrom());
else
rangeStart = (Calendar) projectStart.clone();
Calendar projectNow = Calendar.getInstance();
Calendar rangeEnd = Calendar.getInstance();
projectNow.setTimeInMillis(project.getLastVersion().getTimestamp());
if (settings.getTvDateTill() != null)
rangeEnd.setTimeInMillis(settings.getTvDateTill());
else
rangeEnd = (Calendar) projectNow.clone();
// Render both calendars and their control fields
Calendar phases = Calendar.getInstance();
String[] suffix = new String[]{"From", "Till"};
for (int i=0 ; i<2 ; i++) {
phases = (i == 0) ? rangeStart : rangeEnd;
// Calendar's navigation tool bar
b.append(sp(in++) + "<div class=\"calLabel\">\n");
b.append(sp(in) + "<label class=\"calLabel\""
+ " for=\"day" + suffix[i] + "\">" + suffix[i] + ":</label>\n");
b.append(sp(in) + "<input id=\"day" + suffix[i] + "\" type=\"text\""
+ " class=\"icoTextInput\""
+ " style=\"width: 2em; text-align: center;\""
+ " maxlength=\"2\" value=\"" + phases.get(Calendar.DAY_OF_MONTH) + "\""
+ " onChange=\"javascript:"
+ " updateCalendar('" + suffix[i] + "');\">\n");
b.append(renderMonthSelect(
in, phases.get(Calendar.MONTH), suffix[i]));
b.append(renderYearSelect(in, projectStart.get(Calendar.YEAR),
projectNow.get(Calendar.YEAR), phases.get(Calendar.YEAR),
suffix[i]));
b.append(sp(in) + "<img class=\"icon2\""
+ " alt=\"Calendar\""
+ " title=\"Show calendar\""
+ " src=\"/img/icons/16x16/calendar.png\""
+ " onClick=\"javascript: toggleCalendar('" + suffix[i] + "')\""
+ ">");
b.append(sp(--in) + "</div>");
// Calendar's content
b.append(sp(in)+ "<div id=\"cal" + suffix[i] +"\""
+ " style=\"display: none;\">"
+ "<script type=\"text/javascript\">"
+ "document.write(renderCalendar("
+ phases.get(Calendar.YEAR) + " ,"
+ phases.get(Calendar.MONTH) + " ,'"
+ suffix[i] + "'));"
+ "</script>"
+ "</div>");
}
b.append(sp(in++) + "<div class=\"calLabel\">\n");
b.append(sp(in) + "<form>");
for (int i=0 ; i<2 ; i++) {
phases = (i == 0) ? projectStart : projectNow;
b.append(sp(in) + "<input type=\"hidden\""
+ " id=\"date" + suffix[i] + "\""
+ " name=\"date" + suffix[i] + "\""
+ " value=\"" + phases.getTimeInMillis() + "\""
+ ">\n");
}
b.append(sp(in) + "<input class=\"icoButton\" type=\"submit\""
+ " value=\"Apply\">\n");
b.append(sp(in) + "</form>");
b.append(sp(--in) + "</div>");
return b.toString();
}
private String tableChart (long in, Calendar calLow, Calendar calHigh) {
// Hold the accumulated HTML content
StringBuilder b = new StringBuilder("");
b.append(sp(in++) + "<table>\n");
// Table header
b.append(sp(in++) + "<thead>\n");
b.append(sp(in) + "<tr>"
+ "<td style=\"width: 20%;\"></td>"
+ "<td style=\"width: 10%;\"></td>"
+ "<td style=\"width: 70%;\"></td>"
+ "</tr>\n");
b.append(sp(--in) + "</thead>\n");
- boolean firstResult = true;
+ boolean displayHeader = true;
long viewRange = settings.getTvViewRange() != null
? settings.getTvViewRange() : 1;
while (calLow.getTimeInMillis() < settings.getTvDateTill()) {
if (viewRange == 2) {
- Calendar calPeriod;
- if ((calLow.get(Calendar.MONTH) != calHigh.get(Calendar.MONTH))
- || (firstResult)) {
- firstResult = false;
- calPeriod = (Calendar) calLow.clone();
- calPeriod.add(Calendar.MONTH, 1);
- if (!((getVersionsInPeriod(calLow, calPeriod).size() == 0)
+ Calendar calTmp;
+ calTmp = (Calendar) calLow.clone();
+ calTmp.add(Calendar.DATE, -7);
+ if (calLow.get(Calendar.MONTH) != calTmp.get(Calendar.MONTH))
+ displayHeader = true;
+ if (displayHeader) {
+ displayHeader = false;
+ calTmp = (Calendar) calLow.clone();
+ calTmp.add(Calendar.MONTH, 1);
+ if (!((getVersionsInPeriod(calLow, calTmp).size() == 0)
&& (settings.getTvShowEmptyState() == false)))
b.append(sp(in) + "<tr>"
+ "<td class=\"def_head_center\" colspan=\"3\">"
+ Functions.formatMonth(
calHigh.getTimeInMillis(),
settings.getUserLocale())
+ ", " + calHigh.get(Calendar.YEAR)
+"</td>"
+ "</tr>\n");
}
int numVersions = getVersionsInPeriod(calLow, calHigh).size();
if (!((numVersions == 0) && (settings.getTvShowEmptyState() == false))) {
b.append(sp(in++) + "<tr>\n");
b.append(sp(in) + "<td class=\"def_major\">"
+ "Week " + calLow.get(Calendar.WEEK_OF_YEAR)
+ "</td>\n");
b.append(sp(in) + "<td class=\"def_right\">"
+ numVersions + "</td>\n");
}
if (numVersions > 0) {
b.append(sp(in) + "<td class=\"def\">"
+ "<img style=\"height: 10px; width: 4px;\""
+ " src=\"/img/icons/16x16/testl.png\">"
+ "<img style=\"height: 10px; width: "
+ numVersions
+ "px;\""
+ " src=\"/img/icons/16x16/testm.png\">"
+ "<img style=\"height: 10px; width: 4px;\""
+ " src=\"/img/icons/16x16/testr.png\">"
+ " "
+ "</td>\n");
b.append(sp(--in) + "</tr>\n");
}
else if (settings.getTvShowEmptyState()) {
b.append(sp(in) + "<td class=\"def\"> </td>\n");
b.append(sp(--in) + "</tr>\n");
}
calLow.add(Calendar.DATE, 7);
calHigh.add(Calendar.DATE, 7);
if (calHigh.getTimeInMillis() > settings.getTvDateTill())
calHigh.setTimeInMillis(settings.getTvDateTill() + 1);
}
else if (viewRange == 3) {
Calendar calPeriod;
- if ((calLow.get(Calendar.MONTH) == 0)
- || (firstResult)) {
- firstResult = false;
+ if (calLow.get(Calendar.MONTH) == 0)
+ displayHeader = true;
+ if (displayHeader) {
+ displayHeader = false;
calPeriod = (Calendar) calLow.clone();
calPeriod.add(Calendar.YEAR, 1);
if (!((getVersionsInPeriod(calLow, calPeriod).size() == 0)
&& (settings.getTvShowEmptyState() == false)))
b.append(sp(in) + "<tr>"
+ "<td class=\"def_head_center\" colspan=\"3\">"
+ calLow.get(Calendar.YEAR)
+"</td>"
+ "</tr>\n");
}
int numVersions = getVersionsInPeriod(calLow, calHigh).size();
if (!((numVersions == 0) && (settings.getTvShowEmptyState() == false))) {
b.append(sp(in++) + "<tr>\n");
b.append(sp(in) + "<td class=\"def_major\">"
+ Functions.formatMonth(
calLow.getTimeInMillis(),
settings.getUserLocale())
+ "</td>\n");
b.append(sp(in) + "<td class=\"def_right\">"
+ numVersions + "</td>\n");
}
if (numVersions > 0) {
b.append(sp(in) + "<td class=\"def\">"
+ "<img style=\"height: 10px; width: 4px;\""
+ " src=\"/img/icons/16x16/testl.png\">"
+ "<img style=\"height: 10px; width: "
+ numVersions
+ "px;\""
+ " src=\"/img/icons/16x16/testm.png\">"
+ "<img style=\"height: 10px; width: 4px;\""
+ " src=\"/img/icons/16x16/testr.png\">"
+ " "
+ "</td>\n");
b.append(sp(--in) + "</tr>\n");
}
else if (settings.getTvShowEmptyState()) {
b.append(sp(in) + "<td class=\"def\"> </td>\n");
b.append(sp(--in) + "</tr>\n");
}
calLow.add(Calendar.MONTH, 1);
calLow.set(Calendar.DATE, 1);
calHigh.add(Calendar.MONTH, 1);
calHigh.set(Calendar.DATE, 1);
if (calHigh.getTimeInMillis() > settings.getTvDateTill())
calHigh.setTimeInMillis(settings.getTvDateTill() + 1);
}
else if (viewRange == 4) {
int numVersions = getVersionsInPeriod(calLow, calHigh).size();
if (!((numVersions == 0) && (settings.getTvShowEmptyState() == false))) {
b.append(sp(in++) + "<tr>\n");
b.append(sp(in) + "<td class=\"def_major\">"
+ calLow.get(Calendar.YEAR)
+ "</td>\n");
b.append(sp(in) + "<td class=\"def_right\">"
+ numVersions + "</td>\n");
}
if (numVersions > 0) {
b.append(sp(in) + "<td class=\"def\">"
+ "<img style=\"height: 10px; width: 4px;\""
+ " src=\"/img/icons/16x16/testl.png\">"
+ "<img style=\"height: 10px; width: "
+ numVersions
+ "px;\""
+ " src=\"/img/icons/16x16/testm.png\">"
+ "<img style=\"height: 10px; width: 4px;\""
+ " src=\"/img/icons/16x16/testr.png\">"
+ " "
+ "</td>\n");
b.append(sp(--in) + "</tr>\n");
}
else if (settings.getTvShowEmptyState()) {
b.append(sp(in) + "<td class=\"def\"> </td>\n");
b.append(sp(--in) + "</tr>\n");
}
calLow.add(Calendar.YEAR, 1);
calLow.set(Calendar.DATE, 1);
calLow.set(Calendar.MONTH, Calendar.JANUARY);
calHigh.add(Calendar.YEAR, 1);
calHigh.set(Calendar.DATE, 1);
calHigh.set(Calendar.MONTH, Calendar.JANUARY);
if (calHigh.getTimeInMillis() > settings.getTvDateTill())
calHigh.setTimeInMillis(settings.getTvDateTill() + 1);
}
else {
Calendar calPeriod;
- if ((calLow.get(Calendar.DAY_OF_WEEK) == Calendar.MONDAY)
- || (firstResult)) {
- firstResult = false;
+ if (calLow.get(Calendar.DAY_OF_WEEK) == Calendar.MONDAY)
+ displayHeader = true;
+ if (displayHeader) {
+ displayHeader = false;
calPeriod = (Calendar) calLow.clone();
calPeriod.add(Calendar.DATE, 7);
if (!((getVersionsInPeriod(calLow, calPeriod).size() == 0)
&& (settings.getTvShowEmptyState() == false)))
b.append(sp(in) + "<tr>"
+ "<td class=\"def_head_center\" colspan=\"3\">"
+ "Week " + calLow.get(Calendar.WEEK_OF_YEAR)
+ ", " + calLow.get(Calendar.YEAR)
+"</td>"
+ "</tr>\n");
}
int numVersions = getVersionsInPeriod(calLow, calHigh).size();
if (!((numVersions == 0) && (settings.getTvShowEmptyState() == false))) {
b.append(sp(in++) + "<tr>\n");
b.append(sp(in) + "<td class=\"def_major\">"
+ Functions.formatDaystamp(
calLow.getTimeInMillis(),
settings.getUserLocale())
+ "</td>\n");
b.append(sp(in) + "<td class=\"def_right\">"
+ numVersions + "</td>\n");
}
if (numVersions > 0) {
b.append(sp(in) + "<td class=\"def\">"
+ "<img style=\"height: 10px; width: 4px;\""
+ " src=\"/img/icons/16x16/testl.png\">"
+ "<img style=\"height: 10px; width: "
+ numVersions
+ "px;\""
+ " src=\"/img/icons/16x16/testm.png\">"
+ "<img style=\"height: 10px; width: 4px;\""
+ " src=\"/img/icons/16x16/testr.png\">"
+ " "
+ "</td>\n");
b.append(sp(--in) + "</tr>\n");
}
else if (settings.getTvShowEmptyState()) {
b.append(sp(in) + "<td class=\"def\"> </td>\n");
b.append(sp(--in) + "</tr>\n");
}
calLow.add(Calendar.DATE, 1);
calHigh.add(Calendar.DATE, 1);
}
}
b.append(sp(--in) + "</table>\n");
return b.toString();
}
private String lineChart (Calendar calLow, Calendar calHigh) {
// Construct the chart's dataset
TimePeriodValuesCollection data = new TimePeriodValuesCollection();
// TODO:: Quick definition. Rework to support bug and email timelines.
TimePeriodValues versionsData = new TimePeriodValues("Versions");
while (calLow.getTimeInMillis() < settings.getTvDateTill()) {
int numVersions = getVersionsInPeriod(calLow, calHigh).size();
versionsData.add(
new Day(calLow.getTime()),
new Double(numVersions));
calLow.add(Calendar.DATE, 1);
calHigh.add(Calendar.DATE, 1);
}
if (versionsData.getItemCount() > 0)
data.addSeries(versionsData);
// Generate the chart
if (data.getSeriesCount() > 0) {
JFreeChart chart;
chart = ChartFactory.createTimeSeriesChart(
null, "Time", "Result",
data,
true, true, false);
chart.setBackgroundPaint(new Color(0, 0, 0, 0));
chart.setPadding(RectangleInsets.ZERO_INSETS);
// Save the chart into a temporary file
try {
java.io.File image = java.io.File.createTempFile(
"img", ".png", settings.getTempFolder());
java.io.File thumbnail = new java.io.File(
settings.getTempFolder()
+ java.io.File.separator
+ image.getName().replace("img", "thb"));
ChartUtilities.saveChartAsPNG(image, chart, 960, 720);
ChartUtilities.saveChartAsPNG(thumbnail, chart, 320, 240);
return thumbnail.getName();
}
catch (IOException e) { /* Do nothing. */ }
}
return null;
}
}
| false | true | private String tableChart (long in, Calendar calLow, Calendar calHigh) {
// Hold the accumulated HTML content
StringBuilder b = new StringBuilder("");
b.append(sp(in++) + "<table>\n");
// Table header
b.append(sp(in++) + "<thead>\n");
b.append(sp(in) + "<tr>"
+ "<td style=\"width: 20%;\"></td>"
+ "<td style=\"width: 10%;\"></td>"
+ "<td style=\"width: 70%;\"></td>"
+ "</tr>\n");
b.append(sp(--in) + "</thead>\n");
boolean firstResult = true;
long viewRange = settings.getTvViewRange() != null
? settings.getTvViewRange() : 1;
while (calLow.getTimeInMillis() < settings.getTvDateTill()) {
if (viewRange == 2) {
Calendar calPeriod;
if ((calLow.get(Calendar.MONTH) != calHigh.get(Calendar.MONTH))
|| (firstResult)) {
firstResult = false;
calPeriod = (Calendar) calLow.clone();
calPeriod.add(Calendar.MONTH, 1);
if (!((getVersionsInPeriod(calLow, calPeriod).size() == 0)
&& (settings.getTvShowEmptyState() == false)))
b.append(sp(in) + "<tr>"
+ "<td class=\"def_head_center\" colspan=\"3\">"
+ Functions.formatMonth(
calHigh.getTimeInMillis(),
settings.getUserLocale())
+ ", " + calHigh.get(Calendar.YEAR)
+"</td>"
+ "</tr>\n");
}
int numVersions = getVersionsInPeriod(calLow, calHigh).size();
if (!((numVersions == 0) && (settings.getTvShowEmptyState() == false))) {
b.append(sp(in++) + "<tr>\n");
b.append(sp(in) + "<td class=\"def_major\">"
+ "Week " + calLow.get(Calendar.WEEK_OF_YEAR)
+ "</td>\n");
b.append(sp(in) + "<td class=\"def_right\">"
+ numVersions + "</td>\n");
}
if (numVersions > 0) {
b.append(sp(in) + "<td class=\"def\">"
+ "<img style=\"height: 10px; width: 4px;\""
+ " src=\"/img/icons/16x16/testl.png\">"
+ "<img style=\"height: 10px; width: "
+ numVersions
+ "px;\""
+ " src=\"/img/icons/16x16/testm.png\">"
+ "<img style=\"height: 10px; width: 4px;\""
+ " src=\"/img/icons/16x16/testr.png\">"
+ " "
+ "</td>\n");
b.append(sp(--in) + "</tr>\n");
}
else if (settings.getTvShowEmptyState()) {
b.append(sp(in) + "<td class=\"def\"> </td>\n");
b.append(sp(--in) + "</tr>\n");
}
calLow.add(Calendar.DATE, 7);
calHigh.add(Calendar.DATE, 7);
if (calHigh.getTimeInMillis() > settings.getTvDateTill())
calHigh.setTimeInMillis(settings.getTvDateTill() + 1);
}
else if (viewRange == 3) {
Calendar calPeriod;
if ((calLow.get(Calendar.MONTH) == 0)
|| (firstResult)) {
firstResult = false;
calPeriod = (Calendar) calLow.clone();
calPeriod.add(Calendar.YEAR, 1);
if (!((getVersionsInPeriod(calLow, calPeriod).size() == 0)
&& (settings.getTvShowEmptyState() == false)))
b.append(sp(in) + "<tr>"
+ "<td class=\"def_head_center\" colspan=\"3\">"
+ calLow.get(Calendar.YEAR)
+"</td>"
+ "</tr>\n");
}
int numVersions = getVersionsInPeriod(calLow, calHigh).size();
if (!((numVersions == 0) && (settings.getTvShowEmptyState() == false))) {
b.append(sp(in++) + "<tr>\n");
b.append(sp(in) + "<td class=\"def_major\">"
+ Functions.formatMonth(
calLow.getTimeInMillis(),
settings.getUserLocale())
+ "</td>\n");
b.append(sp(in) + "<td class=\"def_right\">"
+ numVersions + "</td>\n");
}
if (numVersions > 0) {
b.append(sp(in) + "<td class=\"def\">"
+ "<img style=\"height: 10px; width: 4px;\""
+ " src=\"/img/icons/16x16/testl.png\">"
+ "<img style=\"height: 10px; width: "
+ numVersions
+ "px;\""
+ " src=\"/img/icons/16x16/testm.png\">"
+ "<img style=\"height: 10px; width: 4px;\""
+ " src=\"/img/icons/16x16/testr.png\">"
+ " "
+ "</td>\n");
b.append(sp(--in) + "</tr>\n");
}
else if (settings.getTvShowEmptyState()) {
b.append(sp(in) + "<td class=\"def\"> </td>\n");
b.append(sp(--in) + "</tr>\n");
}
calLow.add(Calendar.MONTH, 1);
calLow.set(Calendar.DATE, 1);
calHigh.add(Calendar.MONTH, 1);
calHigh.set(Calendar.DATE, 1);
if (calHigh.getTimeInMillis() > settings.getTvDateTill())
calHigh.setTimeInMillis(settings.getTvDateTill() + 1);
}
else if (viewRange == 4) {
int numVersions = getVersionsInPeriod(calLow, calHigh).size();
if (!((numVersions == 0) && (settings.getTvShowEmptyState() == false))) {
b.append(sp(in++) + "<tr>\n");
b.append(sp(in) + "<td class=\"def_major\">"
+ calLow.get(Calendar.YEAR)
+ "</td>\n");
b.append(sp(in) + "<td class=\"def_right\">"
+ numVersions + "</td>\n");
}
if (numVersions > 0) {
b.append(sp(in) + "<td class=\"def\">"
+ "<img style=\"height: 10px; width: 4px;\""
+ " src=\"/img/icons/16x16/testl.png\">"
+ "<img style=\"height: 10px; width: "
+ numVersions
+ "px;\""
+ " src=\"/img/icons/16x16/testm.png\">"
+ "<img style=\"height: 10px; width: 4px;\""
+ " src=\"/img/icons/16x16/testr.png\">"
+ " "
+ "</td>\n");
b.append(sp(--in) + "</tr>\n");
}
else if (settings.getTvShowEmptyState()) {
b.append(sp(in) + "<td class=\"def\"> </td>\n");
b.append(sp(--in) + "</tr>\n");
}
calLow.add(Calendar.YEAR, 1);
calLow.set(Calendar.DATE, 1);
calLow.set(Calendar.MONTH, Calendar.JANUARY);
calHigh.add(Calendar.YEAR, 1);
calHigh.set(Calendar.DATE, 1);
calHigh.set(Calendar.MONTH, Calendar.JANUARY);
if (calHigh.getTimeInMillis() > settings.getTvDateTill())
calHigh.setTimeInMillis(settings.getTvDateTill() + 1);
}
else {
Calendar calPeriod;
if ((calLow.get(Calendar.DAY_OF_WEEK) == Calendar.MONDAY)
|| (firstResult)) {
firstResult = false;
calPeriod = (Calendar) calLow.clone();
calPeriod.add(Calendar.DATE, 7);
if (!((getVersionsInPeriod(calLow, calPeriod).size() == 0)
&& (settings.getTvShowEmptyState() == false)))
b.append(sp(in) + "<tr>"
+ "<td class=\"def_head_center\" colspan=\"3\">"
+ "Week " + calLow.get(Calendar.WEEK_OF_YEAR)
+ ", " + calLow.get(Calendar.YEAR)
+"</td>"
+ "</tr>\n");
}
int numVersions = getVersionsInPeriod(calLow, calHigh).size();
if (!((numVersions == 0) && (settings.getTvShowEmptyState() == false))) {
b.append(sp(in++) + "<tr>\n");
b.append(sp(in) + "<td class=\"def_major\">"
+ Functions.formatDaystamp(
calLow.getTimeInMillis(),
settings.getUserLocale())
+ "</td>\n");
b.append(sp(in) + "<td class=\"def_right\">"
+ numVersions + "</td>\n");
}
if (numVersions > 0) {
b.append(sp(in) + "<td class=\"def\">"
+ "<img style=\"height: 10px; width: 4px;\""
+ " src=\"/img/icons/16x16/testl.png\">"
+ "<img style=\"height: 10px; width: "
+ numVersions
+ "px;\""
+ " src=\"/img/icons/16x16/testm.png\">"
+ "<img style=\"height: 10px; width: 4px;\""
+ " src=\"/img/icons/16x16/testr.png\">"
+ " "
+ "</td>\n");
b.append(sp(--in) + "</tr>\n");
}
else if (settings.getTvShowEmptyState()) {
b.append(sp(in) + "<td class=\"def\"> </td>\n");
b.append(sp(--in) + "</tr>\n");
}
calLow.add(Calendar.DATE, 1);
calHigh.add(Calendar.DATE, 1);
}
}
b.append(sp(--in) + "</table>\n");
return b.toString();
}
| private String tableChart (long in, Calendar calLow, Calendar calHigh) {
// Hold the accumulated HTML content
StringBuilder b = new StringBuilder("");
b.append(sp(in++) + "<table>\n");
// Table header
b.append(sp(in++) + "<thead>\n");
b.append(sp(in) + "<tr>"
+ "<td style=\"width: 20%;\"></td>"
+ "<td style=\"width: 10%;\"></td>"
+ "<td style=\"width: 70%;\"></td>"
+ "</tr>\n");
b.append(sp(--in) + "</thead>\n");
boolean displayHeader = true;
long viewRange = settings.getTvViewRange() != null
? settings.getTvViewRange() : 1;
while (calLow.getTimeInMillis() < settings.getTvDateTill()) {
if (viewRange == 2) {
Calendar calTmp;
calTmp = (Calendar) calLow.clone();
calTmp.add(Calendar.DATE, -7);
if (calLow.get(Calendar.MONTH) != calTmp.get(Calendar.MONTH))
displayHeader = true;
if (displayHeader) {
displayHeader = false;
calTmp = (Calendar) calLow.clone();
calTmp.add(Calendar.MONTH, 1);
if (!((getVersionsInPeriod(calLow, calTmp).size() == 0)
&& (settings.getTvShowEmptyState() == false)))
b.append(sp(in) + "<tr>"
+ "<td class=\"def_head_center\" colspan=\"3\">"
+ Functions.formatMonth(
calHigh.getTimeInMillis(),
settings.getUserLocale())
+ ", " + calHigh.get(Calendar.YEAR)
+"</td>"
+ "</tr>\n");
}
int numVersions = getVersionsInPeriod(calLow, calHigh).size();
if (!((numVersions == 0) && (settings.getTvShowEmptyState() == false))) {
b.append(sp(in++) + "<tr>\n");
b.append(sp(in) + "<td class=\"def_major\">"
+ "Week " + calLow.get(Calendar.WEEK_OF_YEAR)
+ "</td>\n");
b.append(sp(in) + "<td class=\"def_right\">"
+ numVersions + "</td>\n");
}
if (numVersions > 0) {
b.append(sp(in) + "<td class=\"def\">"
+ "<img style=\"height: 10px; width: 4px;\""
+ " src=\"/img/icons/16x16/testl.png\">"
+ "<img style=\"height: 10px; width: "
+ numVersions
+ "px;\""
+ " src=\"/img/icons/16x16/testm.png\">"
+ "<img style=\"height: 10px; width: 4px;\""
+ " src=\"/img/icons/16x16/testr.png\">"
+ " "
+ "</td>\n");
b.append(sp(--in) + "</tr>\n");
}
else if (settings.getTvShowEmptyState()) {
b.append(sp(in) + "<td class=\"def\"> </td>\n");
b.append(sp(--in) + "</tr>\n");
}
calLow.add(Calendar.DATE, 7);
calHigh.add(Calendar.DATE, 7);
if (calHigh.getTimeInMillis() > settings.getTvDateTill())
calHigh.setTimeInMillis(settings.getTvDateTill() + 1);
}
else if (viewRange == 3) {
Calendar calPeriod;
if (calLow.get(Calendar.MONTH) == 0)
displayHeader = true;
if (displayHeader) {
displayHeader = false;
calPeriod = (Calendar) calLow.clone();
calPeriod.add(Calendar.YEAR, 1);
if (!((getVersionsInPeriod(calLow, calPeriod).size() == 0)
&& (settings.getTvShowEmptyState() == false)))
b.append(sp(in) + "<tr>"
+ "<td class=\"def_head_center\" colspan=\"3\">"
+ calLow.get(Calendar.YEAR)
+"</td>"
+ "</tr>\n");
}
int numVersions = getVersionsInPeriod(calLow, calHigh).size();
if (!((numVersions == 0) && (settings.getTvShowEmptyState() == false))) {
b.append(sp(in++) + "<tr>\n");
b.append(sp(in) + "<td class=\"def_major\">"
+ Functions.formatMonth(
calLow.getTimeInMillis(),
settings.getUserLocale())
+ "</td>\n");
b.append(sp(in) + "<td class=\"def_right\">"
+ numVersions + "</td>\n");
}
if (numVersions > 0) {
b.append(sp(in) + "<td class=\"def\">"
+ "<img style=\"height: 10px; width: 4px;\""
+ " src=\"/img/icons/16x16/testl.png\">"
+ "<img style=\"height: 10px; width: "
+ numVersions
+ "px;\""
+ " src=\"/img/icons/16x16/testm.png\">"
+ "<img style=\"height: 10px; width: 4px;\""
+ " src=\"/img/icons/16x16/testr.png\">"
+ " "
+ "</td>\n");
b.append(sp(--in) + "</tr>\n");
}
else if (settings.getTvShowEmptyState()) {
b.append(sp(in) + "<td class=\"def\"> </td>\n");
b.append(sp(--in) + "</tr>\n");
}
calLow.add(Calendar.MONTH, 1);
calLow.set(Calendar.DATE, 1);
calHigh.add(Calendar.MONTH, 1);
calHigh.set(Calendar.DATE, 1);
if (calHigh.getTimeInMillis() > settings.getTvDateTill())
calHigh.setTimeInMillis(settings.getTvDateTill() + 1);
}
else if (viewRange == 4) {
int numVersions = getVersionsInPeriod(calLow, calHigh).size();
if (!((numVersions == 0) && (settings.getTvShowEmptyState() == false))) {
b.append(sp(in++) + "<tr>\n");
b.append(sp(in) + "<td class=\"def_major\">"
+ calLow.get(Calendar.YEAR)
+ "</td>\n");
b.append(sp(in) + "<td class=\"def_right\">"
+ numVersions + "</td>\n");
}
if (numVersions > 0) {
b.append(sp(in) + "<td class=\"def\">"
+ "<img style=\"height: 10px; width: 4px;\""
+ " src=\"/img/icons/16x16/testl.png\">"
+ "<img style=\"height: 10px; width: "
+ numVersions
+ "px;\""
+ " src=\"/img/icons/16x16/testm.png\">"
+ "<img style=\"height: 10px; width: 4px;\""
+ " src=\"/img/icons/16x16/testr.png\">"
+ " "
+ "</td>\n");
b.append(sp(--in) + "</tr>\n");
}
else if (settings.getTvShowEmptyState()) {
b.append(sp(in) + "<td class=\"def\"> </td>\n");
b.append(sp(--in) + "</tr>\n");
}
calLow.add(Calendar.YEAR, 1);
calLow.set(Calendar.DATE, 1);
calLow.set(Calendar.MONTH, Calendar.JANUARY);
calHigh.add(Calendar.YEAR, 1);
calHigh.set(Calendar.DATE, 1);
calHigh.set(Calendar.MONTH, Calendar.JANUARY);
if (calHigh.getTimeInMillis() > settings.getTvDateTill())
calHigh.setTimeInMillis(settings.getTvDateTill() + 1);
}
else {
Calendar calPeriod;
if (calLow.get(Calendar.DAY_OF_WEEK) == Calendar.MONDAY)
displayHeader = true;
if (displayHeader) {
displayHeader = false;
calPeriod = (Calendar) calLow.clone();
calPeriod.add(Calendar.DATE, 7);
if (!((getVersionsInPeriod(calLow, calPeriod).size() == 0)
&& (settings.getTvShowEmptyState() == false)))
b.append(sp(in) + "<tr>"
+ "<td class=\"def_head_center\" colspan=\"3\">"
+ "Week " + calLow.get(Calendar.WEEK_OF_YEAR)
+ ", " + calLow.get(Calendar.YEAR)
+"</td>"
+ "</tr>\n");
}
int numVersions = getVersionsInPeriod(calLow, calHigh).size();
if (!((numVersions == 0) && (settings.getTvShowEmptyState() == false))) {
b.append(sp(in++) + "<tr>\n");
b.append(sp(in) + "<td class=\"def_major\">"
+ Functions.formatDaystamp(
calLow.getTimeInMillis(),
settings.getUserLocale())
+ "</td>\n");
b.append(sp(in) + "<td class=\"def_right\">"
+ numVersions + "</td>\n");
}
if (numVersions > 0) {
b.append(sp(in) + "<td class=\"def\">"
+ "<img style=\"height: 10px; width: 4px;\""
+ " src=\"/img/icons/16x16/testl.png\">"
+ "<img style=\"height: 10px; width: "
+ numVersions
+ "px;\""
+ " src=\"/img/icons/16x16/testm.png\">"
+ "<img style=\"height: 10px; width: 4px;\""
+ " src=\"/img/icons/16x16/testr.png\">"
+ " "
+ "</td>\n");
b.append(sp(--in) + "</tr>\n");
}
else if (settings.getTvShowEmptyState()) {
b.append(sp(in) + "<td class=\"def\"> </td>\n");
b.append(sp(--in) + "</tr>\n");
}
calLow.add(Calendar.DATE, 1);
calHigh.add(Calendar.DATE, 1);
}
}
b.append(sp(--in) + "</table>\n");
return b.toString();
}
|
diff --git a/test/src/com/redhat/ceylon/compiler/java/test/issues/IssuesTest_1000_1499.java b/test/src/com/redhat/ceylon/compiler/java/test/issues/IssuesTest_1000_1499.java
index 4125157c1..9544b9ef1 100644
--- a/test/src/com/redhat/ceylon/compiler/java/test/issues/IssuesTest_1000_1499.java
+++ b/test/src/com/redhat/ceylon/compiler/java/test/issues/IssuesTest_1000_1499.java
@@ -1,378 +1,377 @@
/*
* Copyright Red Hat Inc. and/or its affiliates and other contributors
* as indicated by the authors tag. All rights reserved.
*
* This copyrighted material is made available to anyone wishing to use,
* modify, copy, or redistribute it subject to the terms and conditions
* of the GNU General Public License version 2.
*
* This particular file is subject to the "Classpath" exception as provided in the
* LICENSE file that accompanied this code.
*
* This program is distributed in the hope that it will be useful, but WITHOUT A
* 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 distribution; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301, USA.
*/
package com.redhat.ceylon.compiler.java.test.issues;
import org.junit.Ignore;
import org.junit.Test;
import com.redhat.ceylon.compiler.java.test.CompilerError;
import com.redhat.ceylon.compiler.java.test.CompilerTest;
public class IssuesTest_1000_1499 extends CompilerTest {
@Override
protected ModuleWithArtifact getDestModuleWithArtifact(){
return new ModuleWithArtifact("com.redhat.ceylon.compiler.java.test.issues", "1");
}
@Override
protected String transformDestDir(String name) {
return name + "-1000-1499";
}
@Test
public void testBug1000() {
compile("bug10xx/Bug1000.ceylon");
}
@Test
public void testBug1001() {
compareWithJavaSource("bug10xx/Bug1001");
}
@Test
public void testBug1007() {
compareWithJavaSource("bug10xx/Bug1007");
}
@Test
public void testBug1011() {
compareWithJavaSource("bug10xx/Bug1011");
}
@Test
public void testBug1016() {
compareWithJavaSource("bug10xx/Bug1016");
}
@Test
public void testBug1024() {
compareWithJavaSource("bug10xx/Bug1024");
}
@Test
public void testBug1026() {
compileAndRun("com.redhat.ceylon.compiler.java.test.issues.bug10xx.bug1026", "bug10xx/Bug1026.ceylon");
}
@Test
public void testBug1029() {
compareWithJavaSource("bug10xx/Bug1029");
}
@Ignore("Disabled because of https://github.com/ceylon/ceylon-spec/issues/596")
@Test
public void testBug1036() {
compareWithJavaSource("bug10xx/Bug1036");
}
@Test
public void testBug1037() {
compile("bug10xx/bug1037/Bug1037Java.java");
}
@Test
public void testBug1041() {
compile("bug10xx/bug1041/Bug1041Java.java");
compareWithJavaSource("bug10xx/bug1041/Bug1041");
}
@Test
public void testBug1042() {
compareWithJavaSource("bug10xx/Bug1042");
}
@Test
public void testBug1043() {
compareWithJavaSource("bug10xx/Bug1043");
}
@Test
public void testBug1059() {
compareWithJavaSource("bug10xx/Bug1059");
}
@Test
public void testBug1064() {
compile("bug10xx/Bug1064.ceylon");
}
@Test
public void testBug1067() {
compareWithJavaSource("bug10xx/Bug1067");
}
@Test
public void testBug1071() {
compile("bug10xx/Bug1071.ceylon");
}
@Test
public void testBug1079() {
compareWithJavaSource("bug10xx/Bug1079");
}
@Test
public void testBug1080() {
compareWithJavaSource("bug10xx/Bug1080");
}
@Test
public void testBug1083() {
assertErrors("bug10xx/Bug1083",
new CompilerError(24, "ambiguous reference to overloaded method or class: BigInteger"));
}
@Test
public void testBug1089() {
compareWithJavaSource("bug10xx/Bug1089");
run("com.redhat.ceylon.compiler.java.test.issues.bug10xx.bug1089");
}
@Test
public void testBug1095() {
compareWithJavaSource("bug10xx/Bug1095");
}
@Test
public void testBug1095B() {
compareWithJavaSource("bug10xx/Bug1095B");
}
@Test
public void testBug1106() {
compareWithJavaSource("bug11xx/Bug1106");
}
@Test
public void testBug1108() {
compareWithJavaSource("bug11xx/Bug1108");
}
@Test
public void testBug1113() {
compareWithJavaSource("bug11xx/Bug1113");
}
@Test
public void testBug1114() {
compareWithJavaSource("bug11xx/Bug1114");
}
@Test
public void testBug1116() {
compareWithJavaSource("bug11xx/Bug1116");
}
@Test
public void testBug1117() {
compareWithJavaSource("bug11xx/Bug1117");
}
@Test
public void testBug1119() {
compareWithJavaSource("bug11xx/Bug1119");
}
@Test
public void testBug1120() {
compareWithJavaSource("bug11xx/Bug1120");
}
@Test
public void testBug1124() {
compareWithJavaSource("bug11xx/Bug1124");
}
@Test
public void testBug1127() {
compareWithJavaSource("bug11xx/Bug1127");
}
@Test
public void testBug1134() {
compareWithJavaSource("bug11xx/Bug1134");
}
@Test
public void testBug1132() {
compareWithJavaSource("bug11xx/Bug1132");
compileAndRun("com.redhat.ceylon.compiler.java.test.issues.bug11xx.bug1132_testX", "bug11xx/Bug1132_2.ceylon");
}
@Test
public void testBug1133() {
compareWithJavaSource("bug11xx/Bug1133");
}
@Test
public void testBug1135() {
compareWithJavaSource("bug11xx/Bug1135");
}
@Test
public void testBug1151() {
compareWithJavaSource("bug11xx/Bug1151");
run("com.redhat.ceylon.compiler.java.test.issues.bug11xx.bug1151_callsite");
}
@Test
public void testBug1152() {
compareWithJavaSource("bug11xx/Bug1152");
}
@Test
public void testBug1153() {
compileAndRun("com.redhat.ceylon.compiler.java.test.issues.bug11xx.Bug1153", "bug11xx/Bug1153.ceylon");
}
@Test
public void testBug1154() {
compareWithJavaSource("bug11xx/Bug1154");
}
@Ignore("To resolve for M6: https://github.com/ceylon/ceylon-compiler/issues/1155")
@Test
public void testBug1155() {
//compareWithJavaSource("bug11xx/Bug1155");
compileAndRun("com.redhat.ceylon.compiler.java.test.issues.bug11xx.bug1155",
"bug11xx/Bug1155.ceylon");
}
@Test
public void testBug1156() {
compile("bug11xx/Bug1156.java", "bug11xx/Bug1156.ceylon");
}
@Ignore("To resolve for M6: https://github.com/ceylon/ceylon-compiler/issues/1157")
@Test
public void testBug1157() {
compareWithJavaSource("bug11xx/Bug1157");
}
@Test
public void testBug1161() {
compareWithJavaSource("bug11xx/Bug1161");
}
@Ignore("To resolve for M6: https://github.com/ceylon/ceylon-compiler/issues/1165")
@Test
public void testBug1165() {
compareWithJavaSource("bug11xx/Bug1165");
}
@Test
public void testBug1174() {
compileAndRun("com.redhat.ceylon.compiler.java.test.issues.bug11xx.bug1174_callsite", "bug11xx/Bug1174.ceylon");
}
@Test
public void testBug1177() {
compareWithJavaSource("bug11xx/Bug1177");
}
@Test
public void testBug1180() {
compile("bug11xx/Bug1180_1.ceylon");
assertErrors("bug11xx/Bug1180_2",
- new CompilerError(25, "member containsAll is inherited ambiguously by Bug1180People from AbstractCollection and another subtype of List and so must be refined by Bug1180People"),
- new CompilerError(25, "formal member containsAll of List not implemented in class hierarchy")
+ new CompilerError(25, "ambiguous reference to overloaded method or class: ArrayList")
);
}
@Test
public void testBug1184() {
compareWithJavaSource("bug11xx/Bug1184");
}
@Test
public void testBug1188() {
compareWithJavaSource("bug11xx/Bug1188");
}
@Ignore("https://github.com/ceylon/ceylon-compiler/issues/1203")
@Test
public void testBug1203_fail() {
compileAndRun("com.redhat.ceylon.compiler.java.test.issues.bug11xx.bug1203", "bug12xx/Bug1203.ceylon");
}
@Test
public void testBug1204() {
compareWithJavaSource("bug12xx/Bug1204");
}
@Test
public void testBug1206() {
compareWithJavaSource("bug12xx/Bug1206");
}
@Test
public void testBug1207() {
compareWithJavaSource("bug12xx/Bug1207");
}
@Test
public void testBug1208() {
compareWithJavaSource("bug12xx/Bug1208");
}
@Test
public void testBug1211() {
compareWithJavaSource("bug12xx/Bug1211");
}
@Test
public void testBug1212() {
compile("bug12xx/Bug1212_1.ceylon");
compile("bug12xx/Bug1212_2.ceylon");
}
@Test
public void testBug1219() {
compareWithJavaSource("bug12xx/Bug1219");
}
@Ignore("https://github.com/ceylon/ceylon-compiler/issues/1221")
@Test
public void testBug1221() {
compareWithJavaSource("bug12xx/Bug1221");
}
@Test
public void testBug1225() {
compareWithJavaSource("bug12xx/Bug1225");
}
@Test
public void testBug1235() {
compareWithJavaSource("bug12xx/Bug1235");
}
@Test
public void testBug1236() {
compareWithJavaSource("bug12xx/Bug1236");
}
@Test
public void testBug1238() {
compile("bug12xx/Bug1238.java");
compareWithJavaSource("bug12xx/Bug1238");
}
}
| true | true | public void testBug1180() {
compile("bug11xx/Bug1180_1.ceylon");
assertErrors("bug11xx/Bug1180_2",
new CompilerError(25, "member containsAll is inherited ambiguously by Bug1180People from AbstractCollection and another subtype of List and so must be refined by Bug1180People"),
new CompilerError(25, "formal member containsAll of List not implemented in class hierarchy")
);
}
| public void testBug1180() {
compile("bug11xx/Bug1180_1.ceylon");
assertErrors("bug11xx/Bug1180_2",
new CompilerError(25, "ambiguous reference to overloaded method or class: ArrayList")
);
}
|
diff --git a/tests/src/com/vaadin/tests/components/combobox/ComboBoxLargeIcons.java b/tests/src/com/vaadin/tests/components/combobox/ComboBoxLargeIcons.java
index 1992c1294..0f8124ca2 100644
--- a/tests/src/com/vaadin/tests/components/combobox/ComboBoxLargeIcons.java
+++ b/tests/src/com/vaadin/tests/components/combobox/ComboBoxLargeIcons.java
@@ -1,44 +1,43 @@
package com.vaadin.tests.components.combobox;
import java.util.Date;
import com.vaadin.data.Item;
import com.vaadin.terminal.Resource;
import com.vaadin.terminal.ThemeResource;
import com.vaadin.tests.components.TestBase;
import com.vaadin.ui.ComboBox;
public class ComboBoxLargeIcons extends TestBase {
@Override
protected Integer getTicketNumber() {
return null;
}
@Override
protected String getDescription() {
return "<p>All items in the Combobox has large icons. The size of the dropdown should fit the contents, also when changing pages. The height of the dropdown shouldn't exceed the browser's viewport, but fewer items should be visible then.</p><p>The size of the shadow behind the dropdown must also be correctly sized.</p><p>Note that the image URL change for every restart to keep the browser from using cached images.</p>";
}
@Override
protected void setup() {
ComboBox cb = new ComboBox();
cb.addContainerProperty("icon", Resource.class, null);
cb.setItemIconPropertyId("icon");
getLayout().addComponent(cb);
cb.setNullSelectionAllowed(false);
String[] icons = new String[] { "folder-add", "folder-delete",
"arrow-down", "arrow-left", "arrow-right", "arrow-up",
"document-add", "document-delete", "document-doc",
"document-edit", "document-image", "document-pdf",
- "document-ppt", "document-txt", "document-web", "document-xls",
- "document" };
+ "document-ppt", "document-txt", "document-web", "document" };
for (String icon : icons) {
- Item item = cb.addItem(new Object());
+ Item item = cb.addItem(icon);
item.getItemProperty("icon").setValue(
- new ThemeResource("icons/64/" + icon + ".png?"
+ new ThemeResource("../runo/icons/32/" + icon + ".png?"
+ new Date().getTime()));
}
}
}
| false | true | protected void setup() {
ComboBox cb = new ComboBox();
cb.addContainerProperty("icon", Resource.class, null);
cb.setItemIconPropertyId("icon");
getLayout().addComponent(cb);
cb.setNullSelectionAllowed(false);
String[] icons = new String[] { "folder-add", "folder-delete",
"arrow-down", "arrow-left", "arrow-right", "arrow-up",
"document-add", "document-delete", "document-doc",
"document-edit", "document-image", "document-pdf",
"document-ppt", "document-txt", "document-web", "document-xls",
"document" };
for (String icon : icons) {
Item item = cb.addItem(new Object());
item.getItemProperty("icon").setValue(
new ThemeResource("icons/64/" + icon + ".png?"
+ new Date().getTime()));
}
}
| protected void setup() {
ComboBox cb = new ComboBox();
cb.addContainerProperty("icon", Resource.class, null);
cb.setItemIconPropertyId("icon");
getLayout().addComponent(cb);
cb.setNullSelectionAllowed(false);
String[] icons = new String[] { "folder-add", "folder-delete",
"arrow-down", "arrow-left", "arrow-right", "arrow-up",
"document-add", "document-delete", "document-doc",
"document-edit", "document-image", "document-pdf",
"document-ppt", "document-txt", "document-web", "document" };
for (String icon : icons) {
Item item = cb.addItem(icon);
item.getItemProperty("icon").setValue(
new ThemeResource("../runo/icons/32/" + icon + ".png?"
+ new Date().getTime()));
}
}
|
diff --git a/ps3mediaserver/net/pms/newgui/TranscodingTab.java b/ps3mediaserver/net/pms/newgui/TranscodingTab.java
index db42c7f9..55fccdc5 100644
--- a/ps3mediaserver/net/pms/newgui/TranscodingTab.java
+++ b/ps3mediaserver/net/pms/newgui/TranscodingTab.java
@@ -1,691 +1,691 @@
/*
* PS3 Media Server, for streaming any medias to your PS3.
* Copyright (C) 2008 A.Brochard
*
* 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; version 2
* of the License only.
*
* 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 Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package net.pms.newgui;
import java.awt.CardLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.util.ArrayList;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.JTree;
import javax.swing.SwingUtilities;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreePath;
import javax.swing.tree.TreeSelectionModel;
import net.pms.Messages;
import net.pms.PMS;
import net.pms.configuration.PmsConfiguration;
import net.pms.encoders.Player;
import com.jgoodies.forms.builder.PanelBuilder;
import com.jgoodies.forms.factories.Borders;
import com.jgoodies.forms.layout.CellConstraints;
import com.jgoodies.forms.layout.FormLayout;
import com.sun.jna.Platform;
public class TranscodingTab {
private final PmsConfiguration configuration;
TranscodingTab(PmsConfiguration configuration) {
this.configuration = configuration;
}
private JCheckBox disableSubs;
public JCheckBox getDisableSubs() {
return disableSubs;
}
private JTextField forcetranscode;
private JTextField notranscode;
private JTextField maxbuffer;
private JComboBox nbcores;
private DefaultMutableTreeNode parent[];
private JPanel tabbedPane;
private CardLayout cl;
private JTextField abitrate;
private JTextField maxbitrate;
private JTree tree;
private JCheckBox forcePCM;
private JCheckBox hdaudiopass;
private JCheckBox forceDTSinPCM;
private JComboBox channels;
private JComboBox vq;
private JCheckBox ac3remux;
private JCheckBox mpeg2remux;
private JCheckBox chapter_support;
private JTextField chapter_interval;
private static final int MAX_CORES = 32;
private void updateEngineModel() {
ArrayList<String> engines = new ArrayList<String>();
Object root = tree.getModel().getRoot();
for (int i = 0; i < tree.getModel().getChildCount(root); i++) {
Object firstChild = tree.getModel().getChild(root, i);
if (!tree.getModel().isLeaf(firstChild)) {
for (int j = 0; j < tree.getModel().getChildCount(firstChild); j++) {
Object secondChild = tree.getModel().getChild(firstChild, j);
if (secondChild instanceof TreeNodeSettings) {
TreeNodeSettings tns = (TreeNodeSettings) secondChild;
if (tns.isEnable() && tns.getPlayer() != null) {
engines.add(tns.getPlayer().id());
}
}
}
}
}
PMS.get().getFrame().setReloadable(true);
PMS.getConfiguration().setEnginesAsList(engines);
}
private void handleCardComponentChange(Component component) {
tabbedPane.setPreferredSize(component.getPreferredSize());
SwingUtilities.updateComponentTreeUI(tabbedPane);
}
public JComponent build() {
FormLayout mainlayout = new FormLayout(
"left:pref, pref, 7dlu, pref, pref, fill:10:grow",
"fill:10:grow"
);
PanelBuilder builder = new PanelBuilder(mainlayout);
builder.setBorder(Borders.DLU4_BORDER);
builder.setOpaque(true);
CellConstraints cc = new CellConstraints();
builder.add(buildRightTabbedPane(), cc.xyw(4, 1, 3));
builder.add(buildLeft(), cc.xy(2, 1));
return builder.getPanel();
}
public JComponent buildRightTabbedPane() {
cl = new CardLayout();
tabbedPane = new JPanel(cl);
tabbedPane.setBorder(BorderFactory.createEmptyBorder());
JScrollPane scrollPane = new JScrollPane(tabbedPane);
scrollPane.setBorder(null);
return scrollPane;
}
public JComponent buildLeft() {
FormLayout layout = new FormLayout(
"left:pref, pref, pref, pref, 0:grow",
"fill:10:grow, 3dlu, p, 3dlu, p, 3dlu, p");
PanelBuilder builder = new PanelBuilder(layout);
builder.setBorder(Borders.EMPTY_BORDER);
builder.setOpaque(false);
CellConstraints cc = new CellConstraints();
JButton but = new JButton(LooksFrame.readImageIcon("kdevelop_down-32.png"));
but.setToolTipText(Messages.getString("TrTab2.6"));
but.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
TreePath path = tree.getSelectionModel().getSelectionPath();
if (path != null && path.getLastPathComponent() instanceof TreeNodeSettings) {
TreeNodeSettings node = ((TreeNodeSettings) path.getLastPathComponent());
if (node.getPlayer() != null) {
DefaultTreeModel dtm = (DefaultTreeModel) tree.getModel(); // get the tree model
//now get the index of the selected node in the DefaultTreeModel
int index = dtm.getIndexOfChild(node.getParent(), node);
// if selected node is first, return (can't move it up)
if (index < node.getParent().getChildCount() - 1) {
dtm.insertNodeInto(node, (DefaultMutableTreeNode) node.getParent(), index + 1); // move the node
dtm.reload();
for (int i = 0; i < tree.getRowCount(); i++) {
tree.expandRow(i);
}
tree.getSelectionModel().setSelectionPath(new TreePath(node.getPath()));
updateEngineModel();
}
}
}
}
});
builder.add(but, cc.xy(2, 3));
JButton but2 = new JButton(LooksFrame.readImageIcon("up-32.png"));
but2.setToolTipText(Messages.getString("TrTab2.6"));
but2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
TreePath path = tree.getSelectionModel().getSelectionPath();
if (path != null && path.getLastPathComponent() instanceof TreeNodeSettings) {
TreeNodeSettings node = ((TreeNodeSettings) path.getLastPathComponent());
if (node.getPlayer() != null) {
DefaultTreeModel dtm = (DefaultTreeModel) tree.getModel(); // get the tree model
//now get the index of the selected node in the DefaultTreeModel
int index = dtm.getIndexOfChild(node.getParent(), node);
// if selected node is first, return (can't move it up)
if (index != 0) {
dtm.insertNodeInto(node, (DefaultMutableTreeNode) node.getParent(), index - 1); // move the node
dtm.reload();
for (int i = 0; i < tree.getRowCount(); i++) {
tree.expandRow(i);
}
tree.getSelectionModel().setSelectionPath(new TreePath(node.getPath()));
updateEngineModel();
}
}
}
}
});
builder.add(but2, cc.xy(3, 3));
JButton but3 = new JButton(LooksFrame.readImageIcon("connect_no-32.png"));
but3.setToolTipText(Messages.getString("TrTab2.0"));
but3.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
TreePath path = tree.getSelectionModel().getSelectionPath();
if (path != null && path.getLastPathComponent() instanceof TreeNodeSettings && ((TreeNodeSettings) path.getLastPathComponent()).getPlayer() != null) {
((TreeNodeSettings) path.getLastPathComponent()).setEnable(!((TreeNodeSettings) path.getLastPathComponent()).isEnable());
updateEngineModel();
tree.updateUI();
}
}
});
builder.add(but3, cc.xy(4, 3));
DefaultMutableTreeNode root = new DefaultMutableTreeNode(Messages.getString("TrTab2.11"));
TreeNodeSettings commonEnc = new TreeNodeSettings(Messages.getString("TrTab2.5"), null, buildCommon());
commonEnc.getConfigPanel().addComponentListener(new ComponentAdapter() {
@Override
public void componentShown(ComponentEvent e) {
handleCardComponentChange(e.getComponent());
}
});
tabbedPane.add(commonEnc.id(), commonEnc.getConfigPanel());
root.add(commonEnc);
parent = new DefaultMutableTreeNode[5];
parent[0] = new DefaultMutableTreeNode(Messages.getString("TrTab2.14"));
parent[1] = new DefaultMutableTreeNode(Messages.getString("TrTab2.15"));
parent[2] = new DefaultMutableTreeNode(Messages.getString("TrTab2.16"));
parent[3] = new DefaultMutableTreeNode(Messages.getString("TrTab2.17"));
parent[4] = new DefaultMutableTreeNode(Messages.getString("TrTab2.18"));
root.add(parent[0]);
root.add(parent[1]);
root.add(parent[2]);
root.add(parent[3]);
root.add(parent[4]);
tree = new JTree(new DefaultTreeModel(root)) {
private static final long serialVersionUID = -6703434752606636290L;
};
tree.setRootVisible(false);
tree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
tree.addTreeSelectionListener(new TreeSelectionListener() {
@Override
public void valueChanged(TreeSelectionEvent e) {
if (e.getNewLeadSelectionPath() != null && e.getNewLeadSelectionPath().getLastPathComponent() instanceof TreeNodeSettings) {
TreeNodeSettings tns = (TreeNodeSettings) e.getNewLeadSelectionPath().getLastPathComponent();
cl.show(tabbedPane, tns.id());
}
}
});
tree.setCellRenderer(new TreeRenderer());
JScrollPane pane = new JScrollPane(tree, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
builder.add(pane, cc.xyw(2, 1, 4));
builder.addLabel(Messages.getString("TrTab2.19"), cc.xyw(2, 5, 4));
builder.addLabel(Messages.getString("TrTab2.20"), cc.xyw(2, 7, 4));
return builder.getPanel();
}
public void addEngines() {
ArrayList<Player> disPlayers = new ArrayList<Player>();
ArrayList<Player> ordPlayers = new ArrayList<Player>();
PMS r = PMS.get();
for (String id : PMS.getConfiguration().getEnginesAsList(r.getRegistry())) {
//boolean matched = false;
for (Player p : PMS.get().getAllPlayers()) {
if (p.id().equals(id)) {
ordPlayers.add(p);
//matched = true;
}
}
}
for (Player p : PMS.get().getAllPlayers()) {
if (!ordPlayers.contains(p)) {
ordPlayers.add(p);
disPlayers.add(p);
}
}
for (Player p : ordPlayers) {
TreeNodeSettings en = new TreeNodeSettings(p.name(), p, null);
if (disPlayers.contains(p)) {
en.setEnable(false);
}
JComponent jc = en.getConfigPanel();
if (jc == null) {
jc = buildEmpty();
}
jc.addComponentListener(new ComponentAdapter() {
@Override
public void componentShown(ComponentEvent e) {
handleCardComponentChange(e.getComponent());
}
});
tabbedPane.add(en.id(), jc);
parent[p.purpose()].add(en);
}
for (int i = 0; i < tree.getRowCount(); i++) {
tree.expandRow(i);
}
tree.setSelectionRow(0);
}
public JComponent buildEmpty() {
FormLayout layout = new FormLayout(
"left:pref, 2dlu, pref:grow",
"p, 3dlu, p, 3dlu, p, 3dlu, p, 3dlu, p, 3dlu, p, 3dlu, p, 3dlu, p, 3dlu, p, 3dlu, p, 3dlu, p , 3dlu, p, 3dlu, p, 3dlu, p, 3dlu, p, 3dlu, p, 20dlu, p, 3dlu, p, 3dlu, p");
PanelBuilder builder = new PanelBuilder(layout);
builder.setBorder(Borders.EMPTY_BORDER);
builder.setOpaque(false);
CellConstraints cc = new CellConstraints();
builder.addSeparator(Messages.getString("TrTab2.1"), cc.xyw(1, 1, 3));
return builder.getPanel();
}
public JComponent buildCommon() {
FormLayout layout = new FormLayout(
"left:pref, 2dlu, pref:grow",
- "p, 2dlu, p, 2dlu, p, 2dlu, p, 2dlu, p, 2dlu, p, 9dlu, p, 2dlu, p, 2dlu, p, 2dlu, p, 2dlu, p,2dlu, p, 9dlu, p, 2dlu, p, 2dlu, p, 2dlu, p, 9dlu, p, 2dlu, p, 2dlu, p, 2dlu, p, 2dlu, p, 2dlu, p, 2dlu, p");
+ "p, 2dlu, p, 2dlu, p, 2dlu, p, 2dlu, p, 9dlu, p, 2dlu, p, 2dlu, p, 2dlu, p, 2dlu, p, 2dlu, p, 2dlu, p, 2dlu, p, 9dlu, p, 2dlu, p, 2dlu, p, 2dlu, p, 9dlu, p, 2dlu, p, 2dlu, p, 2dlu, p, 2dlu, p, 2dlu, p, 2dlu, p");
PanelBuilder builder = new PanelBuilder(layout);
builder.setBorder(Borders.EMPTY_BORDER);
builder.setOpaque(false);
CellConstraints cc = new CellConstraints();
maxbuffer = new JTextField("" + configuration.getMaxMemoryBufferSize());
maxbuffer.addKeyListener(new KeyListener() {
@Override
public void keyPressed(KeyEvent e) {
}
@Override
public void keyTyped(KeyEvent e) {
}
@Override
public void keyReleased(KeyEvent e) {
try {
int ab = Integer.parseInt(maxbuffer.getText());
configuration.setMaxMemoryBufferSize(ab);
} catch (NumberFormatException nfe) {
}
}
});
JComponent cmp = builder.addSeparator(Messages.getString("NetworkTab.5"), cc.xyw(1, 1, 3));
cmp = (JComponent) cmp.getComponent(0);
cmp.setFont(cmp.getFont().deriveFont(Font.BOLD));
builder.addLabel(Messages.getString("NetworkTab.6").replaceAll("MAX_BUFFER_SIZE", configuration.getMaxMemoryBufferSizeStr()), cc.xy(1, 3));
builder.add(maxbuffer, cc.xy(3, 3));
builder.addLabel(Messages.getString("NetworkTab.7") + Runtime.getRuntime().availableProcessors() + ")", cc.xy(1, 5));
String[] guiCores = new String[MAX_CORES];
for (int i = 0; i < MAX_CORES; i++) {
guiCores[i] = Integer.toString(i + 1);
}
nbcores = new JComboBox(guiCores);
nbcores.setEditable(false);
int nbConfCores = PMS.getConfiguration().getNumberOfCpuCores();
if (nbConfCores > 0 && nbConfCores <= MAX_CORES) {
nbcores.setSelectedItem(Integer.toString(nbConfCores));
} else {
nbcores.setSelectedIndex(0);
}
nbcores.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
PMS.getConfiguration().setNumberOfCpuCores(Integer.parseInt(e.getItem().toString()));
}
});
builder.add(nbcores, cc.xy(3, 5));
chapter_interval = new JTextField("" + configuration.getChapterInterval());
chapter_interval.setEnabled(configuration.isChapterSupport());
chapter_interval.addKeyListener(new KeyListener() {
@Override
public void keyPressed(KeyEvent e) {
}
@Override
public void keyTyped(KeyEvent e) {
}
@Override
public void keyReleased(KeyEvent e) {
try {
int ab = Integer.parseInt(chapter_interval.getText());
configuration.setChapterInterval(ab);
} catch (NumberFormatException nfe) {
}
}
});
chapter_support = new JCheckBox(Messages.getString("TrTab2.52"));
chapter_support.setContentAreaFilled(false);
chapter_support.setSelected(configuration.isChapterSupport());
chapter_support.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
configuration.setChapterSupport((e.getStateChange() == ItemEvent.SELECTED));
chapter_interval.setEnabled(configuration.isChapterSupport());
PMS.get().getFrame().setReloadable(true);
}
});
builder.add(chapter_support, cc.xy(1, 7));
builder.add(chapter_interval, cc.xy(3, 7));
cmp = builder.addSeparator(Messages.getString("TrTab2.3"), cc.xyw(1, 11, 3));
cmp = (JComponent) cmp.getComponent(0);
cmp.setFont(cmp.getFont().deriveFont(Font.BOLD));
channels = new JComboBox(new Object[]{"2 channels (Stereo)", "6 channels (5.1)" /*, "8 channels 7.1" */}); // 7.1 not supported by Mplayer :\
channels.setEditable(false);
if (PMS.getConfiguration().getAudioChannelCount() == 2) {
channels.setSelectedIndex(0);
} else {
channels.setSelectedIndex(1);
}
channels.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
PMS.getConfiguration().setAudioChannelCount(Integer.parseInt(e.getItem().toString().substring(0, 1)));
}
});
builder.addLabel(Messages.getString("TrTab2.50"), cc.xy(1, 13));
builder.add(channels, cc.xy(3, 13));
abitrate = new JTextField("" + PMS.getConfiguration().getAudioBitrate());
abitrate.addKeyListener(new KeyListener() {
@Override
public void keyPressed(KeyEvent e) {
}
@Override
public void keyTyped(KeyEvent e) {
}
@Override
public void keyReleased(KeyEvent e) {
try {
int ab = Integer.parseInt(abitrate.getText());
PMS.getConfiguration().setAudioBitrate(ab);
} catch (NumberFormatException nfe) {
}
}
});
builder.addLabel(Messages.getString("TrTab2.29"), cc.xy(1, 15));
builder.add(abitrate, cc.xy(3, 15));
hdaudiopass = new JCheckBox(Messages.getString("TrTab2.53") + (Platform.isWindows() ? Messages.getString("TrTab2.21") : ""));
hdaudiopass.setContentAreaFilled(false);
if (configuration.isHDAudioPassthrough()) {
hdaudiopass.setSelected(true);
}
hdaudiopass.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
configuration.setHDAudioPassthrough(hdaudiopass.isSelected());
if (configuration.isHDAudioPassthrough()) {
JOptionPane.showMessageDialog(
(JFrame) (SwingUtilities.getWindowAncestor((Component) PMS.get().getFrame())),
Messages.getString("TrTab2.10"),
"Information",
JOptionPane.INFORMATION_MESSAGE);
}
}
});
builder.add(hdaudiopass, cc.xyw(1, 19, 3));
forceDTSinPCM = new JCheckBox(Messages.getString("TrTab2.28") + (Platform.isWindows() ? Messages.getString("TrTab2.21") : ""));
forceDTSinPCM.setContentAreaFilled(false);
if (configuration.isDTSEmbedInPCM()) {
forceDTSinPCM.setSelected(true);
}
forceDTSinPCM.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
configuration.setDTSEmbedInPCM(forceDTSinPCM.isSelected());
if (configuration.isDTSEmbedInPCM()) {
JOptionPane.showMessageDialog(
(JFrame) (SwingUtilities.getWindowAncestor((Component) PMS.get().getFrame())),
Messages.getString("TrTab2.10"),
"Information",
JOptionPane.INFORMATION_MESSAGE);
}
}
});
builder.add(forceDTSinPCM, cc.xyw(1, 17, 3));
forcePCM = new JCheckBox(Messages.getString("TrTab2.27"));
forcePCM.setContentAreaFilled(false);
if (configuration.isMencoderUsePcm()) {
forcePCM.setSelected(true);
}
forcePCM.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
configuration.setMencoderUsePcm(e.getStateChange() == ItemEvent.SELECTED);
}
});
builder.add(forcePCM, cc.xyw(1, 21, 3));
ac3remux = new JCheckBox(Messages.getString("MEncoderVideo.32") + (Platform.isWindows() ? Messages.getString("TrTab2.21") : ""));
ac3remux.setContentAreaFilled(false);
if (PMS.getConfiguration().isRemuxAC3()) {
ac3remux.setSelected(true);
}
ac3remux.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
PMS.getConfiguration().setRemuxAC3((e.getStateChange() == ItemEvent.SELECTED));
}
});
builder.add(ac3remux, cc.xyw(1, 23, 3));
mpeg2remux = new JCheckBox(Messages.getString("MEncoderVideo.39") + (Platform.isWindows() ? Messages.getString("TrTab2.21") : ""));
mpeg2remux.setContentAreaFilled(false);
if (PMS.getConfiguration().isMencoderRemuxMPEG2()) {
mpeg2remux.setSelected(true);
}
mpeg2remux.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
PMS.getConfiguration().setMencoderRemuxMPEG2((e.getStateChange() == ItemEvent.SELECTED));
}
});
builder.add(mpeg2remux, cc.xyw(1, 25, 3));
cmp = builder.addSeparator(Messages.getString("TrTab2.4"), cc.xyw(1, 27, 3));
cmp = (JComponent) cmp.getComponent(0);
cmp.setFont(cmp.getFont().deriveFont(Font.BOLD));
builder.addLabel(Messages.getString("TrTab2.30"), cc.xy(1, 29));
maxbitrate = new JTextField("" + PMS.getConfiguration().getMaximumBitrate());
maxbitrate.addKeyListener(new KeyListener() {
@Override
public void keyPressed(KeyEvent e) {
}
@Override
public void keyTyped(KeyEvent e) {
}
@Override
public void keyReleased(KeyEvent e) {
PMS.getConfiguration().setMaximumBitrate(maxbitrate.getText());
}
});
builder.add(maxbitrate, cc.xy(3, 29));
builder.addLabel(Messages.getString("TrTab2.32"), cc.xyw(1, 31, 3));
Object data[] = new Object[]{PMS.getConfiguration().getMencoderMainSettings(),
"keyint=5:vqscale=1:vqmin=2 /* Great Quality */",
"keyint=5:vqscale=1:vqmin=1 /* Lossless Quality */",
"keyint=5:vqscale=2:vqmin=3 /* Good quality */",
"keyint=25:vqmax=5:vqmin=2 /* Good quality for HD Wifi Transcoding */",
"keyint=25:vqmax=7:vqmin=2 /* Medium quality for HD Wifi Transcoding */",
"keyint=25:vqmax=8:vqmin=3 /* Low quality, Low-end CPU or HD Wifi Transcoding */"};
MyComboBoxModel cbm = new MyComboBoxModel(data);
vq = new JComboBox(cbm);
vq.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
if (e.getStateChange() == ItemEvent.SELECTED) {
String s = (String) e.getItem();
if (s.indexOf("/*") > -1) {
s = s.substring(0, s.indexOf("/*")).trim();
}
PMS.getConfiguration().setMencoderMainSettings(s);
}
}
});
vq.getEditor().getEditorComponent().addKeyListener(new KeyListener() {
@Override
public void keyPressed(KeyEvent e) {
}
@Override
public void keyTyped(KeyEvent e) {
}
@Override
public void keyReleased(KeyEvent e) {
vq.getItemListeners()[0].itemStateChanged(new ItemEvent(vq, 0, vq.getEditor().getItem(), ItemEvent.SELECTED));
}
});
vq.setEditable(true);
builder.add(vq, cc.xyw(1, 33, 3));
String help1 = Messages.getString("TrTab2.39");
help1 += Messages.getString("TrTab2.40");
help1 += Messages.getString("TrTab2.41");
help1 += Messages.getString("TrTab2.42");
help1 += Messages.getString("TrTab2.43");
help1 += Messages.getString("TrTab2.44");
JTextArea decodeTips = new JTextArea(help1);
decodeTips.setEditable(false);
decodeTips.setBorder(BorderFactory.createEtchedBorder());
decodeTips.setBackground(new Color(255, 255, 192));
builder.add(decodeTips, cc.xyw(1, 43, 3));
disableSubs = new JCheckBox(Messages.getString("TrTab2.51"));
disableSubs.setContentAreaFilled(false);
cmp = builder.addSeparator(Messages.getString("TrTab2.7"), cc.xyw(1, 35, 3));
cmp = (JComponent) cmp.getComponent(0);
cmp.setFont(cmp.getFont().deriveFont(Font.BOLD));
builder.add(disableSubs, cc.xy(1, 37));
builder.addLabel(Messages.getString("TrTab2.8"), cc.xy(1, 39));
notranscode = new JTextField(configuration.getNoTranscode());
notranscode.addKeyListener(new KeyListener() {
@Override
public void keyPressed(KeyEvent e) {
}
@Override
public void keyTyped(KeyEvent e) {
}
@Override
public void keyReleased(KeyEvent e) {
configuration.setNoTranscode(notranscode.getText());
PMS.get().getFrame().setReloadable(true);
}
});
builder.add(notranscode, cc.xy(3, 39));
builder.addLabel(Messages.getString("TrTab2.9"), cc.xy(1, 41));
forcetranscode = new JTextField(configuration.getForceTranscode());
forcetranscode.addKeyListener(new KeyListener() {
@Override
public void keyPressed(KeyEvent e) {
}
@Override
public void keyTyped(KeyEvent e) {
}
@Override
public void keyReleased(KeyEvent e) {
configuration.setForceTranscode(forcetranscode.getText());
PMS.get().getFrame().setReloadable(true);
}
});
builder.add(forcetranscode, cc.xy(3, 41));
return builder.getPanel();
}
}
| true | true | public JComponent buildCommon() {
FormLayout layout = new FormLayout(
"left:pref, 2dlu, pref:grow",
"p, 2dlu, p, 2dlu, p, 2dlu, p, 2dlu, p, 2dlu, p, 9dlu, p, 2dlu, p, 2dlu, p, 2dlu, p, 2dlu, p,2dlu, p, 9dlu, p, 2dlu, p, 2dlu, p, 2dlu, p, 9dlu, p, 2dlu, p, 2dlu, p, 2dlu, p, 2dlu, p, 2dlu, p, 2dlu, p");
PanelBuilder builder = new PanelBuilder(layout);
builder.setBorder(Borders.EMPTY_BORDER);
builder.setOpaque(false);
CellConstraints cc = new CellConstraints();
maxbuffer = new JTextField("" + configuration.getMaxMemoryBufferSize());
maxbuffer.addKeyListener(new KeyListener() {
@Override
public void keyPressed(KeyEvent e) {
}
@Override
public void keyTyped(KeyEvent e) {
}
@Override
public void keyReleased(KeyEvent e) {
try {
int ab = Integer.parseInt(maxbuffer.getText());
configuration.setMaxMemoryBufferSize(ab);
} catch (NumberFormatException nfe) {
}
}
});
JComponent cmp = builder.addSeparator(Messages.getString("NetworkTab.5"), cc.xyw(1, 1, 3));
cmp = (JComponent) cmp.getComponent(0);
cmp.setFont(cmp.getFont().deriveFont(Font.BOLD));
builder.addLabel(Messages.getString("NetworkTab.6").replaceAll("MAX_BUFFER_SIZE", configuration.getMaxMemoryBufferSizeStr()), cc.xy(1, 3));
builder.add(maxbuffer, cc.xy(3, 3));
builder.addLabel(Messages.getString("NetworkTab.7") + Runtime.getRuntime().availableProcessors() + ")", cc.xy(1, 5));
String[] guiCores = new String[MAX_CORES];
for (int i = 0; i < MAX_CORES; i++) {
guiCores[i] = Integer.toString(i + 1);
}
nbcores = new JComboBox(guiCores);
nbcores.setEditable(false);
int nbConfCores = PMS.getConfiguration().getNumberOfCpuCores();
if (nbConfCores > 0 && nbConfCores <= MAX_CORES) {
nbcores.setSelectedItem(Integer.toString(nbConfCores));
} else {
nbcores.setSelectedIndex(0);
}
nbcores.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
PMS.getConfiguration().setNumberOfCpuCores(Integer.parseInt(e.getItem().toString()));
}
});
builder.add(nbcores, cc.xy(3, 5));
chapter_interval = new JTextField("" + configuration.getChapterInterval());
chapter_interval.setEnabled(configuration.isChapterSupport());
chapter_interval.addKeyListener(new KeyListener() {
@Override
public void keyPressed(KeyEvent e) {
}
@Override
public void keyTyped(KeyEvent e) {
}
@Override
public void keyReleased(KeyEvent e) {
try {
int ab = Integer.parseInt(chapter_interval.getText());
configuration.setChapterInterval(ab);
} catch (NumberFormatException nfe) {
}
}
});
chapter_support = new JCheckBox(Messages.getString("TrTab2.52"));
chapter_support.setContentAreaFilled(false);
chapter_support.setSelected(configuration.isChapterSupport());
chapter_support.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
configuration.setChapterSupport((e.getStateChange() == ItemEvent.SELECTED));
chapter_interval.setEnabled(configuration.isChapterSupport());
PMS.get().getFrame().setReloadable(true);
}
});
builder.add(chapter_support, cc.xy(1, 7));
builder.add(chapter_interval, cc.xy(3, 7));
cmp = builder.addSeparator(Messages.getString("TrTab2.3"), cc.xyw(1, 11, 3));
cmp = (JComponent) cmp.getComponent(0);
cmp.setFont(cmp.getFont().deriveFont(Font.BOLD));
channels = new JComboBox(new Object[]{"2 channels (Stereo)", "6 channels (5.1)" /*, "8 channels 7.1" */}); // 7.1 not supported by Mplayer :\
channels.setEditable(false);
if (PMS.getConfiguration().getAudioChannelCount() == 2) {
channels.setSelectedIndex(0);
} else {
channels.setSelectedIndex(1);
}
channels.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
PMS.getConfiguration().setAudioChannelCount(Integer.parseInt(e.getItem().toString().substring(0, 1)));
}
});
builder.addLabel(Messages.getString("TrTab2.50"), cc.xy(1, 13));
builder.add(channels, cc.xy(3, 13));
abitrate = new JTextField("" + PMS.getConfiguration().getAudioBitrate());
abitrate.addKeyListener(new KeyListener() {
@Override
public void keyPressed(KeyEvent e) {
}
@Override
public void keyTyped(KeyEvent e) {
}
@Override
public void keyReleased(KeyEvent e) {
try {
int ab = Integer.parseInt(abitrate.getText());
PMS.getConfiguration().setAudioBitrate(ab);
} catch (NumberFormatException nfe) {
}
}
});
builder.addLabel(Messages.getString("TrTab2.29"), cc.xy(1, 15));
builder.add(abitrate, cc.xy(3, 15));
hdaudiopass = new JCheckBox(Messages.getString("TrTab2.53") + (Platform.isWindows() ? Messages.getString("TrTab2.21") : ""));
hdaudiopass.setContentAreaFilled(false);
if (configuration.isHDAudioPassthrough()) {
hdaudiopass.setSelected(true);
}
hdaudiopass.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
configuration.setHDAudioPassthrough(hdaudiopass.isSelected());
if (configuration.isHDAudioPassthrough()) {
JOptionPane.showMessageDialog(
(JFrame) (SwingUtilities.getWindowAncestor((Component) PMS.get().getFrame())),
Messages.getString("TrTab2.10"),
"Information",
JOptionPane.INFORMATION_MESSAGE);
}
}
});
builder.add(hdaudiopass, cc.xyw(1, 19, 3));
forceDTSinPCM = new JCheckBox(Messages.getString("TrTab2.28") + (Platform.isWindows() ? Messages.getString("TrTab2.21") : ""));
forceDTSinPCM.setContentAreaFilled(false);
if (configuration.isDTSEmbedInPCM()) {
forceDTSinPCM.setSelected(true);
}
forceDTSinPCM.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
configuration.setDTSEmbedInPCM(forceDTSinPCM.isSelected());
if (configuration.isDTSEmbedInPCM()) {
JOptionPane.showMessageDialog(
(JFrame) (SwingUtilities.getWindowAncestor((Component) PMS.get().getFrame())),
Messages.getString("TrTab2.10"),
"Information",
JOptionPane.INFORMATION_MESSAGE);
}
}
});
builder.add(forceDTSinPCM, cc.xyw(1, 17, 3));
forcePCM = new JCheckBox(Messages.getString("TrTab2.27"));
forcePCM.setContentAreaFilled(false);
if (configuration.isMencoderUsePcm()) {
forcePCM.setSelected(true);
}
forcePCM.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
configuration.setMencoderUsePcm(e.getStateChange() == ItemEvent.SELECTED);
}
});
builder.add(forcePCM, cc.xyw(1, 21, 3));
ac3remux = new JCheckBox(Messages.getString("MEncoderVideo.32") + (Platform.isWindows() ? Messages.getString("TrTab2.21") : ""));
ac3remux.setContentAreaFilled(false);
if (PMS.getConfiguration().isRemuxAC3()) {
ac3remux.setSelected(true);
}
ac3remux.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
PMS.getConfiguration().setRemuxAC3((e.getStateChange() == ItemEvent.SELECTED));
}
});
builder.add(ac3remux, cc.xyw(1, 23, 3));
mpeg2remux = new JCheckBox(Messages.getString("MEncoderVideo.39") + (Platform.isWindows() ? Messages.getString("TrTab2.21") : ""));
mpeg2remux.setContentAreaFilled(false);
if (PMS.getConfiguration().isMencoderRemuxMPEG2()) {
mpeg2remux.setSelected(true);
}
mpeg2remux.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
PMS.getConfiguration().setMencoderRemuxMPEG2((e.getStateChange() == ItemEvent.SELECTED));
}
});
builder.add(mpeg2remux, cc.xyw(1, 25, 3));
cmp = builder.addSeparator(Messages.getString("TrTab2.4"), cc.xyw(1, 27, 3));
cmp = (JComponent) cmp.getComponent(0);
cmp.setFont(cmp.getFont().deriveFont(Font.BOLD));
builder.addLabel(Messages.getString("TrTab2.30"), cc.xy(1, 29));
maxbitrate = new JTextField("" + PMS.getConfiguration().getMaximumBitrate());
maxbitrate.addKeyListener(new KeyListener() {
@Override
public void keyPressed(KeyEvent e) {
}
@Override
public void keyTyped(KeyEvent e) {
}
@Override
public void keyReleased(KeyEvent e) {
PMS.getConfiguration().setMaximumBitrate(maxbitrate.getText());
}
});
builder.add(maxbitrate, cc.xy(3, 29));
builder.addLabel(Messages.getString("TrTab2.32"), cc.xyw(1, 31, 3));
Object data[] = new Object[]{PMS.getConfiguration().getMencoderMainSettings(),
"keyint=5:vqscale=1:vqmin=2 /* Great Quality */",
"keyint=5:vqscale=1:vqmin=1 /* Lossless Quality */",
"keyint=5:vqscale=2:vqmin=3 /* Good quality */",
"keyint=25:vqmax=5:vqmin=2 /* Good quality for HD Wifi Transcoding */",
"keyint=25:vqmax=7:vqmin=2 /* Medium quality for HD Wifi Transcoding */",
"keyint=25:vqmax=8:vqmin=3 /* Low quality, Low-end CPU or HD Wifi Transcoding */"};
MyComboBoxModel cbm = new MyComboBoxModel(data);
vq = new JComboBox(cbm);
vq.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
if (e.getStateChange() == ItemEvent.SELECTED) {
String s = (String) e.getItem();
if (s.indexOf("/*") > -1) {
s = s.substring(0, s.indexOf("/*")).trim();
}
PMS.getConfiguration().setMencoderMainSettings(s);
}
}
});
vq.getEditor().getEditorComponent().addKeyListener(new KeyListener() {
@Override
public void keyPressed(KeyEvent e) {
}
@Override
public void keyTyped(KeyEvent e) {
}
@Override
public void keyReleased(KeyEvent e) {
vq.getItemListeners()[0].itemStateChanged(new ItemEvent(vq, 0, vq.getEditor().getItem(), ItemEvent.SELECTED));
}
});
vq.setEditable(true);
builder.add(vq, cc.xyw(1, 33, 3));
String help1 = Messages.getString("TrTab2.39");
help1 += Messages.getString("TrTab2.40");
help1 += Messages.getString("TrTab2.41");
help1 += Messages.getString("TrTab2.42");
help1 += Messages.getString("TrTab2.43");
help1 += Messages.getString("TrTab2.44");
JTextArea decodeTips = new JTextArea(help1);
decodeTips.setEditable(false);
decodeTips.setBorder(BorderFactory.createEtchedBorder());
decodeTips.setBackground(new Color(255, 255, 192));
builder.add(decodeTips, cc.xyw(1, 43, 3));
disableSubs = new JCheckBox(Messages.getString("TrTab2.51"));
disableSubs.setContentAreaFilled(false);
cmp = builder.addSeparator(Messages.getString("TrTab2.7"), cc.xyw(1, 35, 3));
cmp = (JComponent) cmp.getComponent(0);
cmp.setFont(cmp.getFont().deriveFont(Font.BOLD));
builder.add(disableSubs, cc.xy(1, 37));
builder.addLabel(Messages.getString("TrTab2.8"), cc.xy(1, 39));
notranscode = new JTextField(configuration.getNoTranscode());
notranscode.addKeyListener(new KeyListener() {
@Override
public void keyPressed(KeyEvent e) {
}
@Override
public void keyTyped(KeyEvent e) {
}
@Override
public void keyReleased(KeyEvent e) {
configuration.setNoTranscode(notranscode.getText());
PMS.get().getFrame().setReloadable(true);
}
});
builder.add(notranscode, cc.xy(3, 39));
builder.addLabel(Messages.getString("TrTab2.9"), cc.xy(1, 41));
forcetranscode = new JTextField(configuration.getForceTranscode());
forcetranscode.addKeyListener(new KeyListener() {
@Override
public void keyPressed(KeyEvent e) {
}
@Override
public void keyTyped(KeyEvent e) {
}
@Override
public void keyReleased(KeyEvent e) {
configuration.setForceTranscode(forcetranscode.getText());
PMS.get().getFrame().setReloadable(true);
}
});
builder.add(forcetranscode, cc.xy(3, 41));
return builder.getPanel();
}
| public JComponent buildCommon() {
FormLayout layout = new FormLayout(
"left:pref, 2dlu, pref:grow",
"p, 2dlu, p, 2dlu, p, 2dlu, p, 2dlu, p, 9dlu, p, 2dlu, p, 2dlu, p, 2dlu, p, 2dlu, p, 2dlu, p, 2dlu, p, 2dlu, p, 9dlu, p, 2dlu, p, 2dlu, p, 2dlu, p, 9dlu, p, 2dlu, p, 2dlu, p, 2dlu, p, 2dlu, p, 2dlu, p, 2dlu, p");
PanelBuilder builder = new PanelBuilder(layout);
builder.setBorder(Borders.EMPTY_BORDER);
builder.setOpaque(false);
CellConstraints cc = new CellConstraints();
maxbuffer = new JTextField("" + configuration.getMaxMemoryBufferSize());
maxbuffer.addKeyListener(new KeyListener() {
@Override
public void keyPressed(KeyEvent e) {
}
@Override
public void keyTyped(KeyEvent e) {
}
@Override
public void keyReleased(KeyEvent e) {
try {
int ab = Integer.parseInt(maxbuffer.getText());
configuration.setMaxMemoryBufferSize(ab);
} catch (NumberFormatException nfe) {
}
}
});
JComponent cmp = builder.addSeparator(Messages.getString("NetworkTab.5"), cc.xyw(1, 1, 3));
cmp = (JComponent) cmp.getComponent(0);
cmp.setFont(cmp.getFont().deriveFont(Font.BOLD));
builder.addLabel(Messages.getString("NetworkTab.6").replaceAll("MAX_BUFFER_SIZE", configuration.getMaxMemoryBufferSizeStr()), cc.xy(1, 3));
builder.add(maxbuffer, cc.xy(3, 3));
builder.addLabel(Messages.getString("NetworkTab.7") + Runtime.getRuntime().availableProcessors() + ")", cc.xy(1, 5));
String[] guiCores = new String[MAX_CORES];
for (int i = 0; i < MAX_CORES; i++) {
guiCores[i] = Integer.toString(i + 1);
}
nbcores = new JComboBox(guiCores);
nbcores.setEditable(false);
int nbConfCores = PMS.getConfiguration().getNumberOfCpuCores();
if (nbConfCores > 0 && nbConfCores <= MAX_CORES) {
nbcores.setSelectedItem(Integer.toString(nbConfCores));
} else {
nbcores.setSelectedIndex(0);
}
nbcores.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
PMS.getConfiguration().setNumberOfCpuCores(Integer.parseInt(e.getItem().toString()));
}
});
builder.add(nbcores, cc.xy(3, 5));
chapter_interval = new JTextField("" + configuration.getChapterInterval());
chapter_interval.setEnabled(configuration.isChapterSupport());
chapter_interval.addKeyListener(new KeyListener() {
@Override
public void keyPressed(KeyEvent e) {
}
@Override
public void keyTyped(KeyEvent e) {
}
@Override
public void keyReleased(KeyEvent e) {
try {
int ab = Integer.parseInt(chapter_interval.getText());
configuration.setChapterInterval(ab);
} catch (NumberFormatException nfe) {
}
}
});
chapter_support = new JCheckBox(Messages.getString("TrTab2.52"));
chapter_support.setContentAreaFilled(false);
chapter_support.setSelected(configuration.isChapterSupport());
chapter_support.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
configuration.setChapterSupport((e.getStateChange() == ItemEvent.SELECTED));
chapter_interval.setEnabled(configuration.isChapterSupport());
PMS.get().getFrame().setReloadable(true);
}
});
builder.add(chapter_support, cc.xy(1, 7));
builder.add(chapter_interval, cc.xy(3, 7));
cmp = builder.addSeparator(Messages.getString("TrTab2.3"), cc.xyw(1, 11, 3));
cmp = (JComponent) cmp.getComponent(0);
cmp.setFont(cmp.getFont().deriveFont(Font.BOLD));
channels = new JComboBox(new Object[]{"2 channels (Stereo)", "6 channels (5.1)" /*, "8 channels 7.1" */}); // 7.1 not supported by Mplayer :\
channels.setEditable(false);
if (PMS.getConfiguration().getAudioChannelCount() == 2) {
channels.setSelectedIndex(0);
} else {
channels.setSelectedIndex(1);
}
channels.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
PMS.getConfiguration().setAudioChannelCount(Integer.parseInt(e.getItem().toString().substring(0, 1)));
}
});
builder.addLabel(Messages.getString("TrTab2.50"), cc.xy(1, 13));
builder.add(channels, cc.xy(3, 13));
abitrate = new JTextField("" + PMS.getConfiguration().getAudioBitrate());
abitrate.addKeyListener(new KeyListener() {
@Override
public void keyPressed(KeyEvent e) {
}
@Override
public void keyTyped(KeyEvent e) {
}
@Override
public void keyReleased(KeyEvent e) {
try {
int ab = Integer.parseInt(abitrate.getText());
PMS.getConfiguration().setAudioBitrate(ab);
} catch (NumberFormatException nfe) {
}
}
});
builder.addLabel(Messages.getString("TrTab2.29"), cc.xy(1, 15));
builder.add(abitrate, cc.xy(3, 15));
hdaudiopass = new JCheckBox(Messages.getString("TrTab2.53") + (Platform.isWindows() ? Messages.getString("TrTab2.21") : ""));
hdaudiopass.setContentAreaFilled(false);
if (configuration.isHDAudioPassthrough()) {
hdaudiopass.setSelected(true);
}
hdaudiopass.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
configuration.setHDAudioPassthrough(hdaudiopass.isSelected());
if (configuration.isHDAudioPassthrough()) {
JOptionPane.showMessageDialog(
(JFrame) (SwingUtilities.getWindowAncestor((Component) PMS.get().getFrame())),
Messages.getString("TrTab2.10"),
"Information",
JOptionPane.INFORMATION_MESSAGE);
}
}
});
builder.add(hdaudiopass, cc.xyw(1, 19, 3));
forceDTSinPCM = new JCheckBox(Messages.getString("TrTab2.28") + (Platform.isWindows() ? Messages.getString("TrTab2.21") : ""));
forceDTSinPCM.setContentAreaFilled(false);
if (configuration.isDTSEmbedInPCM()) {
forceDTSinPCM.setSelected(true);
}
forceDTSinPCM.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
configuration.setDTSEmbedInPCM(forceDTSinPCM.isSelected());
if (configuration.isDTSEmbedInPCM()) {
JOptionPane.showMessageDialog(
(JFrame) (SwingUtilities.getWindowAncestor((Component) PMS.get().getFrame())),
Messages.getString("TrTab2.10"),
"Information",
JOptionPane.INFORMATION_MESSAGE);
}
}
});
builder.add(forceDTSinPCM, cc.xyw(1, 17, 3));
forcePCM = new JCheckBox(Messages.getString("TrTab2.27"));
forcePCM.setContentAreaFilled(false);
if (configuration.isMencoderUsePcm()) {
forcePCM.setSelected(true);
}
forcePCM.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
configuration.setMencoderUsePcm(e.getStateChange() == ItemEvent.SELECTED);
}
});
builder.add(forcePCM, cc.xyw(1, 21, 3));
ac3remux = new JCheckBox(Messages.getString("MEncoderVideo.32") + (Platform.isWindows() ? Messages.getString("TrTab2.21") : ""));
ac3remux.setContentAreaFilled(false);
if (PMS.getConfiguration().isRemuxAC3()) {
ac3remux.setSelected(true);
}
ac3remux.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
PMS.getConfiguration().setRemuxAC3((e.getStateChange() == ItemEvent.SELECTED));
}
});
builder.add(ac3remux, cc.xyw(1, 23, 3));
mpeg2remux = new JCheckBox(Messages.getString("MEncoderVideo.39") + (Platform.isWindows() ? Messages.getString("TrTab2.21") : ""));
mpeg2remux.setContentAreaFilled(false);
if (PMS.getConfiguration().isMencoderRemuxMPEG2()) {
mpeg2remux.setSelected(true);
}
mpeg2remux.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
PMS.getConfiguration().setMencoderRemuxMPEG2((e.getStateChange() == ItemEvent.SELECTED));
}
});
builder.add(mpeg2remux, cc.xyw(1, 25, 3));
cmp = builder.addSeparator(Messages.getString("TrTab2.4"), cc.xyw(1, 27, 3));
cmp = (JComponent) cmp.getComponent(0);
cmp.setFont(cmp.getFont().deriveFont(Font.BOLD));
builder.addLabel(Messages.getString("TrTab2.30"), cc.xy(1, 29));
maxbitrate = new JTextField("" + PMS.getConfiguration().getMaximumBitrate());
maxbitrate.addKeyListener(new KeyListener() {
@Override
public void keyPressed(KeyEvent e) {
}
@Override
public void keyTyped(KeyEvent e) {
}
@Override
public void keyReleased(KeyEvent e) {
PMS.getConfiguration().setMaximumBitrate(maxbitrate.getText());
}
});
builder.add(maxbitrate, cc.xy(3, 29));
builder.addLabel(Messages.getString("TrTab2.32"), cc.xyw(1, 31, 3));
Object data[] = new Object[]{PMS.getConfiguration().getMencoderMainSettings(),
"keyint=5:vqscale=1:vqmin=2 /* Great Quality */",
"keyint=5:vqscale=1:vqmin=1 /* Lossless Quality */",
"keyint=5:vqscale=2:vqmin=3 /* Good quality */",
"keyint=25:vqmax=5:vqmin=2 /* Good quality for HD Wifi Transcoding */",
"keyint=25:vqmax=7:vqmin=2 /* Medium quality for HD Wifi Transcoding */",
"keyint=25:vqmax=8:vqmin=3 /* Low quality, Low-end CPU or HD Wifi Transcoding */"};
MyComboBoxModel cbm = new MyComboBoxModel(data);
vq = new JComboBox(cbm);
vq.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
if (e.getStateChange() == ItemEvent.SELECTED) {
String s = (String) e.getItem();
if (s.indexOf("/*") > -1) {
s = s.substring(0, s.indexOf("/*")).trim();
}
PMS.getConfiguration().setMencoderMainSettings(s);
}
}
});
vq.getEditor().getEditorComponent().addKeyListener(new KeyListener() {
@Override
public void keyPressed(KeyEvent e) {
}
@Override
public void keyTyped(KeyEvent e) {
}
@Override
public void keyReleased(KeyEvent e) {
vq.getItemListeners()[0].itemStateChanged(new ItemEvent(vq, 0, vq.getEditor().getItem(), ItemEvent.SELECTED));
}
});
vq.setEditable(true);
builder.add(vq, cc.xyw(1, 33, 3));
String help1 = Messages.getString("TrTab2.39");
help1 += Messages.getString("TrTab2.40");
help1 += Messages.getString("TrTab2.41");
help1 += Messages.getString("TrTab2.42");
help1 += Messages.getString("TrTab2.43");
help1 += Messages.getString("TrTab2.44");
JTextArea decodeTips = new JTextArea(help1);
decodeTips.setEditable(false);
decodeTips.setBorder(BorderFactory.createEtchedBorder());
decodeTips.setBackground(new Color(255, 255, 192));
builder.add(decodeTips, cc.xyw(1, 43, 3));
disableSubs = new JCheckBox(Messages.getString("TrTab2.51"));
disableSubs.setContentAreaFilled(false);
cmp = builder.addSeparator(Messages.getString("TrTab2.7"), cc.xyw(1, 35, 3));
cmp = (JComponent) cmp.getComponent(0);
cmp.setFont(cmp.getFont().deriveFont(Font.BOLD));
builder.add(disableSubs, cc.xy(1, 37));
builder.addLabel(Messages.getString("TrTab2.8"), cc.xy(1, 39));
notranscode = new JTextField(configuration.getNoTranscode());
notranscode.addKeyListener(new KeyListener() {
@Override
public void keyPressed(KeyEvent e) {
}
@Override
public void keyTyped(KeyEvent e) {
}
@Override
public void keyReleased(KeyEvent e) {
configuration.setNoTranscode(notranscode.getText());
PMS.get().getFrame().setReloadable(true);
}
});
builder.add(notranscode, cc.xy(3, 39));
builder.addLabel(Messages.getString("TrTab2.9"), cc.xy(1, 41));
forcetranscode = new JTextField(configuration.getForceTranscode());
forcetranscode.addKeyListener(new KeyListener() {
@Override
public void keyPressed(KeyEvent e) {
}
@Override
public void keyTyped(KeyEvent e) {
}
@Override
public void keyReleased(KeyEvent e) {
configuration.setForceTranscode(forcetranscode.getText());
PMS.get().getFrame().setReloadable(true);
}
});
builder.add(forcetranscode, cc.xy(3, 41));
return builder.getPanel();
}
|
diff --git a/52n-wps-webapp/src/test/java/org/n52/wps/test/WPS4RTester.java b/52n-wps-webapp/src/test/java/org/n52/wps/test/WPS4RTester.java
index 121def48..b9716cc0 100644
--- a/52n-wps-webapp/src/test/java/org/n52/wps/test/WPS4RTester.java
+++ b/52n-wps-webapp/src/test/java/org/n52/wps/test/WPS4RTester.java
@@ -1,306 +1,306 @@
package org.n52.wps.test;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.not;
import static org.hamcrest.Matchers.nullValue;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Random;
import javax.xml.parsers.ParserConfigurationException;
import org.apache.xmlbeans.XmlException;
import org.apache.xmlbeans.XmlObject;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import org.rosuda.REngine.Rserve.RConnection;
import org.rosuda.REngine.Rserve.RserveException;
import org.xml.sax.SAXException;
public class WPS4RTester {
private static String wpsUrl;
@BeforeClass
public static void beforeClass() {
wpsUrl = AllTestsIT.getURL();
// Seems not to work but it would be nice if it does...
// URL resource = WPS4RTester.class
// .getResource("/R/wps_config.xml");
// WPSConfig.forceInitialization(new File(resource.getFile()).getAbsolutePath());
String host = System.getProperty("test.rserve.host", "127.0.0.1");
int port = Integer.parseInt(System.getProperty("test.rserve.port", "6311"));
String user = System.getProperty("test.rserve.user", null);
String password = System.getProperty("test.rserve.pwd", null);
try {
RConnection c = getNewConnection(host, port, user, password);
c.close();
}
catch (RserveException e1) {
e1.printStackTrace();
throw new AssertionError("Cannot connect to Rserve. Skip the tests.");
}
}
@AfterClass
public static void afterClass() {
// WPSConfig.forceInitialization("src/main/webapp/config/wps_config.xml");
}
private static RConnection getNewConnection(String host, int port, String user, String password) throws RserveException {
RConnection con = new RConnection(host, port);
if (con != null && con.needLogin())
con.login(user, password);
return con;
}
@Test
public void sessionInfoRetrievedFromWPSWebsite() throws MalformedURLException {
String temp = wpsUrl.substring(0, wpsUrl.lastIndexOf("/"));
URL urlSessionInfo = new URL(temp + "/R/sessioninfo.jsp");
try {
String response = GetClient.sendRequest(urlSessionInfo.toExternalForm());
assertThat(response, containsString("R version "));
}
catch (IOException e) {
String message = "Cannot retrieve the R session info from WPS.";
e.printStackTrace();
throw new AssertionError(message);
}
}
@Test
public void resourcesAreLoadedAndRead() throws IOException,
ParserConfigurationException,
SAXException,
XmlException {
URL resource = WPS4RTester.class.getResource("/R/ExecuteTestResources.xml");
XmlObject xmlPayload = XmlObject.Factory.parse(resource);
String payload = xmlPayload.toString();
String response = PostClient.sendRequest(wpsUrl, payload);
assertThat(AllTestsIT.parseXML(response), is(not(nullValue())));
assertThat(response, not(containsString("ExceptionReport")));
assertThat(response, containsString("This is a dummy txt-file"));
assertThat(response, containsString("480"));
}
@Test
public void responseContainsVersionSection() throws IOException,
ParserConfigurationException,
SAXException,
XmlException {
URL resource = WPS4RTester.class.getResource("/R/ExecuteTestResources.xml");
XmlObject xmlPayload = XmlObject.Factory.parse(resource);
String payload = xmlPayload.toString();
String response = PostClient.sendRequest(wpsUrl, payload);
assertThat(AllTestsIT.parseXML(response), is(not(nullValue())));
assertThat(response, not(containsString("ExceptionReport")));
assertThat(response, containsString("R version "));
}
@Test
public void responseContainsWarningsSection() throws IOException,
ParserConfigurationException,
SAXException,
XmlException {
URL resource = WPS4RTester.class.getResource("/R/ExecuteTestResources.xml");
XmlObject xmlPayload = XmlObject.Factory.parse(resource);
String payload = xmlPayload.toString();
String response = PostClient.sendRequest(wpsUrl, payload);
assertThat(AllTestsIT.parseXML(response), is(not(nullValue())));
assertThat(response, containsString("warnings"));
}
@Test
public void responseContainsWarningsContent() throws IOException,
ParserConfigurationException,
SAXException,
XmlException {
// FIXME This test fails
URL resource = WPS4RTester.class.getResource("/R/ExecuteTestResources.xml");
XmlObject xmlPayload = XmlObject.Factory.parse(resource);
String payload = xmlPayload.toString();
String response = PostClient.sendRequest(wpsUrl, payload);
assertThat(AllTestsIT.parseXML(response), is(not(nullValue())));
assertThat(response, containsString("Test warning 4: This is a warning with some text."));
}
@Test
public void decribeProcess() throws IOException, ParserConfigurationException, SAXException {
String identifier = "org.n52.wps.server.r.test_resources";
String response = GetClient.sendRequest(wpsUrl, "Service=WPS&Request=DescribeProcess&Version=1.0.0&Identifier="
+ identifier);
assertThat(AllTestsIT.parseXML(response), is(not(nullValue())));
assertThat(response, not(containsString("ExceptionReport")));
assertThat(response, containsString(identifier));
}
@Test
public void capabilitiesContainProcess() throws IOException, ParserConfigurationException, SAXException {
String response = GetClient.sendRequest(wpsUrl, "Service=WPS&Request=GetCapabilities");
assertThat(AllTestsIT.parseXML(response), is(not(nullValue())));
assertThat(response, not(containsString("ExceptionReport")));
assertThat(response, containsString("org.n52.wps.server.r.test_resources"));
}
@Test
public void responseTypeIsImage() throws IOException, XmlException {
URL resource = WPS4RTester.class.getResource("/R/ExecuteTestImage.xml");
XmlObject xmlPayload = XmlObject.Factory.parse(resource);
String payload = xmlPayload.toString();
String response = PostClient.sendRequest(wpsUrl, payload);
assertThat(response.split("\n", 1)[0], containsString("PNG"));
assertThat(response, response, not(containsString("ExceptionReport")));
}
@Test
public void uniformIsExecuted() throws IOException, XmlException {
URL resource = WPS4RTester.class.getResource("/R/ExecuteTestUniform.xml");
XmlObject xmlPayload = XmlObject.Factory.parse(resource);
String payload = xmlPayload.toString();
String response = PostClient.sendRequest(wpsUrl, payload);
assertThat(response, response, containsString("Process successful"));
// output-specific:
assertThat(response, containsString("\"x\""));
assertThat(response, containsString("\"1\""));
assertThat(response, containsString("\"2\""));
assertThat(response, containsString("\"3\""));
assertThat(response, not(containsString("ExceptionReport")));
}
@Test
public void calculatorWorksCorrectly() throws IOException, ParserConfigurationException, SAXException, XmlException {
URL resource = WPS4RTester.class.getResource("/R/ExecuteTestCalculator.xml");
XmlObject xmlPayload = XmlObject.Factory.parse(resource);
String payload = xmlPayload.toString();
Random rand = new Random();
int a = rand.nextInt(100);
- payload.replace("@@@a@@@", Integer.toString(a));
+ payload = payload.replace("@@@a@@@", Integer.toString(a));
int b = rand.nextInt(100);
- payload.replace("@@@a@@@", Integer.toString(b));
+ payload = payload.replace("@@@b@@@", Integer.toString(b));
int op = rand.nextInt(3);
String[] ops = new String[] {"+", "-", "*"};
String opString = ops[op];
- payload.replace("@@@a@@@", opString);
+ payload = payload.replace("@@@op@@@", opString);
int result = Integer.MIN_VALUE;
if (opString.equals("+"))
result = a + b;
else if (opString.equals("-"))
result = a - b;
else if (opString.equals("*"))
result = a * b;
String response = PostClient.sendRequest(wpsUrl, payload);
assertThat(AllTestsIT.parseXML(response), is(not(nullValue())));
assertThat(response, containsString(Integer.toString(result)));
}
// TODO add unit test for wps.off and wps.on annotations using a test script that contains various on/off
// statements.
// /*Complex XML Input by reference */
// @Test
// public void testExecutePOSTreferenceComplexXMLSynchronousXMLOutput()
// throws IOException, ParserConfigurationException, SAXException {
// System.out.println("\nRunning testExecutePOSTreferenceComplexXMLSynchronousXMLOutput");
// String payload =
// "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>"
// +
// "<wps:Execute service=\"WPS\" version=\"1.0.0\" xmlns:wps=\"http://www.opengis.net/wps/1.0.0\" xmlns:ows=\"http://www.opengis.net/ows/1.1\" xmlns:xlink=\"http://www.w3.org/1999/xlink\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://www.opengis.net/wps/1.0.0"
// + "http://schemas.opengis.net/wps/1.0.0/wpsExecute_request.xsd\">"
// +
// "<ows:Identifier>org.n52.wps.server.algorithm.SimpleBufferAlgorithm</ows:Identifier>"
// + "<wps:DataInputs>"
// + "<wps:Input>"
// + "<ows:Identifier>data</ows:Identifier>"
// +
// "<wps:Reference schema=\"http://schemas.opengis.net/gml/2.1.2/feature.xsd\" xlink:href=\"http://geoprocessing.demo.52north.org:8080/geoserver/ows?service=WFS&version=1.0.0&request=GetFeature&typeName=topp:tasmania_roads\"/>"
// + "</wps:Input>"
// + "<wps:Input>"
// + "<ows:Identifier>width</ows:Identifier>"
// +
// "<ows:Title>Distance which people will walk to get to a playground.</ows:Title>"
// + "<wps:Data>"
// + "<wps:LiteralData>20</wps:LiteralData>"
// + "</wps:Data>"
// + "</wps:Input>"
// + "</wps:DataInputs>"
// + "<wps:ResponseForm>"
// + "<wps:ResponseDocument>"
// + "<wps:Output>"
// + "<ows:Identifier>result</ows:Identifier>"
// + "</wps:Output>"
// + "</wps:ResponseDocument>"
// + "</wps:ResponseForm>"
// + "</wps:Execute>";
// String response = PostClient.sendRequest(url, payload);
//
// assertThat(AllTestsIT.parseXML(response), is(not(nullValue())));
// assertThat(response, response, not(containsString("ExceptionReport")));
// assertThat(response, response, containsString("LinearRing"));
// }
//
// /*Complex binary Input by value */
// // Disabled test due to heap size issues.
// @Test
// public void testExecutePOSTValueComplexBinarySynchronousBinaryOutput()
// throws IOException, ParserConfigurationException, SAXException {
// System.out.println("\nRunning testExecutePOSTValueComplexBinarySynchronousBinaryOutput");
// String payload =
// "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>"
// +
// "<wps:Execute service=\"WPS\" version=\"1.0.0\" xmlns:wps=\"http://www.opengis.net/wps/1.0.0\" xmlns:ows=\"http://www.opengis.net/ows/1.1\" xmlns:xlink=\"http://www.w3.org/1999/xlink\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://www.opengis.net/wps/1.0.0"
// + "http://schemas.opengis.net/wps/1.0.0/wpsExecute_request.xsd\">"
// +
// "<ows:Identifier>org.n52.wps.server.algorithm.raster.AddRasterValues</ows:Identifier>"
// + "<wps:DataInputs>"
// + "<wps:Input>"
// + "<ows:Identifier>dataset1</ows:Identifier>"
// +
// "<wps:Reference mimeType=\"image/tiff\" xlink:href=\"http://52north.org/files/geoprocessing/Testdata/elev_srtm_30m.tif\">"
// + "</wps:Reference>"
// + "</wps:Input>"
// + "<wps:Input>"
// + "<ows:Identifier>dataset2</ows:Identifier>"
// +
// "<wps:Reference mimeType=\"image/tiff\" xlink:href=\"http://52north.org/files/geoprocessing/Testdata/elev_srtm_30m.tif\">"
// + "</wps:Reference>"
// + "</wps:Input>"
// + "</wps:DataInputs>"
// + "<wps:ResponseForm>"
// + "<wps:ResponseDocument status=\"true\" storeExecuteResponse=\"true\">"
// + "<wps:Output encoding=\"base64\" >"
// + "<ows:Identifier>result</ows:Identifier>"
// + "</wps:Output>"
// + "</wps:ResponseDocument>"
// + "</wps:ResponseForm>"
// + "</wps:Execute>";
// String response = PostClient.sendRequest(url, payload);
// AllTestsIT.validateBinaryBase64Async(response);
// }
}
| false | true | public void calculatorWorksCorrectly() throws IOException, ParserConfigurationException, SAXException, XmlException {
URL resource = WPS4RTester.class.getResource("/R/ExecuteTestCalculator.xml");
XmlObject xmlPayload = XmlObject.Factory.parse(resource);
String payload = xmlPayload.toString();
Random rand = new Random();
int a = rand.nextInt(100);
payload.replace("@@@a@@@", Integer.toString(a));
int b = rand.nextInt(100);
payload.replace("@@@a@@@", Integer.toString(b));
int op = rand.nextInt(3);
String[] ops = new String[] {"+", "-", "*"};
String opString = ops[op];
payload.replace("@@@a@@@", opString);
int result = Integer.MIN_VALUE;
if (opString.equals("+"))
result = a + b;
else if (opString.equals("-"))
result = a - b;
else if (opString.equals("*"))
result = a * b;
String response = PostClient.sendRequest(wpsUrl, payload);
assertThat(AllTestsIT.parseXML(response), is(not(nullValue())));
assertThat(response, containsString(Integer.toString(result)));
}
| public void calculatorWorksCorrectly() throws IOException, ParserConfigurationException, SAXException, XmlException {
URL resource = WPS4RTester.class.getResource("/R/ExecuteTestCalculator.xml");
XmlObject xmlPayload = XmlObject.Factory.parse(resource);
String payload = xmlPayload.toString();
Random rand = new Random();
int a = rand.nextInt(100);
payload = payload.replace("@@@a@@@", Integer.toString(a));
int b = rand.nextInt(100);
payload = payload.replace("@@@b@@@", Integer.toString(b));
int op = rand.nextInt(3);
String[] ops = new String[] {"+", "-", "*"};
String opString = ops[op];
payload = payload.replace("@@@op@@@", opString);
int result = Integer.MIN_VALUE;
if (opString.equals("+"))
result = a + b;
else if (opString.equals("-"))
result = a - b;
else if (opString.equals("*"))
result = a * b;
String response = PostClient.sendRequest(wpsUrl, payload);
assertThat(AllTestsIT.parseXML(response), is(not(nullValue())));
assertThat(response, containsString(Integer.toString(result)));
}
|
diff --git a/src/org/accesointeligente/client/presenters/ResponseUserSatisfactionPresenter.java b/src/org/accesointeligente/client/presenters/ResponseUserSatisfactionPresenter.java
index 51cd0a6..9c0952d 100644
--- a/src/org/accesointeligente/client/presenters/ResponseUserSatisfactionPresenter.java
+++ b/src/org/accesointeligente/client/presenters/ResponseUserSatisfactionPresenter.java
@@ -1,191 +1,191 @@
/**
* Acceso Inteligente
*
* Copyright (C) 2010-2011 Fundación Ciudadano Inteligente
*
* This program 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.
*
* 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.accesointeligente.client.presenters;
import org.accesointeligente.client.services.RequestServiceAsync;
import org.accesointeligente.client.uihandlers.ResponseUserSatisfactionUiHandlers;
import org.accesointeligente.model.Request;
import org.accesointeligente.model.Response;
import org.accesointeligente.shared.*;
import com.google.gwt.event.shared.EventBus;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.gwtplatform.mvp.client.HasUiHandlers;
import com.gwtplatform.mvp.client.Presenter;
import com.gwtplatform.mvp.client.View;
import com.gwtplatform.mvp.client.annotations.NameToken;
import com.gwtplatform.mvp.client.annotations.ProxyCodeSplit;
import com.gwtplatform.mvp.client.proxy.*;
import javax.inject.Inject;
public class ResponseUserSatisfactionPresenter extends Presenter<ResponseUserSatisfactionPresenter.MyView, ResponseUserSatisfactionPresenter.MyProxy> implements ResponseUserSatisfactionUiHandlers {
public interface MyView extends View, HasUiHandlers<ResponseUserSatisfactionUiHandlers> {
void showUserSatisfactionPanel(Boolean visible);
void showRequestStatusPanel(Boolean visible);
}
@ProxyCodeSplit
@NameToken(AppPlace.RESPONSEUSERSATISFACTION)
public interface MyProxy extends ProxyPlace<ResponseUserSatisfactionPresenter> {
}
@Inject
private PlaceManager placeManager;
@Inject
private RequestServiceAsync requestService;
private String responseKey;
private Integer responseId;
private Response response;
private Request request;
@Inject
public ResponseUserSatisfactionPresenter(EventBus eventBus, MyView view, MyProxy proxy) {
super(eventBus, view, proxy);
getView().setUiHandlers(this);
}
@Override
protected void onReset() {
Window.setTitle("Danos tu opinion");
if (responseId != null) {
loadResponse();
}
}
@Override
protected void revealInParent() {
fireEvent(new RevealContentEvent(MainPresenter.SLOT_MAIN_CONTENT, this));
}
@Override
public void prepareFromRequest(PlaceRequest request) {
super.prepareFromRequest(request);
try {
responseId = Integer.parseInt(request.getParameter("responseId", null));
responseKey = request.getParameter("responseKey", null);
} catch (Exception ex) {
responseId = null;
responseKey = null;
}
}
private void loadResponse() {
if (responseId == null || responseKey == null) {
showNotification("Falta más información para cargar esta ventana", NotificationEventType.ERROR);
placeManager.revealDefaultPlace();
}
requestService.getResponse(responseId, responseKey, new AsyncCallback<Response>() {
@Override
public void onFailure(Throwable caught) {
showNotification("No fue posible cargar la información de la respuesta, por favor intente nuevamente", NotificationEventType.ERROR);
}
@Override
public void onSuccess(Response result) {
if (result != null) {
response = result;
requestService.getRequestByResponseId(responseId, new AsyncCallback<Request>() {
@Override
public void onFailure(Throwable caught) {
showNotification("No fue posible cargar la información de la respuesta, por favor intente nuevamente", NotificationEventType.ERROR);
}
@Override
public void onSuccess(Request result) {
if (result != null) {
request = result;
- if (response.getUserSatisfaction() != null) {
+ if (response.getUserSatisfaction() != null && response.getUserSatisfaction() != UserSatisfaction.NOANSWER) {
getView().showUserSatisfactionPanel(false);
getView().showRequestStatusPanel(false);
}
} else {
showNotification("No fue posible cargar la información de la respuesta, por favor intente nuevamente", NotificationEventType.ERROR);
placeManager.revealDefaultPlace();
}
}
});
} else {
showNotification("La información entregada es incorrecta", NotificationEventType.ERROR);
placeManager.revealDefaultPlace();
}
}
});
}
@Override
public void updateResponse(ResponseType responseType, UserSatisfaction userSatisfaction) {
response.setUserSatisfaction(userSatisfaction);
response.setType(responseType);
requestService.saveResponse(response, new AsyncCallback<Response>() {
@Override
public void onFailure(Throwable caught) {
showNotification("No fue posible realizar esta acción, por favor intente nuevamente", NotificationEventType.ERROR);
getView().showUserSatisfactionPanel(true);
getView().showRequestStatusPanel(false);
}
@Override
public void onSuccess(Response result) {
requestService.setRequestUserSatisfaction(request, new AsyncCallback<Request>() {
@Override
public void onFailure(Throwable caught) {
showNotification("No fue posible realizar esta acción, por favor intente nuevamente", NotificationEventType.ERROR);
getView().showUserSatisfactionPanel(true);
getView().showRequestStatusPanel(false);
}
@Override
public void onSuccess(Request result) {
showNotification("Hemos guardado su respuesta", NotificationEventType.SUCCESS);
getView().showUserSatisfactionPanel(false);
getView().showRequestStatusPanel(false);
}
});
}
});
}
@Override
public RequestStatus getRequestStatus() {
if (response != null) {
return response.getRequest().getStatus();
} else {
return null;
}
}
@Override
public void showNotification(String message, NotificationEventType type) {
NotificationEventParams params = new NotificationEventParams();
params.setMessage(message);
params.setType(type);
params.setDuration(NotificationEventParams.DURATION_NORMAL);
fireEvent(new NotificationEvent(params));
}
}
| true | true | private void loadResponse() {
if (responseId == null || responseKey == null) {
showNotification("Falta más información para cargar esta ventana", NotificationEventType.ERROR);
placeManager.revealDefaultPlace();
}
requestService.getResponse(responseId, responseKey, new AsyncCallback<Response>() {
@Override
public void onFailure(Throwable caught) {
showNotification("No fue posible cargar la información de la respuesta, por favor intente nuevamente", NotificationEventType.ERROR);
}
@Override
public void onSuccess(Response result) {
if (result != null) {
response = result;
requestService.getRequestByResponseId(responseId, new AsyncCallback<Request>() {
@Override
public void onFailure(Throwable caught) {
showNotification("No fue posible cargar la información de la respuesta, por favor intente nuevamente", NotificationEventType.ERROR);
}
@Override
public void onSuccess(Request result) {
if (result != null) {
request = result;
if (response.getUserSatisfaction() != null) {
getView().showUserSatisfactionPanel(false);
getView().showRequestStatusPanel(false);
}
} else {
showNotification("No fue posible cargar la información de la respuesta, por favor intente nuevamente", NotificationEventType.ERROR);
placeManager.revealDefaultPlace();
}
}
});
} else {
showNotification("La información entregada es incorrecta", NotificationEventType.ERROR);
placeManager.revealDefaultPlace();
}
}
});
}
| private void loadResponse() {
if (responseId == null || responseKey == null) {
showNotification("Falta más información para cargar esta ventana", NotificationEventType.ERROR);
placeManager.revealDefaultPlace();
}
requestService.getResponse(responseId, responseKey, new AsyncCallback<Response>() {
@Override
public void onFailure(Throwable caught) {
showNotification("No fue posible cargar la información de la respuesta, por favor intente nuevamente", NotificationEventType.ERROR);
}
@Override
public void onSuccess(Response result) {
if (result != null) {
response = result;
requestService.getRequestByResponseId(responseId, new AsyncCallback<Request>() {
@Override
public void onFailure(Throwable caught) {
showNotification("No fue posible cargar la información de la respuesta, por favor intente nuevamente", NotificationEventType.ERROR);
}
@Override
public void onSuccess(Request result) {
if (result != null) {
request = result;
if (response.getUserSatisfaction() != null && response.getUserSatisfaction() != UserSatisfaction.NOANSWER) {
getView().showUserSatisfactionPanel(false);
getView().showRequestStatusPanel(false);
}
} else {
showNotification("No fue posible cargar la información de la respuesta, por favor intente nuevamente", NotificationEventType.ERROR);
placeManager.revealDefaultPlace();
}
}
});
} else {
showNotification("La información entregada es incorrecta", NotificationEventType.ERROR);
placeManager.revealDefaultPlace();
}
}
});
}
|
diff --git a/doxia-site-renderer/src/test/java/org/apache/maven/doxia/siterenderer/EntitiesVerifier.java b/doxia-site-renderer/src/test/java/org/apache/maven/doxia/siterenderer/EntitiesVerifier.java
index 0255fd4..17a77d9 100644
--- a/doxia-site-renderer/src/test/java/org/apache/maven/doxia/siterenderer/EntitiesVerifier.java
+++ b/doxia-site-renderer/src/test/java/org/apache/maven/doxia/siterenderer/EntitiesVerifier.java
@@ -1,143 +1,148 @@
package org.apache.maven.doxia.siterenderer;
/*
* 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 com.gargoylesoftware.htmlunit.html.HtmlAnchor;
import com.gargoylesoftware.htmlunit.html.HtmlDivision;
import com.gargoylesoftware.htmlunit.html.HtmlElement;
import com.gargoylesoftware.htmlunit.html.HtmlHeader2;
import com.gargoylesoftware.htmlunit.html.HtmlHeader3;
import com.gargoylesoftware.htmlunit.html.HtmlHeader4;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
import com.gargoylesoftware.htmlunit.html.HtmlParagraph;
import com.gargoylesoftware.htmlunit.html.HtmlPreformattedText;
import java.util.Iterator;
/**
* Verify the <code>site/xdoc/entityTest.xml</code>
*
* @author ltheussl
* @version $Id$
*/
public class EntitiesVerifier
extends AbstractVerifier
{
/** {@inheritDoc} */
public void verify( String file )
throws Exception
{
HtmlPage page = htmlPage( file );
assertNotNull( page );
HtmlElement element = page.getHtmlElementById( "contentBox" );
assertNotNull( element );
HtmlDivision division = (HtmlDivision) element;
assertNotNull( division );
Iterator elementIterator = division.getAllHtmlChildElements();
// ----------------------------------------------------------------------
//
// ----------------------------------------------------------------------
HtmlDivision div = (HtmlDivision) elementIterator.next();
assertNotNull( div );
assertEquals( div.getAttributeValue( "class" ), "section" );
HtmlHeader2 h2 = (HtmlHeader2) elementIterator.next();
assertNotNull( h2 );
- assertEquals( h2.asText().trim(), "section name" );
+ // DOXIA-311: FIXME!
+ //assertEquals( h2.asText().trim(), "section name with entities: '&' 'Α' ' '" );
HtmlAnchor a = (HtmlAnchor) elementIterator.next();
assertNotNull( a );
- assertEquals( a.getAttributeValue( "name" ), "section_name" );
+ // DOXIA-311: FIXME!
+ //assertEquals( a.getAttributeValue( "name" ), "section_name_with_entities:____" );
div = (HtmlDivision) elementIterator.next();
assertNotNull( div );
assertEquals( div.getAttributeValue( "class" ), "section" );
div = (HtmlDivision) elementIterator.next();
assertNotNull( div );
assertEquals( div.getAttributeValue( "class" ), "section" );
HtmlHeader4 h4 = (HtmlHeader4) elementIterator.next();
assertNotNull( h4 );
assertEquals( h4.asText().trim(), "Entities" );
div = (HtmlDivision) elementIterator.next();
HtmlHeader3 h3 = (HtmlHeader3) elementIterator.next();
assertNotNull( h3 );
- assertEquals( h3.asText().trim(), "Generic Entities" );
+ assertEquals( h3.asText().trim(), "Generic Entities: '&' '<' '>' '\"' '''" );
a = (HtmlAnchor) elementIterator.next();
HtmlParagraph p = (HtmlParagraph) elementIterator.next();
assertNotNull( p );
assertEquals( p.asText().trim(), "'&' '<' '>' '\"' '''" );
div = (HtmlDivision) elementIterator.next();
h3 = (HtmlHeader3) elementIterator.next();
assertNotNull( h3 );
- assertEquals( h3.asText().trim(), "Local Entities" );
+ // DOXIA-311: FIXME!
+ //assertEquals( h3.asText().trim(), "Local Entities: 'Α' 'Β' 'Γ'" );
a = (HtmlAnchor) elementIterator.next();
p = (HtmlParagraph) elementIterator.next();
assertNotNull( p );
- assertEquals( p.asText().trim(), "'Α' 'Β' 'Γ'" );
+ // DOXIA-310: FIXME!
+ //assertEquals( p.asText().trim(), "'Α' 'Β' 'Γ'" );
div = (HtmlDivision) elementIterator.next();
h3 = (HtmlHeader3) elementIterator.next();
assertNotNull( h3 );
- assertEquals( h3.asText().trim(), "DTD Entities" );
+ // DOXIA-311: FIXME!
+ //assertEquals( h3.asText().trim(), "DTD Entities: ' ' '¡' '¢'" );
a = (HtmlAnchor) elementIterator.next();
p = (HtmlParagraph) elementIterator.next();
assertNotNull( p );
assertEquals( p.asText().trim(), "' ' '¡' '¢'" );
div = (HtmlDivision) elementIterator.next();
assertNotNull( div );
assertEquals( div.getAttributeValue( "class" ), "section" );
h4 = (HtmlHeader4) elementIterator.next();
assertNotNull( h4 );
assertEquals( h4.asText().trim(), "CDATA" );
div = (HtmlDivision) elementIterator.next();
assertNotNull( div );
assertEquals( div.getAttributeValue( "class" ), "source" );
HtmlPreformattedText pre = (HtmlPreformattedText) elementIterator.next();
assertNotNull( pre );
assertEquals( pre.asText().trim(), "<project xmlns:ant=\"jelly:ant\">" );
p = (HtmlParagraph) elementIterator.next();
assertNotNull( p );
assertEquals( p.asText().trim(), "' ' '¡'" );
assertFalse( elementIterator.hasNext() );
}
}
| false | true | public void verify( String file )
throws Exception
{
HtmlPage page = htmlPage( file );
assertNotNull( page );
HtmlElement element = page.getHtmlElementById( "contentBox" );
assertNotNull( element );
HtmlDivision division = (HtmlDivision) element;
assertNotNull( division );
Iterator elementIterator = division.getAllHtmlChildElements();
// ----------------------------------------------------------------------
//
// ----------------------------------------------------------------------
HtmlDivision div = (HtmlDivision) elementIterator.next();
assertNotNull( div );
assertEquals( div.getAttributeValue( "class" ), "section" );
HtmlHeader2 h2 = (HtmlHeader2) elementIterator.next();
assertNotNull( h2 );
assertEquals( h2.asText().trim(), "section name" );
HtmlAnchor a = (HtmlAnchor) elementIterator.next();
assertNotNull( a );
assertEquals( a.getAttributeValue( "name" ), "section_name" );
div = (HtmlDivision) elementIterator.next();
assertNotNull( div );
assertEquals( div.getAttributeValue( "class" ), "section" );
div = (HtmlDivision) elementIterator.next();
assertNotNull( div );
assertEquals( div.getAttributeValue( "class" ), "section" );
HtmlHeader4 h4 = (HtmlHeader4) elementIterator.next();
assertNotNull( h4 );
assertEquals( h4.asText().trim(), "Entities" );
div = (HtmlDivision) elementIterator.next();
HtmlHeader3 h3 = (HtmlHeader3) elementIterator.next();
assertNotNull( h3 );
assertEquals( h3.asText().trim(), "Generic Entities" );
a = (HtmlAnchor) elementIterator.next();
HtmlParagraph p = (HtmlParagraph) elementIterator.next();
assertNotNull( p );
assertEquals( p.asText().trim(), "'&' '<' '>' '\"' '''" );
div = (HtmlDivision) elementIterator.next();
h3 = (HtmlHeader3) elementIterator.next();
assertNotNull( h3 );
assertEquals( h3.asText().trim(), "Local Entities" );
a = (HtmlAnchor) elementIterator.next();
p = (HtmlParagraph) elementIterator.next();
assertNotNull( p );
assertEquals( p.asText().trim(), "'Α' 'Β' 'Γ'" );
div = (HtmlDivision) elementIterator.next();
h3 = (HtmlHeader3) elementIterator.next();
assertNotNull( h3 );
assertEquals( h3.asText().trim(), "DTD Entities" );
a = (HtmlAnchor) elementIterator.next();
p = (HtmlParagraph) elementIterator.next();
assertNotNull( p );
assertEquals( p.asText().trim(), "' ' '¡' '¢'" );
div = (HtmlDivision) elementIterator.next();
assertNotNull( div );
assertEquals( div.getAttributeValue( "class" ), "section" );
h4 = (HtmlHeader4) elementIterator.next();
assertNotNull( h4 );
assertEquals( h4.asText().trim(), "CDATA" );
div = (HtmlDivision) elementIterator.next();
assertNotNull( div );
assertEquals( div.getAttributeValue( "class" ), "source" );
HtmlPreformattedText pre = (HtmlPreformattedText) elementIterator.next();
assertNotNull( pre );
assertEquals( pre.asText().trim(), "<project xmlns:ant=\"jelly:ant\">" );
p = (HtmlParagraph) elementIterator.next();
assertNotNull( p );
assertEquals( p.asText().trim(), "' ' '¡'" );
assertFalse( elementIterator.hasNext() );
}
| public void verify( String file )
throws Exception
{
HtmlPage page = htmlPage( file );
assertNotNull( page );
HtmlElement element = page.getHtmlElementById( "contentBox" );
assertNotNull( element );
HtmlDivision division = (HtmlDivision) element;
assertNotNull( division );
Iterator elementIterator = division.getAllHtmlChildElements();
// ----------------------------------------------------------------------
//
// ----------------------------------------------------------------------
HtmlDivision div = (HtmlDivision) elementIterator.next();
assertNotNull( div );
assertEquals( div.getAttributeValue( "class" ), "section" );
HtmlHeader2 h2 = (HtmlHeader2) elementIterator.next();
assertNotNull( h2 );
// DOXIA-311: FIXME!
//assertEquals( h2.asText().trim(), "section name with entities: '&' 'Α' ' '" );
HtmlAnchor a = (HtmlAnchor) elementIterator.next();
assertNotNull( a );
// DOXIA-311: FIXME!
//assertEquals( a.getAttributeValue( "name" ), "section_name_with_entities:____" );
div = (HtmlDivision) elementIterator.next();
assertNotNull( div );
assertEquals( div.getAttributeValue( "class" ), "section" );
div = (HtmlDivision) elementIterator.next();
assertNotNull( div );
assertEquals( div.getAttributeValue( "class" ), "section" );
HtmlHeader4 h4 = (HtmlHeader4) elementIterator.next();
assertNotNull( h4 );
assertEquals( h4.asText().trim(), "Entities" );
div = (HtmlDivision) elementIterator.next();
HtmlHeader3 h3 = (HtmlHeader3) elementIterator.next();
assertNotNull( h3 );
assertEquals( h3.asText().trim(), "Generic Entities: '&' '<' '>' '\"' '''" );
a = (HtmlAnchor) elementIterator.next();
HtmlParagraph p = (HtmlParagraph) elementIterator.next();
assertNotNull( p );
assertEquals( p.asText().trim(), "'&' '<' '>' '\"' '''" );
div = (HtmlDivision) elementIterator.next();
h3 = (HtmlHeader3) elementIterator.next();
assertNotNull( h3 );
// DOXIA-311: FIXME!
//assertEquals( h3.asText().trim(), "Local Entities: 'Α' 'Β' 'Γ'" );
a = (HtmlAnchor) elementIterator.next();
p = (HtmlParagraph) elementIterator.next();
assertNotNull( p );
// DOXIA-310: FIXME!
//assertEquals( p.asText().trim(), "'Α' 'Β' 'Γ'" );
div = (HtmlDivision) elementIterator.next();
h3 = (HtmlHeader3) elementIterator.next();
assertNotNull( h3 );
// DOXIA-311: FIXME!
//assertEquals( h3.asText().trim(), "DTD Entities: ' ' '¡' '¢'" );
a = (HtmlAnchor) elementIterator.next();
p = (HtmlParagraph) elementIterator.next();
assertNotNull( p );
assertEquals( p.asText().trim(), "' ' '¡' '¢'" );
div = (HtmlDivision) elementIterator.next();
assertNotNull( div );
assertEquals( div.getAttributeValue( "class" ), "section" );
h4 = (HtmlHeader4) elementIterator.next();
assertNotNull( h4 );
assertEquals( h4.asText().trim(), "CDATA" );
div = (HtmlDivision) elementIterator.next();
assertNotNull( div );
assertEquals( div.getAttributeValue( "class" ), "source" );
HtmlPreformattedText pre = (HtmlPreformattedText) elementIterator.next();
assertNotNull( pre );
assertEquals( pre.asText().trim(), "<project xmlns:ant=\"jelly:ant\">" );
p = (HtmlParagraph) elementIterator.next();
assertNotNull( p );
assertEquals( p.asText().trim(), "' ' '¡'" );
assertFalse( elementIterator.hasNext() );
}
|
diff --git a/util/src/test/java/com/ning/billing/util/dao/TestStringTemplateInheritance.java b/util/src/test/java/com/ning/billing/util/dao/TestStringTemplateInheritance.java
index 1306cfeb6..df148e12e 100644
--- a/util/src/test/java/com/ning/billing/util/dao/TestStringTemplateInheritance.java
+++ b/util/src/test/java/com/ning/billing/util/dao/TestStringTemplateInheritance.java
@@ -1,191 +1,192 @@
/*
* Copyright 2010-2012 Ning, Inc.
*
* Ning licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package com.ning.billing.util.dao;
import java.io.InputStream;
import java.io.InputStreamReader;
import org.antlr.stringtemplate.StringTemplateGroup;
import org.testng.Assert;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import com.ning.billing.util.UtilTestSuiteNoDB;
import com.google.common.collect.ImmutableMap;
public class TestStringTemplateInheritance extends UtilTestSuiteNoDB {
InputStream entityStream;
InputStream kombuchaStream;
@Override
@BeforeMethod(groups = "fast")
public void beforeMethod() throws Exception {
super.beforeMethod();
entityStream = this.getClass().getResourceAsStream("/com/ning/billing/util/entity/dao/EntitySqlDao.sql.stg");
kombuchaStream = this.getClass().getResourceAsStream("/com/ning/billing/util/dao/Kombucha.sql.stg");
}
@Override
@AfterMethod(groups = "fast")
public void afterMethod() throws Exception {
super.afterMethod();
if (entityStream != null) {
entityStream.close();
}
if (kombuchaStream != null) {
kombuchaStream.close();
}
}
@Test(groups = "fast")
public void testCheckQueries() throws Exception {
// From http://www.antlr.org/wiki/display/ST/ST+condensed+--+Templates+and+groups#STcondensed--Templatesandgroups-Withsupergroupfile:
// there is no mechanism for automatically loading a mentioned super-group file
new StringTemplateGroup(new InputStreamReader(entityStream));
final StringTemplateGroup kombucha = new StringTemplateGroup(new InputStreamReader(kombuchaStream));
// Verify non inherited template
Assert.assertEquals(kombucha.getInstanceOf("isIsTimeForKombucha").toString(), "select hour(current_timestamp()) = 17 as is_time;");
// Verify inherited templates
Assert.assertEquals(kombucha.getInstanceOf("getById").toString(), "select\n" +
" t.record_id\n" +
", t.id\n" +
", t.tea\n" +
", t.mushroom\n" +
", t.sugar\n" +
", t.account_record_id\n" +
", t.tenant_record_id\n" +
"from kombucha t\n" +
"where t.id = :id\n" +
"and t.tenant_record_id = :tenantRecordId\n" +
";");
Assert.assertEquals(kombucha.getInstanceOf("getByRecordId").toString(), "select\n" +
" t.record_id\n" +
", t.id\n" +
", t.tea\n" +
", t.mushroom\n" +
", t.sugar\n" +
", t.account_record_id\n" +
", t.tenant_record_id\n" +
"from kombucha t\n" +
"where t.record_id = :recordId\n" +
"and t.tenant_record_id = :tenantRecordId\n" +
";");
Assert.assertEquals(kombucha.getInstanceOf("getRecordId").toString(), "select\n" +
" t.record_id\n" +
"from kombucha t\n" +
"where t.id = :id\n" +
"and t.tenant_record_id = :tenantRecordId\n" +
";");
Assert.assertEquals(kombucha.getInstanceOf("getHistoryRecordId").toString(), "select\n" +
" max(t.record_id)\n" +
"from kombucha_history t\n" +
"where t.target_record_id = :targetRecordId\n" +
"and t.tenant_record_id = :tenantRecordId\n" +
";");
Assert.assertEquals(kombucha.getInstanceOf("getAll").toString(), "select\n" +
" t.record_id\n" +
", t.id\n" +
", t.tea\n" +
", t.mushroom\n" +
", t.sugar\n" +
", t.account_record_id\n" +
", t.tenant_record_id\n" +
"from kombucha t\n" +
"where t.tenant_record_id = :tenantRecordId\n" +
+ "order by t.record_id ASC\n" +
";");
Assert.assertEquals(kombucha.getInstanceOf("get", ImmutableMap.<String, String>of("orderBy", "recordId", "offset", "3", "rowCount", "12")).toString(), "select SQL_CALC_FOUND_ROWS\n" +
" t.record_id\n" +
", t.id\n" +
", t.tea\n" +
", t.mushroom\n" +
", t.sugar\n" +
", t.account_record_id\n" +
", t.tenant_record_id\n" +
"from kombucha t\n" +
"where t.tenant_record_id = :tenantRecordId\n" +
"order by :orderBy\n" +
"limit :offset, :rowCount\n" +
";");
Assert.assertEquals(kombucha.getInstanceOf("test").toString(), "select\n" +
" t.record_id\n" +
", t.id\n" +
", t.tea\n" +
", t.mushroom\n" +
", t.sugar\n" +
", t.account_record_id\n" +
", t.tenant_record_id\n" +
"from kombucha t\n" +
"where t.tenant_record_id = :tenantRecordId\n" +
"limit 1\n" +
";");
Assert.assertEquals(kombucha.getInstanceOf("addHistoryFromTransaction").toString(), "insert into kombucha_history (\n" +
" id\n" +
", target_record_id\n" +
", change_type\n" +
", tea\n" +
", mushroom\n" +
", sugar\n" +
", account_record_id\n" +
", tenant_record_id\n" +
")\n" +
"values (\n" +
" :id\n" +
", :targetRecordId\n" +
", :changeType\n" +
", :tea\n" +
", :mushroom\n" +
", :sugar\n" +
", :accountRecordId\n" +
", :tenantRecordId\n" +
")\n" +
";");
Assert.assertEquals(kombucha.getInstanceOf("insertAuditFromTransaction").toString(), "insert into audit_log (\n" +
"id\n" +
", table_name\n" +
", target_record_id\n" +
", change_type\n" +
", created_by\n" +
", reason_code\n" +
", comments\n" +
", user_token\n" +
", created_date\n" +
", account_record_id\n" +
", tenant_record_id\n" +
")\n" +
"values (\n" +
" :id\n" +
", :tableName\n" +
", :targetRecordId\n" +
", :changeType\n" +
", :createdBy\n" +
", :reasonCode\n" +
", :comments\n" +
", :userToken\n" +
", :createdDate\n" +
", :accountRecordId\n" +
", :tenantRecordId\n" +
")\n" +
";");
}
}
| true | true | public void testCheckQueries() throws Exception {
// From http://www.antlr.org/wiki/display/ST/ST+condensed+--+Templates+and+groups#STcondensed--Templatesandgroups-Withsupergroupfile:
// there is no mechanism for automatically loading a mentioned super-group file
new StringTemplateGroup(new InputStreamReader(entityStream));
final StringTemplateGroup kombucha = new StringTemplateGroup(new InputStreamReader(kombuchaStream));
// Verify non inherited template
Assert.assertEquals(kombucha.getInstanceOf("isIsTimeForKombucha").toString(), "select hour(current_timestamp()) = 17 as is_time;");
// Verify inherited templates
Assert.assertEquals(kombucha.getInstanceOf("getById").toString(), "select\n" +
" t.record_id\n" +
", t.id\n" +
", t.tea\n" +
", t.mushroom\n" +
", t.sugar\n" +
", t.account_record_id\n" +
", t.tenant_record_id\n" +
"from kombucha t\n" +
"where t.id = :id\n" +
"and t.tenant_record_id = :tenantRecordId\n" +
";");
Assert.assertEquals(kombucha.getInstanceOf("getByRecordId").toString(), "select\n" +
" t.record_id\n" +
", t.id\n" +
", t.tea\n" +
", t.mushroom\n" +
", t.sugar\n" +
", t.account_record_id\n" +
", t.tenant_record_id\n" +
"from kombucha t\n" +
"where t.record_id = :recordId\n" +
"and t.tenant_record_id = :tenantRecordId\n" +
";");
Assert.assertEquals(kombucha.getInstanceOf("getRecordId").toString(), "select\n" +
" t.record_id\n" +
"from kombucha t\n" +
"where t.id = :id\n" +
"and t.tenant_record_id = :tenantRecordId\n" +
";");
Assert.assertEquals(kombucha.getInstanceOf("getHistoryRecordId").toString(), "select\n" +
" max(t.record_id)\n" +
"from kombucha_history t\n" +
"where t.target_record_id = :targetRecordId\n" +
"and t.tenant_record_id = :tenantRecordId\n" +
";");
Assert.assertEquals(kombucha.getInstanceOf("getAll").toString(), "select\n" +
" t.record_id\n" +
", t.id\n" +
", t.tea\n" +
", t.mushroom\n" +
", t.sugar\n" +
", t.account_record_id\n" +
", t.tenant_record_id\n" +
"from kombucha t\n" +
"where t.tenant_record_id = :tenantRecordId\n" +
";");
Assert.assertEquals(kombucha.getInstanceOf("get", ImmutableMap.<String, String>of("orderBy", "recordId", "offset", "3", "rowCount", "12")).toString(), "select SQL_CALC_FOUND_ROWS\n" +
" t.record_id\n" +
", t.id\n" +
", t.tea\n" +
", t.mushroom\n" +
", t.sugar\n" +
", t.account_record_id\n" +
", t.tenant_record_id\n" +
"from kombucha t\n" +
"where t.tenant_record_id = :tenantRecordId\n" +
"order by :orderBy\n" +
"limit :offset, :rowCount\n" +
";");
Assert.assertEquals(kombucha.getInstanceOf("test").toString(), "select\n" +
" t.record_id\n" +
", t.id\n" +
", t.tea\n" +
", t.mushroom\n" +
", t.sugar\n" +
", t.account_record_id\n" +
", t.tenant_record_id\n" +
"from kombucha t\n" +
"where t.tenant_record_id = :tenantRecordId\n" +
"limit 1\n" +
";");
Assert.assertEquals(kombucha.getInstanceOf("addHistoryFromTransaction").toString(), "insert into kombucha_history (\n" +
" id\n" +
", target_record_id\n" +
", change_type\n" +
", tea\n" +
", mushroom\n" +
", sugar\n" +
", account_record_id\n" +
", tenant_record_id\n" +
")\n" +
"values (\n" +
" :id\n" +
", :targetRecordId\n" +
", :changeType\n" +
", :tea\n" +
", :mushroom\n" +
", :sugar\n" +
", :accountRecordId\n" +
", :tenantRecordId\n" +
")\n" +
";");
Assert.assertEquals(kombucha.getInstanceOf("insertAuditFromTransaction").toString(), "insert into audit_log (\n" +
"id\n" +
", table_name\n" +
", target_record_id\n" +
", change_type\n" +
", created_by\n" +
", reason_code\n" +
", comments\n" +
", user_token\n" +
", created_date\n" +
", account_record_id\n" +
", tenant_record_id\n" +
")\n" +
"values (\n" +
" :id\n" +
", :tableName\n" +
", :targetRecordId\n" +
", :changeType\n" +
", :createdBy\n" +
", :reasonCode\n" +
", :comments\n" +
", :userToken\n" +
", :createdDate\n" +
", :accountRecordId\n" +
", :tenantRecordId\n" +
")\n" +
";");
}
| public void testCheckQueries() throws Exception {
// From http://www.antlr.org/wiki/display/ST/ST+condensed+--+Templates+and+groups#STcondensed--Templatesandgroups-Withsupergroupfile:
// there is no mechanism for automatically loading a mentioned super-group file
new StringTemplateGroup(new InputStreamReader(entityStream));
final StringTemplateGroup kombucha = new StringTemplateGroup(new InputStreamReader(kombuchaStream));
// Verify non inherited template
Assert.assertEquals(kombucha.getInstanceOf("isIsTimeForKombucha").toString(), "select hour(current_timestamp()) = 17 as is_time;");
// Verify inherited templates
Assert.assertEquals(kombucha.getInstanceOf("getById").toString(), "select\n" +
" t.record_id\n" +
", t.id\n" +
", t.tea\n" +
", t.mushroom\n" +
", t.sugar\n" +
", t.account_record_id\n" +
", t.tenant_record_id\n" +
"from kombucha t\n" +
"where t.id = :id\n" +
"and t.tenant_record_id = :tenantRecordId\n" +
";");
Assert.assertEquals(kombucha.getInstanceOf("getByRecordId").toString(), "select\n" +
" t.record_id\n" +
", t.id\n" +
", t.tea\n" +
", t.mushroom\n" +
", t.sugar\n" +
", t.account_record_id\n" +
", t.tenant_record_id\n" +
"from kombucha t\n" +
"where t.record_id = :recordId\n" +
"and t.tenant_record_id = :tenantRecordId\n" +
";");
Assert.assertEquals(kombucha.getInstanceOf("getRecordId").toString(), "select\n" +
" t.record_id\n" +
"from kombucha t\n" +
"where t.id = :id\n" +
"and t.tenant_record_id = :tenantRecordId\n" +
";");
Assert.assertEquals(kombucha.getInstanceOf("getHistoryRecordId").toString(), "select\n" +
" max(t.record_id)\n" +
"from kombucha_history t\n" +
"where t.target_record_id = :targetRecordId\n" +
"and t.tenant_record_id = :tenantRecordId\n" +
";");
Assert.assertEquals(kombucha.getInstanceOf("getAll").toString(), "select\n" +
" t.record_id\n" +
", t.id\n" +
", t.tea\n" +
", t.mushroom\n" +
", t.sugar\n" +
", t.account_record_id\n" +
", t.tenant_record_id\n" +
"from kombucha t\n" +
"where t.tenant_record_id = :tenantRecordId\n" +
"order by t.record_id ASC\n" +
";");
Assert.assertEquals(kombucha.getInstanceOf("get", ImmutableMap.<String, String>of("orderBy", "recordId", "offset", "3", "rowCount", "12")).toString(), "select SQL_CALC_FOUND_ROWS\n" +
" t.record_id\n" +
", t.id\n" +
", t.tea\n" +
", t.mushroom\n" +
", t.sugar\n" +
", t.account_record_id\n" +
", t.tenant_record_id\n" +
"from kombucha t\n" +
"where t.tenant_record_id = :tenantRecordId\n" +
"order by :orderBy\n" +
"limit :offset, :rowCount\n" +
";");
Assert.assertEquals(kombucha.getInstanceOf("test").toString(), "select\n" +
" t.record_id\n" +
", t.id\n" +
", t.tea\n" +
", t.mushroom\n" +
", t.sugar\n" +
", t.account_record_id\n" +
", t.tenant_record_id\n" +
"from kombucha t\n" +
"where t.tenant_record_id = :tenantRecordId\n" +
"limit 1\n" +
";");
Assert.assertEquals(kombucha.getInstanceOf("addHistoryFromTransaction").toString(), "insert into kombucha_history (\n" +
" id\n" +
", target_record_id\n" +
", change_type\n" +
", tea\n" +
", mushroom\n" +
", sugar\n" +
", account_record_id\n" +
", tenant_record_id\n" +
")\n" +
"values (\n" +
" :id\n" +
", :targetRecordId\n" +
", :changeType\n" +
", :tea\n" +
", :mushroom\n" +
", :sugar\n" +
", :accountRecordId\n" +
", :tenantRecordId\n" +
")\n" +
";");
Assert.assertEquals(kombucha.getInstanceOf("insertAuditFromTransaction").toString(), "insert into audit_log (\n" +
"id\n" +
", table_name\n" +
", target_record_id\n" +
", change_type\n" +
", created_by\n" +
", reason_code\n" +
", comments\n" +
", user_token\n" +
", created_date\n" +
", account_record_id\n" +
", tenant_record_id\n" +
")\n" +
"values (\n" +
" :id\n" +
", :tableName\n" +
", :targetRecordId\n" +
", :changeType\n" +
", :createdBy\n" +
", :reasonCode\n" +
", :comments\n" +
", :userToken\n" +
", :createdDate\n" +
", :accountRecordId\n" +
", :tenantRecordId\n" +
")\n" +
";");
}
|
diff --git a/components/bio-formats/src/loci/formats/in/CellSensReader.java b/components/bio-formats/src/loci/formats/in/CellSensReader.java
index 18b6524e9..74818a1cd 100644
--- a/components/bio-formats/src/loci/formats/in/CellSensReader.java
+++ b/components/bio-formats/src/loci/formats/in/CellSensReader.java
@@ -1,168 +1,168 @@
//
// CellSensReader.java
//
/*
OME Bio-Formats package for reading and converting biological file formats.
Copyright (C) 2005-@year@ UW-Madison LOCI and Glencoe Software, Inc.
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 loci.formats.in;
import java.io.IOException;
import java.util.ArrayList;
import loci.common.Location;
import loci.common.RandomAccessInputStream;
import loci.formats.CoreMetadata;
import loci.formats.FormatException;
import loci.formats.FormatReader;
import loci.formats.FormatTools;
import loci.formats.MetadataTools;
import loci.formats.meta.MetadataStore;
import loci.formats.tiff.IFD;
import loci.formats.tiff.IFDList;
import loci.formats.tiff.PhotoInterp;
import loci.formats.tiff.TiffParser;
/**
* CellSensReader is the file format reader for cellSens .vsi files.
*
* <dl><dt><b>Source code:</b></dt>
* <dd><a href="http://trac.openmicroscopy.org.uk/ome/browser/bioformats.git/components/bio-formats/src/loci/formats/in/CellSensReader.java">Trac</a>,
* <a href="http://git.openmicroscopy.org/?p=bioformats.git;a=blob;f=components/bio-formats/src/loci/formats/in/CellSensReader.java;hb=HEAD">Gitweb</a></dd></dl>
*/
public class CellSensReader extends FormatReader {
// -- Constants --
// -- Fields --
private String[] usedFiles;
private TiffParser parser;
private IFDList ifds;
// -- Constructor --
/** Constructs a new cellSens reader. */
public CellSensReader() {
super("CellSens VSI", "vsi");
domains = new String[] {FormatTools.HISTOLOGY_DOMAIN};
suffixSufficient = true;
}
// -- IFormatReader API methods --
/* @see loci.formats.IFormatReader#getSeriesUsedFiles(boolean) */
public String[] getSeriesUsedFiles(boolean noPixels) {
FormatTools.assertId(currentId, true, 1);
return usedFiles;
}
/**
* @see loci.formats.IFormatReader#openBytes(int, byte[], int, int, int, int)
*/
public byte[] openBytes(int no, byte[] buf, int x, int y, int w, int h)
throws FormatException, IOException
{
FormatTools.checkPlaneParameters(this, no, buf.length, x, y, w, h);
if (getSeries() < getSeriesCount() - ifds.size()) {
return buf;
}
else {
return parser.getSamples(ifds.get(getSeries()), buf, x, y, w, h);
}
}
/* @see loci.formats.IFormatReader#close(boolean) */
public void close(boolean fileOnly) throws IOException {
super.close(fileOnly);
if (!fileOnly) {
parser = null;
ifds = null;
usedFiles = null;
}
}
// -- Internal FormatReader API methods --
/* @see loci.formats.FormatReader#initFile(String) */
protected void initFile(String id) throws FormatException, IOException {
super.initFile(id);
parser = new TiffParser(id);
ifds = parser.getIFDs();
ArrayList<String> files = new ArrayList<String>();
Location file = new Location(id).getAbsoluteFile();
files.add(file.getAbsolutePath());
Location dir = file.getParentFile();
String name = file.getName();
name = name.substring(0, name.lastIndexOf("."));
Location pixelsDir = new Location(dir, "_" + name + "_");
String[] stackDirs = pixelsDir.list(true);
for (String f : stackDirs) {
Location stackDir = new Location(pixelsDir, f);
String[] pixelsFiles = stackDir.list(true);
for (String pixelsFile : pixelsFiles) {
files.add(new Location(stackDir, pixelsFile).getAbsolutePath());
}
}
usedFiles = files.toArray(new String[files.size()]);
core = new CoreMetadata[files.size() - 1 + ifds.size()];
for (int s=0; s<core.length; s++) {
core[s] = new CoreMetadata();
if (s < files.size() - 1) {
}
else {
- IFD ifd = ifds.get(s - files.size() - 1);
+ IFD ifd = ifds.get(s - files.size() + 1);
PhotoInterp p = ifd.getPhotometricInterpretation();
int samples = ifd.getSamplesPerPixel();
core[s].rgb = samples > 1 || p == PhotoInterp.RGB;
core[s].sizeX = (int) ifd.getImageWidth();
core[s].sizeY = (int) ifd.getImageLength();
core[s].sizeZ = 1;
core[s].sizeT = 1;
core[s].sizeC = core[s].rgb ? samples : 1;
core[s].littleEndian = ifd.isLittleEndian();
core[s].indexed = p == PhotoInterp.RGB_PALETTE &&
(get8BitLookupTable() != null || get16BitLookupTable() != null);
core[s].imageCount = 1;
core[s].pixelType = ifd.getPixelType();
core[s].metadataComplete = true;
core[s].interleaved = false;
core[s].falseColor = false;
core[s].dimensionOrder = "XYCZT";
core[s].thumbnail = s != 0;
}
}
MetadataStore store = makeFilterMetadata();
MetadataTools.populatePixels(store, this);
}
}
| true | true | protected void initFile(String id) throws FormatException, IOException {
super.initFile(id);
parser = new TiffParser(id);
ifds = parser.getIFDs();
ArrayList<String> files = new ArrayList<String>();
Location file = new Location(id).getAbsoluteFile();
files.add(file.getAbsolutePath());
Location dir = file.getParentFile();
String name = file.getName();
name = name.substring(0, name.lastIndexOf("."));
Location pixelsDir = new Location(dir, "_" + name + "_");
String[] stackDirs = pixelsDir.list(true);
for (String f : stackDirs) {
Location stackDir = new Location(pixelsDir, f);
String[] pixelsFiles = stackDir.list(true);
for (String pixelsFile : pixelsFiles) {
files.add(new Location(stackDir, pixelsFile).getAbsolutePath());
}
}
usedFiles = files.toArray(new String[files.size()]);
core = new CoreMetadata[files.size() - 1 + ifds.size()];
for (int s=0; s<core.length; s++) {
core[s] = new CoreMetadata();
if (s < files.size() - 1) {
}
else {
IFD ifd = ifds.get(s - files.size() - 1);
PhotoInterp p = ifd.getPhotometricInterpretation();
int samples = ifd.getSamplesPerPixel();
core[s].rgb = samples > 1 || p == PhotoInterp.RGB;
core[s].sizeX = (int) ifd.getImageWidth();
core[s].sizeY = (int) ifd.getImageLength();
core[s].sizeZ = 1;
core[s].sizeT = 1;
core[s].sizeC = core[s].rgb ? samples : 1;
core[s].littleEndian = ifd.isLittleEndian();
core[s].indexed = p == PhotoInterp.RGB_PALETTE &&
(get8BitLookupTable() != null || get16BitLookupTable() != null);
core[s].imageCount = 1;
core[s].pixelType = ifd.getPixelType();
core[s].metadataComplete = true;
core[s].interleaved = false;
core[s].falseColor = false;
core[s].dimensionOrder = "XYCZT";
core[s].thumbnail = s != 0;
}
}
MetadataStore store = makeFilterMetadata();
MetadataTools.populatePixels(store, this);
}
| protected void initFile(String id) throws FormatException, IOException {
super.initFile(id);
parser = new TiffParser(id);
ifds = parser.getIFDs();
ArrayList<String> files = new ArrayList<String>();
Location file = new Location(id).getAbsoluteFile();
files.add(file.getAbsolutePath());
Location dir = file.getParentFile();
String name = file.getName();
name = name.substring(0, name.lastIndexOf("."));
Location pixelsDir = new Location(dir, "_" + name + "_");
String[] stackDirs = pixelsDir.list(true);
for (String f : stackDirs) {
Location stackDir = new Location(pixelsDir, f);
String[] pixelsFiles = stackDir.list(true);
for (String pixelsFile : pixelsFiles) {
files.add(new Location(stackDir, pixelsFile).getAbsolutePath());
}
}
usedFiles = files.toArray(new String[files.size()]);
core = new CoreMetadata[files.size() - 1 + ifds.size()];
for (int s=0; s<core.length; s++) {
core[s] = new CoreMetadata();
if (s < files.size() - 1) {
}
else {
IFD ifd = ifds.get(s - files.size() + 1);
PhotoInterp p = ifd.getPhotometricInterpretation();
int samples = ifd.getSamplesPerPixel();
core[s].rgb = samples > 1 || p == PhotoInterp.RGB;
core[s].sizeX = (int) ifd.getImageWidth();
core[s].sizeY = (int) ifd.getImageLength();
core[s].sizeZ = 1;
core[s].sizeT = 1;
core[s].sizeC = core[s].rgb ? samples : 1;
core[s].littleEndian = ifd.isLittleEndian();
core[s].indexed = p == PhotoInterp.RGB_PALETTE &&
(get8BitLookupTable() != null || get16BitLookupTable() != null);
core[s].imageCount = 1;
core[s].pixelType = ifd.getPixelType();
core[s].metadataComplete = true;
core[s].interleaved = false;
core[s].falseColor = false;
core[s].dimensionOrder = "XYCZT";
core[s].thumbnail = s != 0;
}
}
MetadataStore store = makeFilterMetadata();
MetadataTools.populatePixels(store, this);
}
|
diff --git a/src/VASSAL/counters/PlaceMarker.java b/src/VASSAL/counters/PlaceMarker.java
index 1bc990eb..422c4976 100644
--- a/src/VASSAL/counters/PlaceMarker.java
+++ b/src/VASSAL/counters/PlaceMarker.java
@@ -1,485 +1,485 @@
/*
* $Id$
*
* Copyright (c) 2000-2003 by Rodney Kinney
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License (LGPL) as published by the Free Software Foundation.
*
* 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
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this library; if not, copies are available
* at http://www.opensource.org.
*/
package VASSAL.counters;
import java.awt.Component;
import java.awt.Frame;
import java.awt.Graphics;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.Shape;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.geom.AffineTransform;
import java.awt.geom.Point2D;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.KeyStroke;
import javax.swing.SwingUtilities;
import VASSAL.build.BadDataReport;
import VASSAL.build.Configurable;
import VASSAL.build.GameModule;
import VASSAL.build.GpIdSupport;
import VASSAL.build.module.BasicCommandEncoder;
import VASSAL.build.module.Chatter;
import VASSAL.build.module.documentation.HelpFile;
import VASSAL.build.widget.CardSlot;
import VASSAL.build.widget.PieceSlot;
import VASSAL.command.AddPiece;
import VASSAL.command.ChangeTracker;
import VASSAL.command.Command;
import VASSAL.configure.BooleanConfigurer;
import VASSAL.configure.ChooseComponentPathDialog;
import VASSAL.configure.ConfigurerWindow;
import VASSAL.configure.HotKeyConfigurer;
import VASSAL.configure.IntConfigurer;
import VASSAL.configure.StringConfigurer;
import VASSAL.i18n.PieceI18nData;
import VASSAL.i18n.TranslatablePiece;
import VASSAL.tools.ComponentPathBuilder;
import VASSAL.tools.ErrorDialog;
import VASSAL.tools.SequenceEncoder;
/**
* This Decorator defines a key command to places another counter on top of this one.
*/
public class PlaceMarker extends Decorator implements TranslatablePiece {
public static final String ID = "placemark;";
protected KeyCommand command;
protected KeyStroke key;
protected String markerSpec;
protected String markerText = "";
protected int xOffset = 0;
protected int yOffset = 0;
protected boolean matchRotation = false;
protected KeyCommand[] commands;
protected KeyStroke afterBurnerKey;
protected String description = "";
protected String gpId = "";
protected String newGpId;
protected GpIdSupport gpidSupport; // The component that generates unique Slot Id's for us
private static final int STACK_TOP = 0;
private static final int STACK_BOTTOM = 1;
private static final int ABOVE = 2;
private static final int BELOW = 3;
protected int placement = STACK_TOP;
public PlaceMarker() {
this(ID + "Place Marker;M;null;null;null", null);
}
public PlaceMarker(String type, GamePiece inner) {
mySetType(type);
setInner(inner);
}
public Rectangle boundingBox() {
return piece.boundingBox();
}
public void draw(Graphics g, int x, int y, Component obs, double zoom) {
piece.draw(g, x, y, obs, zoom);
}
public String getName() {
return piece.getName();
}
protected KeyCommand[] myGetKeyCommands() {
command.setEnabled(getMap() != null && markerSpec != null);
return commands;
}
public String myGetState() {
return "";
}
public String myGetType() {
final SequenceEncoder se = new SequenceEncoder(';');
se.append(command.getName())
.append(key)
.append(markerSpec == null ? "null" : markerSpec)
.append(markerText == null ? "null" : markerText)
.append(xOffset).append(yOffset)
.append(matchRotation)
.append(afterBurnerKey)
.append(description)
.append(gpId)
.append(placement);
return ID + se.getValue();
}
public Command myKeyEvent(KeyStroke stroke) {
myGetKeyCommands();
if (command.matches(stroke)) {
return placeMarker();
}
else {
return null;
}
}
protected Command placeMarker() {
final GamePiece marker = createMarker();
Command c = null;
if (marker != null) {
GamePiece outer = getOutermost(this);
Point p = getPosition();
p.translate(xOffset, -yOffset);
if (matchRotation) {
FreeRotator myRotation = (FreeRotator) Decorator.getDecorator(outer, FreeRotator.class);
FreeRotator markerRotation = (FreeRotator) Decorator.getDecorator(marker, FreeRotator.class);
if (myRotation != null && markerRotation != null) {
markerRotation.setAngle(myRotation.getAngle());
Point2D myPosition = getPosition().getLocation();
Point2D markerPosition = p.getLocation();
markerPosition = AffineTransform.getRotateInstance(myRotation.getAngleInRadians(), myPosition.getX(), myPosition.getY()).transform(markerPosition,
null);
p = new Point((int) markerPosition.getX(), (int) markerPosition.getY());
}
}
if (!Boolean.TRUE.equals(marker.getProperty(Properties.IGNORE_GRID))) {
p = getMap().snapTo(p);
}
if (getMap().getStackMetrics().isStackingEnabled()
&& !Boolean.TRUE.equals(marker.getProperty(Properties.NO_STACK))
&& !Boolean.TRUE.equals(outer.getProperty(Properties.NO_STACK))
&& getMap().getPieceCollection().canMerge(outer, marker)) {
final Stack parent = getParent();
GamePiece target = outer;
int index = -1;
switch (placement) {
case ABOVE:
target = outer;
break;
case BELOW:
index = parent == null ? 0 : parent.indexOf(outer);
break;
case STACK_BOTTOM:
index = 0;
break;
case STACK_TOP:
- target = parent;
+ target = parent == null ? outer : parent;
}
c = getMap().getStackMetrics().merge(target, marker);
if (index >= 0) {
final ChangeTracker ct = new ChangeTracker(parent);
parent.insert(marker,index);
c = c.append(ct.getChangeCommand());
}
}
else {
c = getMap().placeAt(marker, p);
}
if (afterBurnerKey != null) {
marker.setProperty(Properties.SNAPSHOT, PieceCloner.getInstance().clonePiece(marker));
c.append(marker.keyEvent(afterBurnerKey));
}
selectMarker(marker);
if (markerText != null && getMap() != null) {
if (!Boolean.TRUE.equals(outer.getProperty(Properties.OBSCURED_TO_OTHERS)) && !Boolean.TRUE.equals(outer.getProperty(Properties.OBSCURED_TO_ME))
&& !Boolean.TRUE.equals(outer.getProperty(Properties.INVISIBLE_TO_OTHERS))) {
String location = getMap().locationName(getPosition());
if (location != null) {
Command display = new Chatter.DisplayText(GameModule.getGameModule().getChatter(), " * " + location + ": " + outer.getName() + " " + markerText
+ " * ");
display.execute();
c = c == null ? display : c.append(display);
}
}
}
}
return c;
}
protected void selectMarker(GamePiece marker) {
if (marker.getProperty(Properties.SELECT_EVENT_FILTER) == null) {
if (marker.getParent() != null && marker.getParent().equals(getParent())) {
KeyBuffer.getBuffer().add(marker);
}
}
}
/**
* The marker, with prototypes fully expanded
*
* @return
*/
public GamePiece createMarker() {
GamePiece piece = createBaseMarker();
if (piece == null) {
piece = new BasicPiece();
newGpId = getGpId();
}
else {
piece = PieceCloner.getInstance().clonePiece(piece);
}
piece.setProperty(Properties.PIECE_ID, newGpId);
return piece;
}
/**
* The marker, with prototypes unexpanded
*
* @return
*/
public GamePiece createBaseMarker() {
if (markerSpec == null) {
return null;
}
GamePiece piece = null;
if (isMarkerStandalone()) {
final AddPiece comm =
(AddPiece) GameModule.getGameModule().decode(markerSpec);
piece = comm.getTarget();
piece.setState(comm.getState());
newGpId = getGpId();
}
else {
try {
final Configurable[] c =
ComponentPathBuilder.getInstance().getPath(markerSpec);
final Configurable conf = c[c.length-1];
if (conf instanceof PieceSlot) {
piece = ((PieceSlot) conf).getPiece();
newGpId = ((PieceSlot) conf).getGpId();
}
}
catch (ComponentPathBuilder.PathFormatException e) {
ErrorDialog.dataError(new BadDataReport(e.getMessage(),markerSpec,e));
}
}
return piece;
}
/**
* @return true if the marker is defined from scratch. Return false if the marker is defined as a component in the
* Game Piece Palette
*/
public boolean isMarkerStandalone() {
return markerSpec != null && markerSpec.startsWith(BasicCommandEncoder.ADD);
}
public void mySetState(String newState) {
}
public Shape getShape() {
return piece.getShape();
}
public String getDescription() {
String d = "Place Marker";
if (description.length() > 0) {
d += " - " + description;
}
return d;
}
public HelpFile getHelpFile() {
return HelpFile.getReferenceManualPage("Marker.htm");
}
public void mySetType(String type) {
SequenceEncoder.Decoder st = new SequenceEncoder.Decoder(type, ';');
st.nextToken();
String name = st.nextToken();
key = st.nextKeyStroke(null);
command = new KeyCommand(name, key, this, this);
if (name.length() > 0 && key != null) {
commands = new KeyCommand[]{command};
}
else {
commands = new KeyCommand[0];
}
markerSpec = st.nextToken();
if ("null".equals(markerSpec)) {
markerSpec = null;
}
markerText = st.nextToken("null");
if ("null".equals(markerText)) {
markerText = null;
}
xOffset = st.nextInt(0);
yOffset = st.nextInt(0);
matchRotation = st.nextBoolean(false);
afterBurnerKey = st.nextKeyStroke(null);
description = st.nextToken("");
setGpId(st.nextToken(""));
placement = st.nextInt(STACK_TOP);
}
public PieceEditor getEditor() {
return new Ed(this);
}
public PieceI18nData getI18nData() {
return getI18nData(command.getName(), getCommandDescription(description, "Place Marker command"));
}
public String getGpId() {
return gpId;
}
public void setGpId(String s) {
gpId = s;
}
public void updateGpId(GpIdSupport s) {
gpidSupport = s;
updateGpId();
}
public void updateGpId() {
setGpId(gpidSupport.generateGpId());
}
protected static class Ed implements PieceEditor {
private HotKeyConfigurer keyInput;
private StringConfigurer commandInput;
private PieceSlot pieceInput;
private JPanel p = new JPanel();
private String markerSlotPath;
protected JButton defineButton = new JButton("Define Marker");
protected JButton selectButton = new JButton("Select");
protected IntConfigurer xOffsetConfig = new IntConfigurer(null, "Horizontal offset: ");
protected IntConfigurer yOffsetConfig = new IntConfigurer(null, "Vertical offset: ");
protected BooleanConfigurer matchRotationConfig;
protected JComboBox placementConfig;
protected HotKeyConfigurer afterBurner;
protected StringConfigurer descConfig;
private String slotId;
protected Ed(PlaceMarker piece) {
matchRotationConfig = createMatchRotationConfig();
descConfig = new StringConfigurer(null, "Description: ", piece.description);
keyInput = new HotKeyConfigurer(null, "Keyboard Command: ", piece.key);
afterBurner = new HotKeyConfigurer(null, "Keystroke to apply after placement: ", piece.afterBurnerKey);
commandInput = new StringConfigurer(null, "Command: ", piece.command.getName());
GamePiece marker = piece.createBaseMarker();
pieceInput = new PieceSlot(marker);
pieceInput.setGpId(piece.getGpId());
markerSlotPath = piece.markerSpec;
p = new JPanel();
p.setLayout(new BoxLayout(p, BoxLayout.Y_AXIS));
p.add(descConfig.getControls());
p.add(commandInput.getControls());
p.add(keyInput.getControls());
Box b = Box.createHorizontalBox();
b.add(pieceInput.getComponent());
defineButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
markerSlotPath = null;
new ConfigurerWindow(pieceInput.getConfigurer()).setVisible(true);
}
});
b.add(defineButton);
selectButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
ChoosePieceDialog d = new ChoosePieceDialog((Frame) SwingUtilities.getAncestorOfClass(Frame.class, p), PieceSlot.class);
d.setVisible(true);
if (d.getTarget() instanceof PieceSlot) {
pieceInput.setPiece(((PieceSlot) d.getTarget()).getPiece());
}
if (d.getPath() != null) {
markerSlotPath = ComponentPathBuilder.getInstance().getId(d.getPath());
slotId = "";
}
else {
markerSlotPath = null;
}
}
});
b.add(selectButton);
p.add(b);
xOffsetConfig.setValue(new Integer(piece.xOffset));
p.add(xOffsetConfig.getControls());
yOffsetConfig.setValue(new Integer(piece.yOffset));
p.add(yOffsetConfig.getControls());
matchRotationConfig.setValue(Boolean.valueOf(piece.matchRotation));
p.add(matchRotationConfig.getControls());
placementConfig = new JComboBox(new String[]{"On top of stack","On bottom of stack","Above this piece","Below this piece"});
placementConfig.setSelectedIndex(piece.placement);
Box placementBox = Box.createHorizontalBox();
placementBox.add(new JLabel("Place marker: "));
placementBox.add(placementConfig);
p.add(placementBox);
p.add(afterBurner.getControls());
slotId = piece.getGpId();
}
protected BooleanConfigurer createMatchRotationConfig() {
return new BooleanConfigurer(null, "Match Rotation?");
}
public Component getControls() {
return p;
}
public String getState() {
return "";
}
public String getType() {
SequenceEncoder se = new SequenceEncoder(';');
se.append(commandInput.getValueString());
se.append((KeyStroke) keyInput.getValue());
if (pieceInput.getPiece() == null) {
se.append("null");
}
else if (markerSlotPath != null) {
se.append(markerSlotPath);
}
else {
String spec = GameModule.getGameModule().encode(new AddPiece(pieceInput.getPiece()));
se.append(spec);
}
se.append("null"); // Older versions specified a text message to echo. Now performed by the ReportState trait,
// but we remain backward-compatible.
se.append(xOffsetConfig.getValueString());
se.append(yOffsetConfig.getValueString());
se.append(matchRotationConfig.getValueString());
se.append((KeyStroke) afterBurner.getValue());
se.append(descConfig.getValueString());
se.append(slotId);
se.append(placementConfig.getSelectedIndex());
return ID + se.getValue();
}
public static class ChoosePieceDialog extends ChooseComponentPathDialog {
private static final long serialVersionUID = 1L;
public ChoosePieceDialog(Frame owner, Class<PieceSlot> targetClass) {
super(owner, targetClass);
}
protected boolean isValidTarget(Object selected) {
return super.isValidTarget(selected) || CardSlot.class.isInstance(selected);
}
}
}
}
| true | true | protected Command placeMarker() {
final GamePiece marker = createMarker();
Command c = null;
if (marker != null) {
GamePiece outer = getOutermost(this);
Point p = getPosition();
p.translate(xOffset, -yOffset);
if (matchRotation) {
FreeRotator myRotation = (FreeRotator) Decorator.getDecorator(outer, FreeRotator.class);
FreeRotator markerRotation = (FreeRotator) Decorator.getDecorator(marker, FreeRotator.class);
if (myRotation != null && markerRotation != null) {
markerRotation.setAngle(myRotation.getAngle());
Point2D myPosition = getPosition().getLocation();
Point2D markerPosition = p.getLocation();
markerPosition = AffineTransform.getRotateInstance(myRotation.getAngleInRadians(), myPosition.getX(), myPosition.getY()).transform(markerPosition,
null);
p = new Point((int) markerPosition.getX(), (int) markerPosition.getY());
}
}
if (!Boolean.TRUE.equals(marker.getProperty(Properties.IGNORE_GRID))) {
p = getMap().snapTo(p);
}
if (getMap().getStackMetrics().isStackingEnabled()
&& !Boolean.TRUE.equals(marker.getProperty(Properties.NO_STACK))
&& !Boolean.TRUE.equals(outer.getProperty(Properties.NO_STACK))
&& getMap().getPieceCollection().canMerge(outer, marker)) {
final Stack parent = getParent();
GamePiece target = outer;
int index = -1;
switch (placement) {
case ABOVE:
target = outer;
break;
case BELOW:
index = parent == null ? 0 : parent.indexOf(outer);
break;
case STACK_BOTTOM:
index = 0;
break;
case STACK_TOP:
target = parent;
}
c = getMap().getStackMetrics().merge(target, marker);
if (index >= 0) {
final ChangeTracker ct = new ChangeTracker(parent);
parent.insert(marker,index);
c = c.append(ct.getChangeCommand());
}
}
else {
c = getMap().placeAt(marker, p);
}
if (afterBurnerKey != null) {
marker.setProperty(Properties.SNAPSHOT, PieceCloner.getInstance().clonePiece(marker));
c.append(marker.keyEvent(afterBurnerKey));
}
selectMarker(marker);
if (markerText != null && getMap() != null) {
if (!Boolean.TRUE.equals(outer.getProperty(Properties.OBSCURED_TO_OTHERS)) && !Boolean.TRUE.equals(outer.getProperty(Properties.OBSCURED_TO_ME))
&& !Boolean.TRUE.equals(outer.getProperty(Properties.INVISIBLE_TO_OTHERS))) {
String location = getMap().locationName(getPosition());
if (location != null) {
Command display = new Chatter.DisplayText(GameModule.getGameModule().getChatter(), " * " + location + ": " + outer.getName() + " " + markerText
+ " * ");
display.execute();
c = c == null ? display : c.append(display);
}
}
}
}
return c;
}
| protected Command placeMarker() {
final GamePiece marker = createMarker();
Command c = null;
if (marker != null) {
GamePiece outer = getOutermost(this);
Point p = getPosition();
p.translate(xOffset, -yOffset);
if (matchRotation) {
FreeRotator myRotation = (FreeRotator) Decorator.getDecorator(outer, FreeRotator.class);
FreeRotator markerRotation = (FreeRotator) Decorator.getDecorator(marker, FreeRotator.class);
if (myRotation != null && markerRotation != null) {
markerRotation.setAngle(myRotation.getAngle());
Point2D myPosition = getPosition().getLocation();
Point2D markerPosition = p.getLocation();
markerPosition = AffineTransform.getRotateInstance(myRotation.getAngleInRadians(), myPosition.getX(), myPosition.getY()).transform(markerPosition,
null);
p = new Point((int) markerPosition.getX(), (int) markerPosition.getY());
}
}
if (!Boolean.TRUE.equals(marker.getProperty(Properties.IGNORE_GRID))) {
p = getMap().snapTo(p);
}
if (getMap().getStackMetrics().isStackingEnabled()
&& !Boolean.TRUE.equals(marker.getProperty(Properties.NO_STACK))
&& !Boolean.TRUE.equals(outer.getProperty(Properties.NO_STACK))
&& getMap().getPieceCollection().canMerge(outer, marker)) {
final Stack parent = getParent();
GamePiece target = outer;
int index = -1;
switch (placement) {
case ABOVE:
target = outer;
break;
case BELOW:
index = parent == null ? 0 : parent.indexOf(outer);
break;
case STACK_BOTTOM:
index = 0;
break;
case STACK_TOP:
target = parent == null ? outer : parent;
}
c = getMap().getStackMetrics().merge(target, marker);
if (index >= 0) {
final ChangeTracker ct = new ChangeTracker(parent);
parent.insert(marker,index);
c = c.append(ct.getChangeCommand());
}
}
else {
c = getMap().placeAt(marker, p);
}
if (afterBurnerKey != null) {
marker.setProperty(Properties.SNAPSHOT, PieceCloner.getInstance().clonePiece(marker));
c.append(marker.keyEvent(afterBurnerKey));
}
selectMarker(marker);
if (markerText != null && getMap() != null) {
if (!Boolean.TRUE.equals(outer.getProperty(Properties.OBSCURED_TO_OTHERS)) && !Boolean.TRUE.equals(outer.getProperty(Properties.OBSCURED_TO_ME))
&& !Boolean.TRUE.equals(outer.getProperty(Properties.INVISIBLE_TO_OTHERS))) {
String location = getMap().locationName(getPosition());
if (location != null) {
Command display = new Chatter.DisplayText(GameModule.getGameModule().getChatter(), " * " + location + ": " + outer.getName() + " " + markerText
+ " * ");
display.execute();
c = c == null ? display : c.append(display);
}
}
}
}
return c;
}
|
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.