AS3, Access of undefined property - actionscript-3

I want to use the Base64 class written by Subhero in AS3, so I created a ActionScript Project containing two files: StringCompress.as and Base64.as. The code is as following. (The code of Base64.as is a bit long, but I just want to show you the function it contains.) However, in StringCompress.as, these two lines
return Base64.Encode(textBytes);
and
var textBytes:ByteArray = Base64.Decode(value);
have the same error "Access of undefined property Base64".
I don't know why, can anyone help me? Many Thanks!!!
//code
StringCompress.as code
package
{
import flash.display.Sprite;
import flash.utils.ByteArray;
import flash.errors.IOError;
import flash.events.Event;
public class StringCompress extends Sprite
{
public function StringCompress()
{
}
public static function Compress(value:String):String
{
var textBytes:ByteArray = new ByteArray();
textBytes.writeUTFBytes(value);
textBytes.compress();
return Base64.Encode(textBytes);
}
public static function UnCompress(value:String):String
{
var textBytes:ByteArray = Base64.Decode(value);
try
{
textBytes.uncompress();
}
catch(e:IOError){
trace("The code to uncompress is not valid.");
}
return textBytes.toString();
}
}
}
Base64.as code
/*
* A Base64 encoder/decoder implementation in Actionscript 3
* This work is made available under http://creativecommons.org/licenses/by-nc-sa/2.0/de/deed.en
*
* #author subhero#gmail.com
* #version 0.5
*/
package formatter {
// import ->
import flash.utils.ByteArray;
import flash.errors.EOFError;
// <- import
// Base64 ->
/*
* A class used for transforming a ByteArray to a Base64-encoded string and vice versa.
* Since the "built-in" class (mx.utils.Base64Encoder) is not documented yet, this class can be
* used for Base64 encoding/decoding in the meantime.
* The class will be deprecated as soon as Macromedia/Adobe decides to fully release the
* "native" AS3 Base64 class (Flex2 full release respectively).
* Its implementation is based upon a HowTo {#link http://www.kbcafe.com/articles/HowTo.Base64.pdf},
* a Java implementation {#link http://ostermiller.org/utils/Base64.java.html} and an
* AS2-implementation by Jason Nussbaum {#link http://blog.jasonnussbaum.com/?p=108}
*
*/
public class Base64 {
// mx.utils.StringUtil
public static function isWhitespace(char:String):Boolean{
switch (char){
case " ":
case "\t":
case "\r":
case "\n":
case "\f":
return true;
default:
return false;
}
}
// the Base64 "alphabet"
private static var _b64Chars:Array=new Array(
'A','B','C','D','E','F','G','H',
'I','J','K','L','M','N','O','P',
'Q','R','S','T','U','V','W','X',
'Y','Z','a','b','c','d','e','f',
'g','h','i','j','k','l','m','n',
'o','p','q','r','s','t','u','v',
'w','x','y','z','0','1','2','3',
'4','5','6','7','8','9','+','/'
)
// the reverse-lookup object used for decoding
private static var _b64Lookup:Object=_buildB64Lookup();
// the boolean to insert linebreaks after 76 chars into the Base64 encoded string
private static var _linebreaks:Boolean;
/*
* The class method for encoding an array of bytes to a Base64 encoded string.
*
* #param bArr A ByteArray containing values to encode
* #param linebreaks A boolean to insert a linebreak after 76 Base64-chars
* #return The Base64 encoded string
*
*/
public static function Encode(bArr:ByteArray, linebreaks:Boolean=false):String
{
_linebreaks= linebreaks;
return _encodeBytes(bArr);
}
/*
* The class method for decoding a Base64 encoded string to an array of bytes.
*
* #param str A Base64 encoded string
* #return An array of bytes
*
*/
public static function Decode(str:String):ByteArray
{
return _decodeSring(str);
}
/*
* The private helper class method to build an object used for reverse B64 char lookup.
*
* #return An object with each B64 char as a property containing the corresponding value
*
*/
private static function _buildB64Lookup():Object
{
var obj:Object=new Object();
for (var i:Number=0; i < _b64Chars.length; i++)
{
obj[_b64Chars[i]]=i;
}
return obj;
}
/*
* The private helper class method to determine whether a given char is B64 compliant.
*
* #param char A character as string (length=1)
* #return A boolean indicating the given char *is* in the B64 alphabet
*
*/
private static function _isBase64(char:String):Boolean
{
return _b64Lookup[char] != undefined;
}
/*
* The private class method for encoding an array of bytes into a B64 encoded string.
*
* #param bs An array of bytes
* #return The B64 encoded string
*
* #see formatter.Base64.Encode()
*
*/
private static function _encodeBytes(bs:ByteArray):String
{
var b64EncStr:String = "";
var bufferSize:uint;
var col:uint=0;
bs.position=0;
while (bs.position < bs.length)
{
bufferSize= bs.bytesAvailable >= 3 ? 3 : bs.bytesAvailable;
var byteBuffer:ByteArray=new ByteArray();
bs.readBytes(byteBuffer, 0, bufferSize);
b64EncStr += _b64EncodeBuffer(byteBuffer);
col+=4;
if (_linebreaks && col%76 == 0) {
b64EncStr += "\n";
col=0;
}
}
return b64EncStr.toString();
}
/*
* The private class method for encoding a buffer of 3 bytes (24bit) to 4 B64-chars
* (representing 6bit each => 24bit).
*
* #param buffer An array of bytes (1 <= length <= 3)
* #return The byte buffer encoded to 4 B64 chars as string
*
* #see formatter.Base64._encodeBytes()
*
*/
private static function _b64EncodeBuffer(buffer:ByteArray):String
{
var bufferEncStr:String = "";
bufferEncStr += _b64Chars[buffer[0] >> 2];
switch (buffer.length)
{
case 1 :
bufferEncStr += _b64Chars[((buffer[0] << 4) & 0x30)];
bufferEncStr += "==";
break;
case 2 :
bufferEncStr += _b64Chars[(buffer[0] << 4) & 0x30 | buffer[1] >> 4];
bufferEncStr += _b64Chars[(buffer[1] << 2) & 0x3c];
bufferEncStr += "=";
break;
case 3 :
bufferEncStr += _b64Chars[(buffer[0] << 4) & 0x30 | buffer[1] >> 4];
bufferEncStr += _b64Chars[(buffer[1] << 2) & 0x3c | buffer[2] >> 6];
bufferEncStr += _b64Chars[buffer[2] & 0x3F];
break;
default : trace("Base64 byteBuffer outOfRange");
}
return bufferEncStr.toString();
}
/*
* The private class method for decoding a string containing B64 chars to an array of bytes
*
* #param s The B64 encoded string
* #return A decoded array of bytes
*
* #see formatter.Base64.Decode()
*
*/
private static function _decodeSring(s:String):ByteArray
{
var b64EncString:String="" + s;
var b64DecBytes:ByteArray=new ByteArray();
var stringBuffer:String="";
var lgth:uint=b64EncString.length;
for (var i:uint=0; i < lgth; i++)
{
var char:String=b64EncString.charAt(i);
if (!isWhitespace(char) && (_isBase64(char) || char == "=")) {
stringBuffer += char;
if (stringBuffer.length == 4) {
b64DecBytes.writeBytes( _b64DecodeBuffer(stringBuffer) );
stringBuffer="";
}
}
}
b64DecBytes.position=0;
return b64DecBytes;
}
/*
* The private class method for decoding a string buffer of 4 B64 chars
* (each representing 6bit) to an array of 3 bytes.
*
* #param buffer A string containing B64 chars (length = 4)
* #return An array of bytes containing the decoded values
*
* #see formatter.Base64._decodeBytes()
*
*/
private static function _b64DecodeBuffer(buffer:String):ByteArray
{
var bufferEncBytes:ByteArray=new ByteArray();
var charValue1:uint=_b64Lookup[buffer.charAt(0)];
var charValue2:uint=_b64Lookup[buffer.charAt(1)];
var charValue3:uint=_b64Lookup[buffer.charAt(2)];
var charValue4:uint=_b64Lookup[buffer.charAt(3)];
bufferEncBytes.writeByte(charValue1 << 2 | charValue2 >> 4);
if (buffer.charAt(2) != "=") bufferEncBytes.writeByte(charValue2 << 4 | charValue3 >> 2);
if (buffer.charAt(3) != "=") bufferEncBytes.writeByte(charValue3 << 6 | charValue4);
return bufferEncBytes;
}
}
// <- Base64
}

