<commit_before>/*
 * $Header$
 *
 * Copyright (c) OSGi Alliance (2004, 2005). All Rights Reserved.
 * 
 * Implementation of certain elements of the OSGi Specification may be subject
 * to third party intellectual property rights, including without limitation,
 * patent rights (such a third party may or may not be a member of the OSGi
 * Alliance). The OSGi Alliance is not responsible and shall not be held
 * responsible in any manner for identifying or failing to identify any or all
 * such third party intellectual property rights.
 * 
 * This document and the information contained herein are provided on an "AS IS"
 * basis and THE OSGI ALLIANCE DISCLAIMS ALL WARRANTIES, EXPRESS OR IMPLIED,
 * INCLUDING BUT NOT LIMITED TO ANY WARRANTY THAT THE USE OF THE INFORMATION
 * HEREIN WILL NOT INFRINGE ANY RIGHTS AND ANY IMPLIED WARRANTIES OF
 * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT WILL THE
 * OSGI ALLIANCE BE LIABLE FOR ANY LOSS OF PROFITS, LOSS OF BUSINESS, LOSS OF
 * USE OF DATA, INTERRUPTION OF BUSINESS, OR FOR DIRECT, INDIRECT, SPECIAL OR
 * EXEMPLARY, INCIDENTIAL, PUNITIVE OR CONSEQUENTIAL DAMAGES OF ANY KIND IN
 * CONNECTION WITH THIS DOCUMENT OR THE INFORMATION CONTAINED HEREIN, EVEN IF
 * ADVISED OF THE POSSIBILITY OF SUCH LOSS OR DAMAGE.
 * 
 * All Company, brand and product names may be trademarks that are the sole
 * property of their respective owners. All rights reserved.
 */
package org.osgi.impl.service.megcontainer;

import java.util.*;
import java.io.*;
import java.lang.reflect.Method;
import java.security.*;
import org.osgi.framework.*;
import org.osgi.meglet.*;
import org.osgi.service.application.*;


/**
 * This service represents a Meglet instance. It is a specialization of the
 * application handle and provides features specific to the Meglet model.
 */
public final class MegletHandleImpl extends MegletHandle {
	private int									status;
	private Meglet							meglet;
	private MegletContainer			megletContainer;
	private ServiceReference		appDescRef;
	private ServiceRegistration	serviceReg;
	private BundleContext				bc;
	private File								suspendedFileName	= null;
	private static Long					counter						= new Long(0);
	private Map									resumeArgs				= null;
	private String      				pid;
	private final static int 		NONEXISTENT = -1;
	
	/**
	 * The Meglet instance is suspended.
	 * 
	 * @modelguid {8EBD44E3-883B-4515-8EEA-8469F6F16408}
	 */
	public  final static int 		SUSPENDED = 2;

	public MegletHandleImpl(MegletContainer megletContainer, Meglet meglet,
			MegletDescriptor appDesc, BundleContext bc) throws Exception {
		super( appDesc.getPID(), appDesc );

		appDescRef = megletContainer.getReference( appDesc );		
		pid = appDesc.getPID();
		
		status = MegletHandleImpl.NONEXISTENT;
		this.megletContainer = megletContainer;
		this.bc = bc;
		this.meglet = meglet;
	}

	/**
	 * Returns the state of the Meglet instance specific to the Meglet model.
	 * 
	 * @throws IllegalStateException
	 *             if the Meglet handle is unregistered
	 * 
	 * @return the state of the Meglet instance
	 */
	public int getState() {
		if( status == MegletHandleImpl.NONEXISTENT )
			throw new RuntimeException( "Invalid state!" );
		return status;
	}	



	public ServiceReference startHandle(Map args) throws Exception {
		AccessController.checkPermission(new ApplicationAdminPermission(pid, 
				                             ApplicationAdminPermission.LAUNCH));

		if (args == null)
			resumeArgs = null;
		else
			resumeArgs = new Hashtable(args);

		if (status != MegletHandleImpl.NONEXISTENT)
			throw new Exception("Invalid State");

		if (meglet != null) {
			startApplication( meglet, args, null);
			registerAppHandle();
			setStatus(ApplicationHandle.RUNNING);

			return serviceReg.getReference();
		}
		else
			throw new Exception("Invalid meglet handle!");		
	}

	/**
	 * Destroys a Meglet according to the Meglet model. It calls the associated
	 * Meglet instance's stop() method with null parameter.
	 *  
	 */
	protected void destroySpecific() throws Exception {
		if (status == MegletHandleImpl.NONEXISTENT
				|| status == ApplicationHandle.STOPPING)
			throw new Exception("Invalid State");
		if (meglet != null) {
			setStatus(ApplicationHandle.STOPPING);
			stopApplication( meglet, null);
			meglet = null;
		}
		setStatus(MegletHandleImpl.NONEXISTENT);
		unregisterAppHandle();
	}

	/**
	 * Suspends the Melet instance. It calls the associated Meglet instance's
	 * stop() method and passes a non-null output stream as a parameter. It must
	 * preserve the contents of the output stream written by the Meglet instance
	 * even across device restarts. The same content must be provided to a
	 * resuming Meglet instance.
	 * 
	 * @throws SecurityException
	 *             if the caller doesn't have "manipulate"
	 *             ApplicationAdminPermission for the corresponding application.
	 * @throws IllegalStateException
	 *             if the Meglet handle is unregistered
	 */
	public void suspend() throws Exception {

		AccessController.checkPermission(new ApplicationAdminPermission(pid, 
				ApplicationAdminPermission.MANIPULATE));

		if (status != ApplicationHandle.RUNNING)
			throw new Exception("Invalid State");
		if (meglet != null) {
			synchronized (counter) {
				counter = new Long(counter.longValue() + 1);
				suspendedFileName = bc.getDataFile("SuspendedState-"
						+ counter.toString());
			}

			if (suspendedFileName.exists())
				suspendedFileName.delete();

			OutputStream os = new FileOutputStream(suspendedFileName);
			stopApplication( meglet, os);
			os.close();

			meglet = null;

			setStatus(MegletHandleImpl.SUSPENDED);
		}
		else
			throw new Exception("Invalid meglet handle!");
	}

	/**
	 * Resumes the Meglet instance. It calls the associated Meglet instance's
	 * start() method and passes a non-null input stream as a parameter. It must
	 * have the same contents that was saved by the suspending Meglet instance.
	 * The same startup arguments must also be passed to the resuming Meglet
	 * instance that was passed to the first starting instance.
	 * 
	 * @throws SecurityException
	 *             if the caller doesn't have "manipulate"
	 *             ApplicationAdminPermission for the corresponding application.
	 * @throws IllegalStateException
	 *             if the Meglet handle is unregistered
	 */
	public void resume() throws Exception {

		AccessController.checkPermission(new ApplicationAdminPermission(pid, 
				ApplicationAdminPermission.MANIPULATE));

		if (status != MegletHandleImpl.SUSPENDED)
			throw new Exception("Invalid State");

		MegletDescriptor appDesc = (MegletDescriptor)bc.getService( appDescRef );
		meglet = megletContainer.createMegletInstance(appDesc, true);
		appDesc.initMeglet(meglet, this);
		bc.ungetService( appDescRef );

		InputStream is = new FileInputStream(suspendedFileName);
		startApplication( meglet, resumeArgs, is);
		is.close();

		setStatus(ApplicationHandle.RUNNING);
	}

	private void setStatus(int status) {
		this.status = status;

		if( status != NONEXISTENT )
			serviceReg.setProperties( properties() );
	}

	private Hashtable properties() {
		Hashtable props = new Hashtable();
		props.put( "application.pid", pid );
		props.put( "application.state", new Integer( status ) );
		props.put( "descriptor.pid", appDescRef.getProperty( Constants.SERVICE_PID ) );		
		return props;
	}
	
	private void registerAppHandle() throws Exception {
		serviceReg = bc.registerService(
				"org.osgi.service.application.ApplicationHandle", this, properties() );
	}

	private void unregisterAppHandle() {
		if (serviceReg != null) {
			//unregistering the ApplicationHandle
			serviceReg.unregister();
			serviceReg = null;
		}
	}

	void startApplication( Meglet meglet, Map args, InputStream stream ) throws Exception {
		Class megletClass = Meglet.class;
		Method setupMethod = megletClass.getDeclaredMethod( "startApplication", new Class [] {
										Map.class, InputStream.class } );
		setupMethod.setAccessible( true );
		setupMethod.invoke( meglet, new Object [] { args, stream } );
	}	