You just didn't import base64 to class where you are using it. Add proper import line.
Edit: Put Base64.as into folder formatter, then "import formatter.Base64;" it will work, alternatively - in Base64.as, in first line "package formatter {" delete word "formatter" and then add "import Base64;" in StringCompress.as.

Related

how to write GameObject position in the Scene to json file?

on Clicking the button, I m loading the function WriteJsonForLevel(). I have placed three GameObject with the tag name "RedCoin" and I want to write the position of the GameObject to a JSON file. I can get the position of the object, but it's all overwritten. I can only see the last GameObject position (i.e the completion of the loop)
public List<GameObject> levelObjects;
public string level;
public Vector3 pos;
// Start is called before the first frame update
void Start()
{
levelObjects = new List<GameObject>();
}
// Update is called once per frame
void Update()
{
}
public void WritejsonForAll()
{
WriteJsonForLevel();
}
public void WriteJsonForLevel()
{
/* FileStream fs = new FileStream(Application.dataPath + "/sample.json",FileMode.Create);
StreamWriter writer= new StreamWriter(fs);*/
GameObject[] coinObjRed = GameObject.FindGameObjectsWithTag("RedCoin");
putAllObjectInList(coinObjRed);
}
public void putAllObjectInList(GameObject[] p)
{
string path = Application.dataPath + "/text.json";
foreach (GameObject q in p)
{
levelObjects.Add(q);
}
for (int i = 0; i < levelObjects.Count; i++)
{
GameObject lvlObj = levelObjects[i];
Vector3 pos = lvlObj.transform.position;
string posOutput = JsonUtility.ToJson(pos);
File.WriteAllText(path,posOutput);
Debug.Log("position:" + posOutput);
}
}
}
You are using WriteAllText which will overwrite the file every time it is called. As it is overwriting each time it is in the loop, it will only write the last object to the file as every other previous write is overwritten. I would consider making a serialized class of data, assigning the data to it, converting it to a JSON string then saving that.
// stores individual locations for saving
[System.Serializable]
public class IndividualLocation
{
public IndividualLocation(Vector3 pos)
{
xPos = pos.x;
yPos = pos.y;
zPos = pos.z;
}
public float xPos;
public float yPos;
public float zPos;
}
// stores all game locations for saving
[System.Serializable]
public class AllGameLocations
{
public List<IndividualLocation> Locations = new List<IndividualLocation>();
}
public void PutAllObjectInList(in GameObject[] p)
{
string path = Application.dataPath + "/text.json";
// create a new object to write to
AllGameLocations data = new AllGameLocations();
// iterate the objects adding each to our structure
foreach(GameObject obj in p)
{
data.Locations.Add(new IndividualLocation(obj.transform.position));
}
// now that the data is filled, write out to the file
File.WriteAllText(path, JsonUtility.ToJson(AllGameLocations));
}
If you need a snippet on how to load the data properly I can add one.
Edit: Here is a load snippet
public void LoadJSONObject()
{
string path = Application.dataPath + "/text.json";
// if the file path or name does not exist
if (!Directory.Exists(Path.GetDirectoryName(path)))
{
Debug.LogWarning("File or path does not exist! " + path);
return
}
// load in the save data as byte array
byte[] jsonDataAsBytes = null;
try
{
jsonDataAsBytes = File.ReadAllBytes(path);
Debug.Log("<color=green>Loaded all data from: </color>" + path);
}
catch (Exception e)
{
Debug.LogWarning("Failed to load data from: " + path);
Debug.LogWarning("Error: " + e.Message);
return;
}
if (jsonDataAsBytes == null)
return;
// convert the byte array to json
string jsonData;
// convert the byte array to json
jsonData = Encoding.ASCII.GetString(jsonDataAsBytes);
// convert to the specified object type
AllGameLocations returnedData;
JsonUtility.FromJsonOverwrite<AllGameLocations>(jsonData, AllGameLocations);
// use returnedData as a normal object now
float firstObjectX = returnedData.Locations[0].xPos;
}
}
Let me know if the Load works, just typed it up untested. Added some error handling as well to assure data exists and the load properly works.