	void stopApplication( Meglet meglet, OutputStream stream ) throws Exception {
		Class megletClass = Meglet.class;
		Method setupMethod = megletClass.getDeclaredMethod( "stopApplication", new Class [] {
										OutputStream.class } );
		setupMethod.setAccessible( true );
		setupMethod.invoke( meglet, new Object [] { stream } );
	}	
}<commit_msg>TEMPORARY: removed Security, as it doesn't work with the DOM parser<commit_after>/*
 * $Header$
 *
 * Copyright (c) OSGi Alliance (2004, 2005). All Rights Reserved.
 * 
 * Implementation of certain elements of the OSGi Specification may be subject
 * to third party intellectual property rights, including without limitation,
 * patent rights (such a third party may or may not be a member of the OSGi
 * Alliance). The OSGi Alliance is not responsible and shall not be held
 * responsible in any manner for identifying or failing to identify any or all
 * such third party intellectual property rights.
 * 
 * This document and the information contained herein are provided on an "AS IS"
 * basis and THE OSGI ALLIANCE DISCLAIMS ALL WARRANTIES, EXPRESS OR IMPLIED,
 * INCLUDING BUT NOT LIMITED TO ANY WARRANTY THAT THE USE OF THE INFORMATION
 * HEREIN WILL NOT INFRINGE ANY RIGHTS AND ANY IMPLIED WARRANTIES OF
 * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT WILL THE
 * OSGI ALLIANCE BE LIABLE FOR ANY LOSS OF PROFITS, LOSS OF BUSINESS, LOSS OF
 * USE OF DATA, INTERRUPTION OF BUSINESS, OR FOR DIRECT, INDIRECT, SPECIAL OR
 * EXEMPLARY, INCIDENTIAL, PUNITIVE OR CONSEQUENTIAL DAMAGES OF ANY KIND IN
 * CONNECTION WITH THIS DOCUMENT OR THE INFORMATION CONTAINED HEREIN, EVEN IF
 * ADVISED OF THE POSSIBILITY OF SUCH LOSS OR DAMAGE.
 * 
 * All Company, brand and product names may be trademarks that are the sole
 * property of their respective owners. All rights reserved.
 */
package org.osgi.impl.service.megcontainer;

import java.util.*;
import java.io.*;
import java.lang.reflect.Method;
//import java.security.*;
import org.osgi.framework.*;
import org.osgi.meglet.*;
import org.osgi.service.application.*;


/**
 * This service represents a Meglet instance. It is a specialization of the
 * application handle and provides features specific to the Meglet model.
 */
public final class MegletHandleImpl extends MegletHandle {
	private int									status;
	private Meglet							meglet;
	private MegletContainer			megletContainer;
	private ServiceReference		appDescRef;
	private ServiceRegistration	serviceReg;
	private BundleContext				bc;
	private File								suspendedFileName	= null;
	private static Long					counter						= new Long(0);
	private Map									resumeArgs				= null;
	private String      				pid;
	private final static int 		NONEXISTENT = -1;
	
	/**
	 * The Meglet instance is suspended.
	 * 
	 * @modelguid {8EBD44E3-883B-4515-8EEA-8469F6F16408}
	 */
	public  final static int 		SUSPENDED = 2;

	public MegletHandleImpl(MegletContainer megletContainer, Meglet meglet,
			MegletDescriptor appDesc, BundleContext bc) throws Exception {
		super( appDesc.getPID(), appDesc );

		appDescRef = megletContainer.getReference( appDesc );		
		pid = appDesc.getPID();
		
		status = MegletHandleImpl.NONEXISTENT;
		this.megletContainer = megletContainer;
		this.bc = bc;
		this.meglet = meglet;
	}

	/**
	 * Returns the state of the Meglet instance specific to the Meglet model.
	 * 
	 * @throws IllegalStateException
	 *             if the Meglet handle is unregistered
	 * 
	 * @return the state of the Meglet instance
	 */
	public int getState() {
		if( status == MegletHandleImpl.NONEXISTENT )
			throw new RuntimeException( "Invalid state!" );
		return status;
	}	



	public ServiceReference startHandle(Map args) throws Exception {
//		AccessController.checkPermission(new ApplicationAdminPermission(pid,  /* TODO */ 
//				                             ApplicationAdminPermission.LAUNCH));

		if (args == null)
			resumeArgs = null;
		else
			resumeArgs = new Hashtable(args);

		if (status != MegletHandleImpl.NONEXISTENT)
			throw new Exception("Invalid State");

		if (meglet != null) {
			startApplication( meglet, args, null);
			registerAppHandle();
			setStatus(ApplicationHandle.RUNNING);

			return serviceReg.getReference();
		}
		else
			throw new Exception("Invalid meglet handle!");		
	}

	/**
	 * Destroys a Meglet according to the Meglet model. It calls the associated
	 * Meglet instance's stop() method with null parameter.
	 *  
	 */
	protected void destroySpecific() throws Exception {
		if (status == MegletHandleImpl.NONEXISTENT
				|| status == ApplicationHandle.STOPPING)
			throw new Exception("Invalid State");
		if (meglet != null) {
			setStatus(ApplicationHandle.STOPPING);
			stopApplication( meglet, null);
			meglet = null;
		}
		setStatus(MegletHandleImpl.NONEXISTENT);
		unregisterAppHandle();
	}

	/**
	 * Suspends the Melet instance. It calls the associated Meglet instance's
	 * stop() method and passes a non-null output stream as a parameter. It must
	 * preserve the contents of the output stream written by the Meglet instance
	 * even across device restarts. The same content must be provided to a
	 * resuming Meglet instance.
	 * 
	 * @throws SecurityException
	 *             if the caller doesn't have "manipulate"
	 *             ApplicationAdminPermission for the corresponding application.
	 * @throws IllegalStateException
	 *             if the Meglet handle is unregistered
	 */
	public void suspend() throws Exception {

//		AccessController.checkPermission(new ApplicationAdminPermission(pid,  /* TODO */ 
//				ApplicationAdminPermission.MANIPULATE));

		if (status != ApplicationHandle.RUNNING)
			throw new Exception("Invalid State");
		if (meglet != null) {
			synchronized (counter) {
				counter = new Long(counter.longValue() + 1);
				suspendedFileName = bc.getDataFile("SuspendedState-"
						+ counter.toString());
			}

			if (suspendedFileName.exists())
				suspendedFileName.delete();

			OutputStream os = new FileOutputStream(suspendedFileName);
			stopApplication( meglet, os);
			os.close();

			meglet = null;

			setStatus(MegletHandleImpl.SUSPENDED);
		}
		else
			throw new Exception("Invalid meglet handle!");
	}

	/**
	 * Resumes the Meglet instance. It calls the associated Meglet instance's
	 * start() method and passes a non-null input stream as a parameter. It must
	 * have the same contents that was saved by the suspending Meglet instance.
	 * The same startup arguments must also be passed to the resuming Meglet
	 * instance that was passed to the first starting instance.
	 * 
	 * @throws SecurityException
	 *             if the caller doesn't have "manipulate"
	 *             ApplicationAdminPermission for the corresponding application.
	 * @throws IllegalStateException
	 *             if the Meglet handle is unregistered
	 */
	public void resume() throws Exception {

//		AccessController.checkPermission(new ApplicationAdminPermission(pid,   /* TODO */
//				ApplicationAdminPermission.MANIPULATE));

		if (status != MegletHandleImpl.SUSPENDED)
			throw new Exception("Invalid State");

		MegletDescriptor appDesc = (MegletDescriptor)bc.getService( appDescRef );
		meglet = megletContainer.createMegletInstance(appDesc, true);
		appDesc.initMeglet(meglet, this);
		bc.ungetService( appDescRef );

		InputStream is = new FileInputStream(suspendedFileName);
		startApplication( meglet, resumeArgs, is);
		is.close();

		setStatus(ApplicationHandle.RUNNING);
	}

	private void setStatus(int status) {
		this.status = status;

		if( status != NONEXISTENT )
			serviceReg.setProperties( properties() );
	}

	private Hashtable properties() {
		Hashtable props = new Hashtable();
		props.put( "application.pid", pid );
		props.put( "application.state", new Integer( status ) );
		props.put( "descriptor.pid", appDescRef.getProperty( Constants.SERVICE_PID ) );		
		return props;
	}
	
	private void registerAppHandle() throws Exception {
		serviceReg = bc.registerService(
				"org.osgi.service.application.ApplicationHandle", this, properties() );
	}

	private void unregisterAppHandle() {
		if (serviceReg != null) {
			//unregistering the ApplicationHandle
			serviceReg.unregister();
			serviceReg = null;
		}
	}

	void startApplication( Meglet meglet, Map args, InputStream stream ) throws Exception {
		Class megletClass = Meglet.class;
		Method setupMethod = megletClass.getDeclaredMethod( "startApplication", new Class [] {
										Map.class, InputStream.class } );
		setupMethod.setAccessible( true );
		setupMethod.invoke( meglet, new Object [] { args, stream } );
	}	


	void stopApplication( Meglet meglet, OutputStream stream ) throws Exception {
		Class megletClass = Meglet.class;
		Method setupMethod = megletClass.getDeclaredMethod( "stopApplication", new Class [] {
										OutputStream.class } );
		setupMethod.setAccessible( true );
		setupMethod.invoke( meglet, new Object [] { stream } );
	}	
}
{'fraction_non_alphanumeric': 0.08413801224682053, 'fraction_numerical': 0.004003768252472915, 'mean_word_length': 3.76170451359686, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '382303', 'n_tokens_mistral': 5331, 'n_tokens_neox': 4580, 'n_words': 1623}