Handling checked exceptions for eclipse plugin

I am working on an Eclipse plugin and am faced with checked exceptions thrown from the API that I am using in my plugin. What is the practice around handling such exceptions in the context of a plugin? I could not find an appropriate Exception subclass from the Plugin development API.
Thanks in advance.
I use logging classes that I found in a book titled "Eclipse Plug-ins", by Eric Clayberg and Dan Rubel.
Here's the main logging class.
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Plugin;
import org.eclipse.core.runtime.Status;
public class EclipseLogging {
public static void logInfo(Plugin plugin, String pluginID, String message,
boolean display) {
log(plugin, pluginID, IStatus.INFO, IStatus.OK, message, null, display);
}
public static void logInfo(Plugin plugin, String pluginID,
Throwable exception) {
log(plugin, createStatus(pluginID, IStatus.ERROR, IStatus.OK,
"Unexpected Exception", exception));
}
public static void logInfo(Plugin plugin, String pluginID, String message,
Throwable exception) {
log(plugin, createStatus(pluginID, IStatus.ERROR, IStatus.OK, message,
exception));
}
public static void logError(Plugin plugin, String pluginID,
Throwable exception) {
logError(plugin, pluginID, "Unexpected Exception", exception);
}
public static void logError(Plugin plugin, String pluginID, String message,
Throwable exception) {
log(plugin, pluginID, IStatus.ERROR, IStatus.OK, message, exception,
true);
}
public static void log(Plugin plugin, String pluginID, int severity,
int code, String message, Throwable exception, boolean display) {
if (display) {
ExceptionAction action = new ExceptionAction(plugin, message,
exception);
action.run();
}
log(plugin, createStatus(pluginID, severity, code, message, exception));
}
public static IStatus createStatus(String pluginID, int severity, int code,
String message, Throwable exception) {
return new Status(severity, pluginID, code, message, exception);
}
public static void log(Plugin plugin, IStatus status) {
plugin.getLog().log(status);
}
}
And here's the exception action class.
import org.eclipse.core.runtime.Plugin;
import org.eclipse.jface.action.Action;
import org.eclipse.swt.SWTException;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.PlatformUI;
public class ExceptionAction extends Action {
private Plugin plugin;
private String message;
private Throwable exception;
public ExceptionAction(Plugin plugin, String message, Throwable exception) {
this.plugin = plugin;
this.message = message;
this.exception = exception;
}
public void run() {
IWorkbench workbench = PlatformUI.getWorkbench();
IWorkbenchWindow window = workbench.getActiveWorkbenchWindow();
if (window != null) {
Shell parentShell = window.getShell();
parentShell.forceActive();
try {
ExceptionDetailsDialog dialog = new ExceptionDetailsDialog(
parentShell, null, null, message, exception, plugin);
dialog.open();
} catch (SWTException e) {
}
}
}
}
And finally, the classes to display the exception.
import org.eclipse.jface.dialogs.Dialog;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.jface.window.IShellProvider;
import org.eclipse.jface.window.SameShellProvider;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;
/**
* An abstract dialog with a details section that can be shown or hidden by the
* user. Subclasses are responsible for providing the content of the details
* section.
*/
public abstract class AbstractDetailsDialog extends Dialog {
private final String title;
private final String message;
private final Image image;
private Button detailsButton;
private Control detailsArea;
private Point cachedWindowSize;
/**
* Construct a new instance with the specified elements. Note that the
* window will have no visual representation (no widgets) until it is told
* to open. By default, <code>open</code> blocks for dialogs.
*
* #param parentShell
* the parent shell, or <code>null</code> to create a top-level
* shell
* #param title
* the title for the dialog or <code>null</code> for none
* #param image
* the image to be displayed
* #param message
* the message to be displayed
*/
public AbstractDetailsDialog(Shell parentShell, String title, Image image,
String message) {
this(new SameShellProvider(parentShell), title, image, message);
}
/**
* Construct a new instance with the specified elements. Note that the
* window will have no visual representation (no widgets) until it is told
* to open. By default, <code>open</code> blocks for dialogs.
*
* #param parentShell
* the parent shell provider (not <code>null</code>)
* #param title
* the title for the dialog or <code>null</code> for none
* #param image
* the image to be displayed
* #param message
* the message to be displayed
*/
public AbstractDetailsDialog(IShellProvider parentShell, String title,
Image image, String message) {
super(parentShell);
this.title = title;
this.image = image;
this.message = message;
setShellStyle(SWT.DIALOG_TRIM | SWT.RESIZE | SWT.APPLICATION_MODAL);
}
/**
* Configures the given shell in preparation for opening this window in it.
* In our case, we set the title if one was provided.
*/
protected void configureShell(Shell shell) {
super.configureShell(shell);
if (title != null)
shell.setText(title);
}
/**
* Creates and returns the contents of the upper part of this dialog (above
* the button bar). This includes an image, if specified, and a message.
*
* #param parent
* the parent composite to contain the dialog area
* #return the dialog area control
*/
protected Control createDialogArea(Composite parent) {
Composite composite = (Composite) super.createDialogArea(parent);
composite.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
if (image != null) {
((GridLayout) composite.getLayout()).numColumns = 2;
Label label = new Label(composite, 0);
image.setBackground(label.getBackground());
label.setImage(image);
label.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_CENTER
| GridData.VERTICAL_ALIGN_BEGINNING));
}
Label label = new Label(composite, SWT.WRAP);
if (message != null)
label.setText(message);
GridData data = new GridData(GridData.FILL_HORIZONTAL
| GridData.VERTICAL_ALIGN_CENTER);
data.widthHint = convertHorizontalDLUsToPixels(IDialogConstants.MINIMUM_MESSAGE_AREA_WIDTH);
label.setLayoutData(data);
label.setFont(parent.getFont());
return composite;
}
/**
* Adds OK and Details buttons to this dialog's button bar.
*
* #param parent
* the button bar composite
*/
protected void createButtonsForButtonBar(Composite parent) {
createButton(parent, IDialogConstants.OK_ID, IDialogConstants.OK_LABEL,
false);
detailsButton = createButton(parent, IDialogConstants.DETAILS_ID,
IDialogConstants.SHOW_DETAILS_LABEL, false);
}
/**
* The buttonPressed() method is called when either the OK or Details
* buttons is pressed. We override this method to alternately show or hide
* the details area if the Details button is pressed.
*/
protected void buttonPressed(int id) {
if (id == IDialogConstants.DETAILS_ID)
toggleDetailsArea();
else
super.buttonPressed(id);
}
/**
* Toggles the unfolding of the details area. This is triggered by the user
* pressing the Details button.
*/
protected void toggleDetailsArea() {
Point oldWindowSize = getShell().getSize();
Point newWindowSize = cachedWindowSize;
cachedWindowSize = oldWindowSize;
// Show the details area.
if (detailsArea == null) {
detailsArea = createDetailsArea((Composite) getContents());
detailsButton.setText(IDialogConstants.HIDE_DETAILS_LABEL);
}
// Hide the details area.
else {
detailsArea.dispose();
detailsArea = null;
detailsButton.setText(IDialogConstants.SHOW_DETAILS_LABEL);
}
/*
* Must be sure to call getContents().computeSize(SWT.DEFAULT,
* SWT.DEFAULT) before calling getShell().setSize(newWindowSize) since
* controls have been added or removed.
*/
// Compute the new window size.
Point oldSize = getContents().getSize();
Point newSize = getContents().computeSize(SWT.DEFAULT, SWT.DEFAULT);
if (newWindowSize == null)
newWindowSize = new Point(oldWindowSize.x, oldWindowSize.y
+ (newSize.y - oldSize.y));
// Crop new window size to screen.
Point windowLoc = getShell().getLocation();
Rectangle screenArea = getContents().getDisplay().getClientArea();
final int pos = screenArea.height - (windowLoc.y - screenArea.y);
if (newWindowSize.y > pos)
newWindowSize.y = pos;
getShell().setSize(newWindowSize);
((Composite) getContents()).layout();
}
/**
* subclasses must implement createDetailsArea to provide content for the
* area of the dialog made visible when the Details button is clicked.
*
* #param parent
* the details area parent
* #return the details area
*/
protected abstract Control createDetailsArea(Composite parent);
}
import java.io.PrintWriter;
import java.io.StringWriter;
import java.lang.reflect.InvocationTargetException;
import java.text.MessageFormat;
import java.util.Dictionary;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Plugin;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.jface.window.IShellProvider;
import org.eclipse.jface.window.SameShellProvider;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;
/**
* A dialog to display one or more errors to the user, as contained in an
* <code>IStatus</code> object along with the plug-in identifier, name, version
* and provider. If an error contains additional detailed information then a
* Details button is automatically supplied, which shows or hides an error
* details viewer when pressed by the user.
*
* #see org.eclipse.core.runtime.IStatus
*/
public class ExceptionDetailsDialog extends AbstractDetailsDialog {
/**
* The details to be shown ({#link Exception}, {#link IStatus}, or
* <code>null</code> if no details).
*/
private final Object details;
/**
* The plugin triggering this details dialog and whose information is to be
* shown in the details area or <code>null</code> if no plugin details
* should be shown.
*/
private final Plugin plugin;
/**
* Construct a new instance with the specified elements. Note that the
* window will have no visual representation (no widgets) until it is told
* to open. By default, <code>open</code> blocks for dialogs.
*
* #param parentShell
* the parent shell, or <code>null</code> to create a top-level
* shell
* #param title
* the title for the dialog or <code>null</code> for none
* #param image
* the image to be displayed
* #param message
* the message to be displayed
* #param details
* an object whose content is to be displayed in the details
* area, or <code>null</code> for none
* #param plugin
* The plugin triggering this deatils dialog and whose
* information is to be shown in the details area or
* <code>null</code> if no plugin details should be shown.
*/
public ExceptionDetailsDialog(Shell parentShell, String title, Image image,
String message, Object details, Plugin plugin) {
this(new SameShellProvider(parentShell), title, image, message,
details, plugin);
}
/**
* Construct a new instance with the specified elements. Note that the
* window will have no visual representation (no widgets) until it is told
* to open. By default, <code>open</code> blocks for dialogs.
*
* #param parentShell
* the parent shell provider (not <code>null</code>)
* #param title
* the title for the dialog or <code>null</code> for none
* #param image
* the image to be displayed
* #param message
* the message to be displayed
* #param details
* an object whose content is to be displayed in the details
* area, or <code>null</code> for none
* #param plugin
* The plugin triggering this deatils dialog and whose
* information is to be shown in the details area or
* <code>null</code> if no plugin details should be shown.
*/
public ExceptionDetailsDialog(IShellProvider parentShell, String title,
Image image, String message, Object details, Plugin plugin) {
super(parentShell, getTitle(title, details), getImage(image, details),
getMessage(message, details));
this.details = details;
this.plugin = plugin;
}
/**
* Build content for the area of the dialog made visible when the Details
* button is clicked.
*
* #param parent
* the details area parent
* #return the details area
*/
protected Control createDetailsArea(Composite parent) {
// Create the details area.
Composite panel = new Composite(parent, SWT.NONE);
panel.setLayoutData(new GridData(GridData.FILL_BOTH));
GridLayout layout = new GridLayout();
layout.marginHeight = 0;
layout.marginWidth = 0;
panel.setLayout(layout);
// Create the details content.
createProductInfoArea(panel);
createDetailsViewer(panel);
return panel;
}
/**
* Create fields displaying the plugin information such as name, identifer,
* version and vendor. Do nothing if the plugin is not specified.
*
* #param parent
* the details area in which the fields are created
* #return the product info composite or <code>null</code> if no plugin
* specified.
*/
protected Composite createProductInfoArea(Composite parent) {
// If no plugin specified, then nothing to display here
if (plugin == null)
return null;
Composite composite = new Composite(parent, SWT.NULL);
composite.setLayoutData(new GridData());
GridLayout layout = new GridLayout();
layout.numColumns = 2;
layout.marginWidth = convertHorizontalDLUsToPixels(IDialogConstants.HORIZONTAL_MARGIN);
composite.setLayout(layout);
Dictionary<?, ?> bundleHeaders = plugin.getBundle().getHeaders();
String pluginId = plugin.getBundle().getSymbolicName();
String pluginVendor = (String) bundleHeaders.get("Bundle-Vendor");
String pluginName = (String) bundleHeaders.get("Bundle-Name");
String pluginVersion = (String) bundleHeaders.get("Bundle-Version");
new Label(composite, SWT.NONE).setText("Provider:");
new Label(composite, SWT.NONE).setText(pluginVendor);
new Label(composite, SWT.NONE).setText("Plug-in Name:");
new Label(composite, SWT.NONE).setText(pluginName);
new Label(composite, SWT.NONE).setText("Plug-in ID:");
new Label(composite, SWT.NONE).setText(pluginId);
new Label(composite, SWT.NONE).setText("Version:");
new Label(composite, SWT.NONE).setText(pluginVersion);
return composite;
}
/**
* Create the details field based upon the details object. Do nothing if the
* details object is not specified.
*
* #param parent
* the details area in which the fields are created
* #return the details field
*/
protected Control createDetailsViewer(Composite parent) {
if (details == null)
return null;
Text text = new Text(parent, SWT.MULTI | SWT.READ_ONLY | SWT.BORDER
| SWT.H_SCROLL | SWT.V_SCROLL);
text.setLayoutData(new GridData(GridData.FILL_BOTH));
// Create the content.
StringWriter writer = new StringWriter(1000);
if (details instanceof Throwable)
appendException(new PrintWriter(writer), (Throwable) details);
else if (details instanceof IStatus)
appendStatus(new PrintWriter(writer), (IStatus) details, 0);
text.setText(writer.toString());
return text;
}
// /////////////////////////////////////////////////////////////////
//
// Utility methods for building content
//
// /////////////////////////////////////////////////////////////////
/**
* Answer the title based on the provided title and details object.
*/
public static String getTitle(String title, Object details) {
if (title != null)
return title;
if (details instanceof Throwable) {
Throwable e = (Throwable) details;
while (e instanceof InvocationTargetException)
e = ((InvocationTargetException) e).getTargetException();
String name = e.getClass().getName();
return name.substring(name.lastIndexOf('.') + 1);
}
return "Exception";
}
/**
* Answer the image based on the provided image and details object.
*/
public static Image getImage(Image image, Object details) {
if (image != null)
return image;
Display display = Display.getCurrent();
if (details instanceof IStatus) {
switch (((IStatus) details).getSeverity()) {
case IStatus.ERROR:
return display.getSystemImage(SWT.ICON_ERROR);
case IStatus.WARNING:
return display.getSystemImage(SWT.ICON_WARNING);
case IStatus.INFO:
return display.getSystemImage(SWT.ICON_INFORMATION);
case IStatus.OK:
return null;
}
}
return display.getSystemImage(SWT.ICON_ERROR);
}
/**
* Answer the message based on the provided message and details object.
*/
public static String getMessage(String message, Object details) {
if (details instanceof Throwable) {
Throwable e = (Throwable) details;
while (e instanceof InvocationTargetException)
e = ((InvocationTargetException) e).getTargetException();
if (message == null)
return e.toString();
return MessageFormat.format(message, new Object[] { e.toString() });
}
if (details instanceof IStatus) {
String statusMessage = ((IStatus) details).getMessage();
if (message == null)
return statusMessage;
return MessageFormat
.format(message, new Object[] { statusMessage });
}
if (message != null)
return message;
return "An Exception occurred.";
}
public static void appendException(PrintWriter writer, Throwable ex) {
if (ex instanceof CoreException) {
appendStatus(writer, ((CoreException) ex).getStatus(), 0);
writer.println();
}
appendStackTrace(writer, ex);
if (ex instanceof InvocationTargetException)
appendException(writer, ((InvocationTargetException) ex)
.getTargetException());
}
public static void appendStatus(PrintWriter writer, IStatus status,
int nesting) {
for (int i = 0; i < nesting; i++)
writer.print(" ");
writer.println(status.getMessage());
IStatus[] children = status.getChildren();
for (int i = 0; i < children.length; i++)
appendStatus(writer, children[i], nesting + 1);
}
public static void appendStackTrace(PrintWriter writer, Throwable ex) {
ex.printStackTrace(writer);
}
}

How send a html file direclty to the printer in java

I'm using this to send a htlm file direclty to printer and it says invalid flavour which means that the printer does not support the formats. Any one have an idea to do this..
/**
* #param args
*/
public static void main(String[] args) {
// Input the file
FileInputStream textStream = null;
try {
textStream = new FileInputStream("./some.html");
} catch (FileNotFoundException ffne) {
}
if (textStream == null) {
return;
}
// Set the document type
DocFlavor myFormat = DocFlavor.INPUT_STREAM.TEXT_HTML_HOST;
// Create a Doc
Doc myDoc = new SimpleDoc(textStream, myFormat , null);
// Build a set of attributes
PrintRequestAttributeSet aset = new HashPrintRequestAttributeSet();
aset.add(new Copies(1));
//aset.add(MediaSize.NA.LEGAL);
aset.add(Sides.ONE_SIDED);
// discover the printers that can print the format according to the
// instructions in the attribute set
PrintService services = PrintServiceLookup.lookupDefaultPrintService();
//PrintServiceLookup.lookupPrintServices(myFormat, aset);
// Create a print job from one of the print services
//System.out.println("====5======="+service.get);
//if (services.length > 0) {
for (int i = 0; i < services.getSupportedDocFlavors().length; i++) {
System.out.println("====getSupportedDocFlavors======="+services.getSupportedDocFlavors()[i]);
}
DocPrintJob job = services.createPrintJob();
try {
job.print(myDoc, aset);
} catch (PrintException pe) {
System.out.println("====PrintException======="+pe);
}
//}
}
It says
sun.print.PrintJobFlavorException: invalid flavor
You are trying to force printer to handle (render) HTML document onto the paper. It will never work that way. And ofcourse the flavor you are sending is not supported.
First of all you need to render HTML into some graphical representation and then send it to printer. There are no good cross-platform tools for Java that could render modern HTML pages. But there is one in JavaFX and i guess you could use it to handle the task.
About printing the final image you can read here:
http://www.apl.jhu.edu/~hall/java/Swing-Tutorial/Swing-Tutorial-Printing.html
or see the code here:
http://www.java2s.com/Code/Java/2D-Graphics-GUI/PrintanImagetoprintdirectly.htm
or just find any other resource - there are a lot about printing.
public class POSPrinter {
private static final Log LOG = LogFactory.getLog(POSPrinter.class);
public POSPrinter(Long billID, String printMode) {
}
/**
*
* This method prints the specified PDF to specified printer under specified
*
* job name
*
*
*
* #param filePath
* Path of PDF file
*
* #param printerName
* Printer name
*
* #param jobName
* Print job name
*
* #throws IOException
*
* #throws PrinterException
*/
public void printPDF(String filePath, String printerName, String jobName,
Integer height, Integer width) throws IOException, PrinterException {
FileInputStream fileInputStream = new FileInputStream(filePath);
byte[] pdfContent = new byte[fileInputStream.available()];
fileInputStream.read(pdfContent, 0, fileInputStream.available());
ByteBuffer buffer = ByteBuffer.wrap(pdfContent);
final PDFFile pdfFile = new PDFFile(buffer);
Printable printable = new Printable() {
public int print(Graphics graphics, PageFormat pageFormat,
int pageIndex) throws PrinterException {
int pagenum = pageIndex + 1;
if ((pagenum >= 1) && (pagenum <= pdfFile.getNumPages())) {
Graphics2D graphics2D = (Graphics2D) graphics;
PDFPage page = pdfFile.getPage(pagenum);
Rectangle imageArea = new Rectangle(
(int) pageFormat.getImageableX(),
(int) pageFormat.getImageableY(),
(int) pageFormat.getImageableWidth(),
(int) pageFormat.getImageableHeight());
graphics2D.translate(0, 0);
PDFRenderer pdfRenderer = new PDFRenderer(page, graphics2D,
imageArea, null, null);
try {
page.waitForFinish();
pdfRenderer.run();
} catch (InterruptedException exception) {
exception.printStackTrace();
}
return PAGE_EXISTS;
} else {
return NO_SUCH_PAGE;
}
}
};
PrinterJob printJob = PrinterJob.getPrinterJob();
PageFormat pageFormat = PrinterJob.getPrinterJob().defaultPage();
printJob.setJobName(jobName);
Book book = new Book();
book.append(printable, pageFormat, pdfFile.getNumPages());
printJob.setPageable(book);
Paper paper = new Paper();
paper.setSize(width, height);
paper.setImageableArea(0, 0, paper.getWidth(), paper.getHeight());
// pageFormat
pageFormat.setPaper(paper);
// PrintService[] printServices = PrinterJob.lookupPrintServices();
//
// for (int count = 0; count < printServices.length; ++count) {
//
// if (printerName.equalsIgnoreCase(printServices[count].getName())) {
//
// printJob.setPrintService(printServices[count]);
//
// break;
//
// }
//
// }
PrintService printService = PrintServiceLookup
.lookupDefaultPrintService();
printJob.setPrintService(printService);
printJob.print();
}

java: Zip Exception when creating new zip

What does this exception mean when creating a new zip file?
java.util.zip.ZipException: too short to be Zip
java.util.zipException: too short to be zip means your Zip is invalid. Please check you are creating valid zip.
You can find Example
I have verified and below code is working.
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipException;
import java.util.zip.ZipOutputStream;
public class CreateZipFileDirectory {
public static void main(String args[])
{
try
{
String zipFile = "Path where zip needs to be creaetd e.g.zipdemo.zip";
String sourceDirectory = "directory which contains files.";
//create byte buffer
byte[] buffer = new byte[1024];
/*
* To create a zip file, use
*
* ZipOutputStream(OutputStream out)
* constructor of ZipOutputStream class.
*
*/
//create object of FileOutputStream
FileOutputStream fout = new FileOutputStream(zipFile);
//create object of ZipOutputStream from FileOutputStream
ZipOutputStream zout = new ZipOutputStream(fout);
//create File object from directory name
File dir = new File(sourceDirectory);
//check to see if this directory exists
if(!dir.isDirectory())
{
System.out.println(sourceDirectory + " is not a directory");
}
else
{
File[] files = dir.listFiles();
for(int i=0; i < files.length ; i++)
{
System.out.println("Adding " + files[i].getName());
//create object of FileInputStream for source file
FileInputStream fin = new FileInputStream(files[i]);
/*
* To begin writing ZipEntry in the zip file, use
*
* void putNextEntry(ZipEntry entry)
* method of ZipOutputStream class.
*
* This method begins writing a new Zip entry to
* the zip file and positions the stream to the start
* of the entry data.
*/
zout.putNextEntry(new ZipEntry(files[i].getName()));
/*
* After creating entry in the zip file, actually
* write the file.
*/
int length;
while((length = fin.read(buffer)) > 0)
{
zout.write(buffer, 0, length);
}
/*
* After writing the file to ZipOutputStream, use
*
* void closeEntry() method of ZipOutputStream class to
* close the current entry and position the stream to
* write the next entry.
*/
zout.closeEntry();
//close the InputStream
fin.close();
}
}
//close the ZipOutputStream
zout.close();
System.out.println("Zip file has been created!");
}
catch(IOException ioe)
{
System.out.println("IOException :" + ioe);
}
}
}
/*
Output of this program would be
Adding nonav.log
Adding ospreg.exe
Adding servers.ini
Adding setupisam.log
Adding sourceFile1.doc
Adding sourceFile2.doc
Zip file has been created!
*/
Take a look at the readCentralDir() methode, you will have to take a deeper look into the code, but in general it seems this exception is thrown once the file is too short to be a ZIP File.
Folowing code lines (mRaf is Random Access File):
long scanOffset = mRaf.length() - ENDHDR;
if (scanOffset < 0) {
throw new ZipException("too short to be Zip");
}

ConcurrentmodificationException thrown by java code

I am trying to append a sublist of a list to another. Its throwing me the Concurrent Modification exception in the while loop where I am calling the addAll() to append the perm list elements to outvec. I need to reduce the size of the p list in perm object while and then append a specific fraction of it to outvec. So, this keeps repeatin guntil the number of elements in the list p of perm object is <= 1.This is what my code looks like:
import java.util.Collections;
import java.util.List;
public class Generate {
//function to generate the output vector
ListGenerator gen(ListGenerator perm, double frac, int n) {
ListGenerator outvec = new ListGenerator();
for(int i = 0; i < n; i++)
perm.p.add(i, i+1);
outvec.p = perm.p;
//System.out.println("p in gen function: " + p);
randomPerm(perm);
int x = perm.p.size();
while( x > 1)
{
perm.p = firstFP(frac, perm);
System.out.println("perm.p after firstFP call " + perm.p);
outvec.p.addAll(perm.p);
System.out.println("size of outvec: " + outvec.p.size());
x = perm.p.size();
}
return outvec;
}
//function to generate random permutation of numbers
private void randomPerm(ListGenerator perm) {
Collections.shuffle(perm.p);
//System.out.println("perm in randomPerm function: " + p);
}
//function to return first f*|p| number of elements from p
List<Integer> firstFP(double f, ListGenerator perm) {
int new_size = (int) (f * perm.p.size());
return( perm.p.subList(0, new_size));
}
public static void main(String args[]) {
Generate g = new Generate();
ListGenerator p = new ListGenerator();
ListGenerator outvec = new ListGenerator();
double frac = 0.3;
int N = 70000;
outvec = g.gen(p, frac, N);
System.out.println("outvec: " + outvec.p);
System.out.println("size of outvec: " + outvec.p.size());
}
}
import java.util.ArrayList;
import java.util.List;
public class ListGenerator {
List<Integer> p = new ArrayList<Integer>();
}
The problem is its throwing me a ConcurrentModificationException at outvec.p.addAll(temp); this statement. This is what I am getting:
Exception in thread "main" java.util.ConcurrentModificationException
at java.util.ArrayList$SubList.checkForComodification(Unknown Source)
at java.util.ArrayList$SubList.size(Unknown Source)
at Generate.gen(Generate.java:17)
at Generate.main(Generate.java:49)
Any guidance will be highly appreciated.
Your code does not compile and the error is not in this part of the code.
Concurrent exception happens usually happens when you iterates over a list or another structure and you delete or add some elements at the same time in the same list.