DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets

  • submit to reddit

Recent Snippets

                    package ImageToPdf;

import javax.imageio.ImageIO;
import javax.imageio.ImageReader;
import javax.imageio.stream.ImageInputStream;
import java.awt.image.BufferedImage;
import java.io.File;
import java.net.URI;

import com.aspose.words.Document;
import com.aspose.words.DocumentBuilder;
import com.aspose.words.BreakType;
import com.aspose.words.PageSetup;
import com.aspose.words.ConvertUtil;
import com.aspose.words.RelativeHorizontalPosition;
import com.aspose.words.RelativeVerticalPosition;
import com.aspose.words.WrapType;


class Program
{
    public static void main(String[] args) throws Exception
    {
        // Sample infrastructure.
        URI exeDir = Program.class.getResource("").toURI();
        String dataDir = new File(exeDir.resolve("../../Data")) + File.separator;

        convertImageToPdf(dataDir + "Test.jpg", dataDir + "TestJpg Out.pdf");
        convertImageToPdf(dataDir + "Test.png", dataDir + "TestPng Out.pdf");
        convertImageToPdf(dataDir + "Test.bmp", dataDir + "TestBmp Out.pdf");
        convertImageToPdf(dataDir + "Test.gif", dataDir + "TestGif Out.pdf");
    }

    /**
     * Converts an image to PDF using Aspose.Words for Java.
     *
     * @param inputFileName File name of input image file.
     * @param outputFileName Output PDF file name.
     */
    public static void convertImageToPdf(String inputFileName, String outputFileName) throws Exception
    {
        // Create Aspose.Words.Document and DocumentBuilder.
        // The builder makes it simple to add content to the document.
        Document doc = new Document();
        DocumentBuilder builder = new DocumentBuilder(doc);

        // Load images from the disk using the approriate reader.
        // The file formats that can be loaded depends on the image readers available on the machine.
        ImageInputStream iis = ImageIO.createImageInputStream(new File(inputFileName));
        ImageReader reader = ImageIO.getImageReaders(iis).next();
        reader.setInput(iis, false);

        try
        {
            // Get the number of frames in the image.
            int framesCount = reader.getNumImages(true);

            // Loop through all frames.
            for (int frameIdx = 0; frameIdx < framesCount; frameIdx++)
            {
                // Insert a section break before each new page, in case of a multi-frame image.
                if (frameIdx != 0)
                    builder.insertBreak(BreakType.SECTION_BREAK_NEW_PAGE);

                // Select active frame.
                BufferedImage image = reader.read(frameIdx);

                // We want the size of the page to be the same as the size of the image.
                // Convert pixels to points to size the page to the actual image size.
                PageSetup ps = builder.getPageSetup();

                ps.setPageWidth(ConvertUtil.pixelToPoint(image.getWidth()));
                ps.setPageHeight(ConvertUtil.pixelToPoint(image.getHeight()));

                // Insert the image into the document and position it at the top left corner of the page.
                builder.insertImage(
                    image,
                    RelativeHorizontalPosition.PAGE,
                    0,
                    RelativeVerticalPosition.PAGE,
                    0,
                    ps.getPageWidth(),
                    ps.getPageHeight(),
                    WrapType.NONE);
            }
        }

        finally {
            if (iis != null) {
                iis.close();
                reader.dispose();
            }
        }

        // Save the document to PDF.
        doc.save(outputFileName);
    }
} 

//Converts large size image into a PDF document

//When the size of image is bigger than max allowed size of MS Word page, an exception is thrown or image is not visible in output document. The measurement for images must be between 0 and 55.88 cm (55.88 cm = 1584 points). In this case, use the following code example.
package ImageToPdf;

import javax.imageio.ImageIO;
import javax.imageio.ImageReader;
import javax.imageio.stream.ImageInputStream;
import java.awt.image.BufferedImage;
import java.io.File;
import java.net.URI;

import com.aspose.words.Document;
import com.aspose.words.DocumentBuilder;
import com.aspose.words.BreakType;
import com.aspose.words.PageSetup;
import com.aspose.words.ConvertUtil;
import com.aspose.words.RelativeHorizontalPosition;
import com.aspose.words.RelativeVerticalPosition;
import com.aspose.words.WrapType;


class Program
{
    public static void main(String[] args) throws Exception
    {
        // Sample infrastructure.
        URI exeDir = Program.class.getResource("").toURI();
        String dataDir = new File(exeDir.resolve("../../Data")) + File.separator;

        convertImageToPdf(dataDir + "Test.jpg", dataDir + "TestJpg Out.pdf");
        convertImageToPdf(dataDir + "Test.png", dataDir + "TestPng Out.pdf");
        convertImageToPdf(dataDir + "Test.bmp", dataDir + "TestBmp Out.pdf");
        convertImageToPdf(dataDir + "Test.gif", dataDir + "TestGif Out.pdf");
    }

    /**
     * Converts an image to PDF using Aspose.Words for Java.
     *
     * @param inputFileName File name of input image file.
     * @param outputFileName Output PDF file name.
     */
    	public static void convertImageToPdf(String inputFileName, String outputFileName) throws Exception
	{
	    // Create Aspose.Words.Document and DocumentBuilder.
	    // The builder makes it simple to add content to the document.
	    Document doc = new Document();
	    DocumentBuilder builder = new DocumentBuilder(doc);

	    // Load images from the disk using the approriate reader.
	    // The file formats that can be loaded depends on the image readers available on the machine.
	    ImageInputStream iis = ImageIO.createImageInputStream(new File(inputFileName));
	    ImageReader reader = ImageIO.getImageReaders(iis).next();
	    reader.setInput(iis, false);

	    try
	    {
	        // Get the number of frames in the image.
	        int framesCount = reader.getNumImages(true);

	        // Loop through all frames.
	        for (int frameIdx = 0; frameIdx < framesCount; frameIdx++)
	        {
	            // Insert a section break before each new page, in case of a multi-frame image.
	            if (frameIdx != 0)
	                builder.insertBreak(BreakType.SECTION_BREAK_NEW_PAGE);

	            // Select active frame.
	            BufferedImage image = reader.read(frameIdx);

	            // Max page size
	            double maxPageHeight = 1584;
	            double maxPageWidth = 1584;

	            double currentImageHeight = ConvertUtil.pixelToPoint(image.getHeight());
	            double currentImageWidth = ConvertUtil.pixelToPoint(image.getWidth());

	            if (currentImageWidth >= maxPageWidth || currentImageHeight >= maxPageHeight)
	            {

	                // Get max image size.
	            	 double[] size = CalculateImageSize(image, maxPageHeight, maxPageWidth, currentImageHeight, currentImageWidth);
	            	 currentImageWidth = size[0];
	            	 currentImageHeight = size[1];
	            }

	            // We want the size of the page to be the same as the size of the image.
	            // Convert pixels to points to size the page to the actual image size.
	            PageSetup ps = builder.getPageSetup();

	            ps.setPageWidth(currentImageWidth);
	            ps.setPageHeight(currentImageHeight);

	            // Insert the image into the document and position it at the top left corner of the page.
	            Shape shape = builder.insertImage(
	                image,
	                RelativeHorizontalPosition.PAGE,
	                0,
	                RelativeVerticalPosition.PAGE,
	                0,
	                ps.getPageWidth(),
	                ps.getPageHeight(),
	                WrapType.NONE);

	            resizeLargeImage(shape);
	        }
	    }

	    finally {
	        if (iis != null) {
	            iis.close();
	            reader.dispose();
	        }
	    }

	    // Save the document to PDF.
	    doc.save(outputFileName);
	}

	public static double[] CalculateImageSize(BufferedImage img, double containerHeight,  double containerWidth, double targetHeight, double targetWidth) throws Exception {

	 targetHeight = containerHeight;
	 targetWidth = containerWidth;

	  //Get size of an image
	    double imgHeight = ConvertUtil.pixelToPoint(img.getHeight());
	    double imgWidth = ConvertUtil.pixelToPoint(img.getWidth());

	    if (imgHeight < targetHeight && imgWidth < targetWidth)
	    {
	        targetHeight = imgHeight;
	        targetWidth = imgWidth;
	    }
	    else
	    {
	        //Calculate size of an image in the document
	        double ratioWidth = imgWidth / targetWidth;
	        double ratioHeight = imgHeight / targetHeight;
	        if (ratioWidth > ratioHeight)
	            targetHeight = (targetHeight * (ratioHeight / ratioWidth));
	        else
	            targetWidth = (targetWidth * (ratioWidth / ratioHeight));
	    }

	    double[] size = new double[2];

	    size[0] = targetWidth; //width
	    size[1] = targetHeight; //height

	    return(size);
	}

    public static void resizeLargeImage(Shape image) throws Exception
    {
        // Return if this shape is not an image.
        if (!image.hasImage())
            return;

        // Calculate the free space based on an inline or floating image. If inline we must take the page margins into account.
        PageSetup ps = image.getParentParagraph().getParentSection().getPageSetup();
        double freePageWidth = image.isInline() ? ps.getPageWidth() - ps.getLeftMargin() - ps.getRightMargin() : ps.getPageWidth();
        double freePageHeight = image.isInline() ? ps.getPageHeight() - ps.getTopMargin() - ps.getBottomMargin() : ps.getPageHeight();

        // Is one of the sides of this image too big for the page?
        ImageSize size = image.getImageData().getImageSize();
        boolean exceedsMaxPageSize = size.getWidthPoints() > freePageWidth || size.getHeightPoints() > freePageHeight;

        if (exceedsMaxPageSize)
        {
            // Calculate the ratio to fit the page size based on which side is longer.
            boolean widthLonger = (size.getWidthPoints() > size.getHeightPoints());
            double ratio = widthLonger ? freePageWidth / size.getWidthPoints() : freePageHeight / size.getHeightPoints();

            // Set the new size.
            image.setWidth(size.getWidthPoints() * ratio);
            image.setHeight(size.getHeightPoints() * ratio);
        }
    }
}
                
                    package com.pky.com;

public class StaticExample {
	public static String company = "Infosys Limited";
	public String name;
	public int id;

	public StaticExample(String name, int id) {
		this.name = name;
		this.id = id;
	}

	public void show() {
		System.out.println("Employee Name :" + name + "\nEmployee Id :" + id
				+ "\nEmployee company :" + company);
	}

	public static void main(String arg[]) {
		StaticExample se = new StaticExample("Pradeep Yadav", 99231);
		se.show();

	}
}


Output :

Employee Name :Pradeep Yadav
Employee Id :99231
Employee company :Infosys Limited                
                    Here we are using OR operator so it will return only unique value. If you need to add duplicacy too use + operator. 

#!/usr/local/bin/ruby -w


class Abc

  def display

      arr1=Array(1..10);

      arr2=Array(7..15);

      arr3=arr1|arr2;

      puts "Elements of third array are :";

      arr3.each{|i| puts i};

 
 end

end

abc=Abc.new

abc.display

Output :
Elements of third array are :
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

                
                    package com.pk.com;

public class Example {
	public static void main(String[] args) {
		String s = "abc";
		String s2 = "abc";
		String s3 = new String("abc");
		if (s == s2)
			System.out.println("true");
		else
			System.out.println("false");
		if (s.equals(s2))
			System.out.println("true");
		else
			System.out.println("false");
		if (s == s3)
			System.out.println("true");
		else
			System.out.println("false");
		if (s.equals(s3))
			System.out.println("true");
		else
			System.out.println("false");
	}

}
                
                    //[C#]

/* Create a DataTable object (Employee) and add columns to it (Employee_ID, 
  * Employee_Name, Gender).   
  */
DataTable dt = new DataTable("Employee");
dt.Columns.Add("Employee_ID", typeof(Int32));
dt.Columns.Add("Employee_Name", typeof(string));
dt.Columns.Add("Gender", typeof(string));
//Add 2 rows into the DataTable object programmatically
DataRow dr = dt.NewRow();
dr[0] = 1;
dr[1] = "John Smith";
dr[2] = "Male";
dt.Rows.Add(dr);
dr = dt.NewRow();
dr[0] = 2;
dr[1] = "Mary Miller";
dr[2] = "Female";
dt.Rows.Add(dr);
// Create Document instance
Document doc = new Document();
doc.Pages.Add();
// Initializes a new instance of the Table
Aspose.Pdf.Table table = new Aspose.Pdf.Table();
//Set column widths of the table
table.ColumnWidths = "40 100 100 100";
// Set the table border color as LightGray
table.Border = new Aspose.Pdf.BorderInfo(Aspose.Pdf.BorderSide.All, .5f, Aspose.Pdf.Color.FromRgb(System.Drawing.Color.LightGray));
// set the border for table cells
table.DefaultCellBorder = new Aspose.Pdf.BorderInfo(Aspose.Pdf.BorderSide.All, .5f, Aspose.Pdf.Color.FromRgb(System.Drawing.Color.LightGray));
table.ImportDataTable(dt, true, 0, 1, 3, 3);

// Add table object to first page of input document
doc.Pages[1].Paragraphs.Add(table);
// Save updated document containing table object
doc.Save("c:/pdftest/DataIntegrated.pdf");

//[VB.NET]

'**************************************************************************
'* Create a DataTable object (Employee) and add columns to it (Employee_ID, 
'* Employee_Name, Gender).   
'**************************************************************************
Dim dt As DataTable = New DataTable("Employee")
dt.Columns.Add("Employee_ID", System.Type.GetType("System.Int32"))
dt.Columns.Add("Employee_Name", System.Type.GetType("System.String"))
dt.Columns.Add("Gender", System.Type.GetType("System.String"))
'Add 2 rows into the DataTable object programmatically
Dim dr As DataRow = dt.NewRow()
dr(0) = 1
dr(1) = "John Smith"
dr(2) = "Male"
dt.Rows.Add(dr)

dr = dt.NewRow()
dr(0) = 2
dr(1) = "Mary Miller"
dr(2) = "Female"
dt.Rows.Add(dr)

' Create Document instance
Dim doc As Document = New Document()
doc.Pages.Add()
' Initializes a new instance of the Table
Dim table As Aspose.Pdf.Table = New Aspose.Pdf.Table()
'Set column widths of the table
table.ColumnWidths = "40 100 100 100"
' Set the table border color as LightGray
table.Border = New Aspose.Pdf.BorderInfo(Aspose.Pdf.BorderSide.All, 0.5F, Aspose.Pdf.Color.FromRgb(System.Drawing.Color.LightGray))
' set the border for table cells
table.DefaultCellBorder = New Aspose.Pdf.BorderInfo(Aspose.Pdf.BorderSide.All, 0.5F, Aspose.Pdf.Color.FromRgb(System.Drawing.Color.LightGray))
table.ImportDataTable(dt, True, 0, 1, 3, 3)

' Add table object to first page of input document
doc.Pages(1).Paragraphs.Add(table)
' Save updated document containing table object
doc.Save("c:/pdftest/DataIntegrated.pdf")

                
                    // MainWindow.xaml

<Window x:Class="Basic_CameraViewer.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="550" Width="550" 
        ResizeMode="NoResize" WindowStartupLocation="CenterScreen">
    <Grid>
        <GroupBox Header="Connect to USB camera" Height="100" Width="150"
                  HorizontalAlignment="Left" VerticalAlignment="Top">
            <Grid>
                <Button Content="Connect" Width="75" Margin="32,19,0,0" 
                        HorizontalAlignment="Left" VerticalAlignment="Top"
                        Click="ConnectUSBCamera_Click"/>
                <Button Content="Disconnect" Width="75" Margin="32,46,0,0"
                        HorizontalAlignment="Left" VerticalAlignment="Top"
                        Click="DisconnectUSBCamera_Click"/>
            </Grid>
        </GroupBox>

        <Grid Name="CameraBox" Margin="10,105,10,166"/>

        <GroupBox Header="Function" Height="160" Width="542" Margin="0,360,0,0"
                  HorizontalAlignment="Left" VerticalAlignment="Top" >
            <Grid>
                <Grid.ColumnDefinitions>
                    <ColumnDefinition Width="*"/>
                    <ColumnDefinition Width="*"/>
                </Grid.ColumnDefinitions>
                <ListBox Grid.Column="1" Name="ConnectedClientList"/>
                <GroupBox Grid.Column="0" Header="Set Listen Address">
                    <Grid>
                        <Grid.RowDefinitions>
                            <RowDefinition Height="*"/>
                            <RowDefinition Height="*"/>
                            <RowDefinition Height="*"/>
                        </Grid.RowDefinitions>
                        <Grid Grid.Row="0">
                            <Grid.ColumnDefinitions>
                                <ColumnDefinition Width="*"/>
                                <ColumnDefinition Width="3*"/>
                            </Grid.ColumnDefinitions>
                            <Label Grid.Column="0" Content="Address"/>
                            <TextBox Grid.Column="1" Height="25" Name="IpAddressText"/>
                        </Grid>
                        <Grid Grid.Row="1">
                            <Grid.ColumnDefinitions>
                                <ColumnDefinition Width="*"/>
                                <ColumnDefinition Width="3*"/>
                            </Grid.ColumnDefinitions>
                            <Label Grid.Column="0" Content="Port"/>
                            <TextBox Grid.Column="1" Height="25" Name="PortText"/>
                        </Grid>
                        <Grid Grid.Row="2">
                            <Grid.ColumnDefinitions>
                                <ColumnDefinition Width="*"/>
                                <ColumnDefinition Width="*"/>
                            </Grid.ColumnDefinitions>
                            <Button Grid.Column="0" Content="Start" 
                                    HorizontalAlignment="Center" VerticalAlignment="Center" 
                                    Width="75" Click="StartServer_Click"/>
                            <Button Grid.Column="1" Content="Stop" 
                                    HorizontalAlignment="Center" VerticalAlignment="Center" 
                                    Width="75" Click="StopServer_Click" />
                        </Grid>
                    </Grid>
                </GroupBox>
            </Grid>
        </GroupBox>
    </Grid>
</Window>

// MainWindow.xaml.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Ozeki.Media.IPCamera;
using Ozeki.Media.MediaHandlers;
using Ozeki.Media.MediaHandlers.Video;
using Ozeki.Media.MJPEGStreaming;
using Ozeki.Media.Video.Controls;

namespace Basic_CameraViewer
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        private VideoViewerWPF _videoViewerWpf;

        private BitmapSourceProvider _provider;

        private IIPCamera _ipCamera;

        private WebCamera _webCamera;

        private MediaConnector _connector;

        private MyServer _server;

        private IVideoSender _videoSender;

        public MainWindow()
        {
            InitializeComponent();

            _connector = new MediaConnector();

            _provider = new BitmapSourceProvider();

            _server = new MyServer();

            SetVideoViewer();
        }

        private void SetVideoViewer()
        {
            _videoViewerWpf = new VideoViewerWPF
            {
                HorizontalAlignment = HorizontalAlignment.Stretch,
                VerticalAlignment = VerticalAlignment.Stretch,
                Background = Brushes.Black
            };
            CameraBox.Children.Add(_videoViewerWpf);

            _videoViewerWpf.SetImageProvider(_provider);
        }

        #region USB Camera Connect/Disconnect

        private void ConnectUSBCamera_Click(object sender, RoutedEventArgs e)
        {
            _webCamera = WebCamera.GetDefaultDevice();
            if (_webCamera == null) return;
            _connector.Connect(_webCamera, _provider);
            _videoSender = _webCamera;

            _webCamera.Start();
            _videoViewerWpf.Start();
        }

        private void DisconnectUSBCamera_Click(object sender, RoutedEventArgs e)
        {
            if (_webCamera == null) return;
            _videoViewerWpf.Stop();

            _webCamera.Stop();
            _webCamera.Dispose();

            _connector.Disconnect(_webCamera, _provider);
        }
        #endregion

        private void GuiThread(Action action)
        {
            Dispatcher.BeginInvoke(action);
        }

        private void StartServer_Click(object sender, RoutedEventArgs e)
        {
            var ipadress = IpAddressText.Text;
            var port = int.Parse(PortText.Text);
            _server.VideoSender = _videoSender;

            _server.OnClientCountChanged += server_OnClientCountChanged;

            _server.Start();
            _server.SetListenAddress(ipadress, port);
        }

        void server_OnClientCountChanged(object sender, EventArgs e)
        {
            GuiThread(() =>
            {
                ConnectedClientList.Items.Clear();

                foreach (var client in _server.ConnectedClients)
                    ConnectedClientList.Items.Add("End point: " +
                        client.TransportInfo.RemoteEndPoint);
            });
        }

        private void StopServer_Click(object sender, RoutedEventArgs e)
        {
            _server.OnClientCountChanged -= server_OnClientCountChanged;
            _server.Stop();
        }
    }
}                
                        /** Receives info about opened and closed TopComponents from window system.
     */
    private static class WindowRegistryL implements PropertyChangeListener {

        @Override
        public void propertyChange(PropertyChangeEvent evt) {
            String name = evt.getPropertyName();
            if (TopComponent.Registry.PROP_TC_OPENED.equals(name)) {
                addFile((TopComponent) evt.getNewValue());
            }
        }
    }                
                    package com.sun.enterprise.resource.pool.datastructure;

import com.sun.appserv.connectors.internal.api.PoolingException;
import com.sun.enterprise.resource.ResourceHandle;
import com.sun.enterprise.resource.allocator.ResourceAllocator;
import com.sun.enterprise.resource.pool.ResourceHandler;
import com.sun.enterprise.resource.pool.datastructure.strategy.ResourceSelectionStrategy;
import com.sun.logging.LogDomains;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.logging.Level;
import java.util.logging.Logger;

public class NonBlockingDataStructure implements DataStructure {

    private ResourceSelectionStrategy strategy;
    private final ResourceHandler handler;
    private final AtomicInteger maxSize;

    private final ConcurrentLinkedQueue<ResourceHandle> freeResourceHandles = new ConcurrentLinkedQueue<ResourceHandle>();
    private final ConcurrentLinkedQueue<ResourceHandle> allResourceHandles = new ConcurrentLinkedQueue<ResourceHandle>();

    protected final static Logger _logger =
            LogDomains.getLogger(NonBlockingDataStructure.class, LogDomains.RSR_LOGGER);

    public NonBlockingDataStructure(String parameters, int maxSize,
                                    ResourceHandler handler, String strategyClass) {
        this.maxSize = new AtomicInteger(maxSize);
        this.handler = handler;
        initializeStrategy(strategyClass);
        if (_logger.isLoggable(Level.FINEST)) {
            _logger.log(Level.FINEST, "pool.datastructure.rwlockds.init");
        }
    }

    private void initializeStrategy(String strategyClass) {
        //TODO
    }

    @Override
    public void setMaxSize(int i) {
        this.maxSize.set(i);
    }

    @Override
    public int addResource(ResourceAllocator resourceAllocator, int count) throws PoolingException {
        if(_logger.isLoggable(Level.FINE)){
            _logger.fine("addResource for "+count+" resources.");
        }
        int addedResourceHandles = 0;
        try {
            for (int i = 0; i < count && allResourceHandles.size() < maxSize.get(); i++) {
                ResourceHandle handle = handler.createResource(resourceAllocator);
                allResourceHandles.offer(handle);
                freeResourceHandles.offer(handle);
                addedResourceHandles++;
            }
        } catch (Exception e) {
            PoolingException pe = new PoolingException(e.getMessage());
            pe.initCause(e);
            throw pe;
        }
        if(_logger.isLoggable(Level.FINE)){
            _logger.fine("addResource added "+addedResourceHandles+" resources.");
        }
        return addedResourceHandles;
    }

    @Override
    public ResourceHandle getResource() {
        ResourceHandle resourceHandle = freeResourceHandles.poll();
        if (resourceHandle != null) {
            resourceHandle.setBusy(true);
            if(_logger.isLoggable(Level.FINE)){
                _logger.fine("getResource found resource.");
            }
        }
        return resourceHandle;
    }

    @Override
    public void removeResource(ResourceHandle resourceHandle) {
        if(_logger.isLoggable(Level.FINE)){
            _logger.fine("removeResource called.");
        }
        allResourceHandles.remove(resourceHandle);
        freeResourceHandles.remove(resourceHandle);
        handler.deleteResource(resourceHandle);
    }

    @Override
    public void returnResource(ResourceHandle resourceHandle) {
        if(_logger.isLoggable(Level.FINE)){
            _logger.fine("returnResource called.");
        }
        resourceHandle.setBusy(false);
        freeResourceHandles.offer(resourceHandle);
    }

    @Override
    public int getFreeListSize() {
        return freeResourceHandles.size();
    }

    @Override
    public void removeAll() {
        if(_logger.isLoggable(Level.FINE)){
            _logger.fine("removeAll called.");
        }
        Iterator<ResourceHandle> it = allResourceHandles.iterator();
        while (it.hasNext()) {
            ResourceHandle next = it.next();
            freeResourceHandles.remove(next);
            handler.deleteResource(next);
            it.remove();
        }
    }

    @Override
    public int getResourcesSize() {
        return allResourceHandles.size();
    }

    @Override
    public ArrayList<ResourceHandle> getAllResources() {
        throw new UnsupportedOperationException("Not supported yet.");
    }
}
                
                    //Applying Protection on a PPTX Shapes 

//[Android]

//Open the desired presentation
PresentationEx pTemplate = new PresentationEx("AddingSlides.pptx");

//Slide object for holding temporary slides
SlideEx slide;

//Shape object for holding temporary shapes
ShapeEx shape;

//Traversing through all the slides in presentation
for(int slCount=0;slCount<pTemplate.getSlides().getCount();slCount++)
{
	//Accessing the slide in the presentation
	slide = pTemplate.getSlides().get_Item(slCount);
	
	//Traversing through all the shapes in the slides
	for (int count = 0; count < slide.getShapes().getCount(); count++)
	{
	    shape = slide.getShapes().get_Item(count);

	    //if shape is Autoshape
	    if (shape instanceof AutoShapeEx)
	    {
	        //Type casting to Auto shape and getting auto shape lock
	        AutoShapeEx Ashp = (AutoShapeEx)shape;
	        AutoShapeLockEx AutoShapeLock = Ashp.getShapeLock();

	        //Applying shapes locks
	        AutoShapeLock.setNoMove(true);
	        AutoShapeLock.setNoSelect(true);
	        AutoShapeLock.setNoResize(true);
	    }

	    //if shape is group shape
	    else if (shape instanceof GroupShapeEx)
	    {
	        //Type casting to group shape and getting group shape lock
	        GroupShapeEx Group = (GroupShapeEx)shape;
	        GroupShapeLockEx groupShapeLock = Group.getShapeLock();

	        //Applying shapes locks
	        groupShapeLock.setNoMove(true);
	        groupShapeLock.setNoSelect(true);
	        groupShapeLock.setNoResize(true);
	    }

	    //if shape is Connector shape
	    else if (shape instanceof ConnectorEx )
	    {
	        //Type casting to connector shape and getting connector shape lock
	        ConnectorEx Conn = (ConnectorEx)shape;
	        ConnectorLockEx ConnLock = Conn.getShapeLock();

	        //Applying shapes locks
	        ConnLock.setNoMove(true);
	        ConnLock.setNoSelect(true);
	        ConnLock.setNoResize(true);
	    }

	    //if shape is picture frame
	    else if (shape instanceof PictureFrameEx)
	    {
	        //Type casting to picture frame shape and getting picture frame shape lock
	        PictureFrameEx Pic = (PictureFrameEx)shape;
	        PictureFrameLockEx PicLock = Pic.getShapeLock();

	        //Applying shapes locks
	        PicLock.setNoMove(true);
	        PicLock.setNoSelect(true);
	        PicLock.setNoResize(true);
	    }
	}
}

//Saving the presentation file
pTemplate.write("locked.pptx");

//Removing Protection from the Presentation 

//Protection applied using Aspose.Slides for Android can only be removed with Aspose.Slides. To unlock a shape, set the value of the applied lock to false. The code sample that follows shows how to unlock shapes in a locked presentation.

//[Android]

//Open the desired presentation
PresentationEx pTemplate = new PresentationEx("locked.pptx");

//Slide object for holding temporary slides
SlideEx slide;

//Shape object for holding temporary shapes
ShapeEx shape;

//Traversing through all the slides in presentation
for(int slCount=0;slCount<pTemplate.getSlides().getCount();slCount++)
{
	//Accessing the slide in the presentation
	slide = pTemplate.getSlides().get_Item(slCount);
	
	//Traversing through all the shapes in the slides
	for (int count = 0; count < slide.getShapes().getCount(); count++)
	{
	    shape = slide.getShapes().get_Item(count);

	    //if shape is Autoshape
	    if (shape instanceof AutoShapeEx)
	    {
	        //Type casting to Auto shape and getting auto shape lock
	        AutoShapeEx Ashp = (AutoShapeEx)shape;
	        AutoShapeLockEx AutoShapeLock = Ashp.getShapeLock();

	        //Applying shapes locks
	        AutoShapeLock.setNoMove(false);
	        AutoShapeLock.setNoSelect(false);
	        AutoShapeLock.setNoResize(false);
	    }

	    //if shape is group shape
	    else if (shape instanceof GroupShapeEx)
	    {
	        //Type casting to group shape and getting group shape lock
	        GroupShapeEx Group = (GroupShapeEx)shape;
	        GroupShapeLockEx groupShapeLock = Group.getShapeLock();

	        //Applying shapes locks
	        groupShapeLock.setNoMove(false);
	        groupShapeLock.setNoSelect(false);
	        groupShapeLock.setNoResize(false);
	    }

	    //if shape is Connector shape
	    else if (shape instanceof ConnectorEx )
	    {
	        //Type casting to connector shape and getting connector shape lock
	        ConnectorEx Conn = (ConnectorEx)shape;
	        ConnectorLockEx ConnLock = Conn.getShapeLock();

	        //Applying shapes locks
	        ConnLock.setNoMove(false);
	        ConnLock.setNoSelect(false);
	        ConnLock.setNoResize(false);
	    }

	    //if shape is picture frame
	    else if (shape instanceof PictureFrameEx)
	    {
	        //Type casting to picture frame shape and getting picture frame shape lock
	        PictureFrameEx Pic = (PictureFrameEx)shape;
	        PictureFrameLockEx PicLock = Pic.getShapeLock();

	        //Applying shapes locks
	        PicLock.setNoMove(false);
	        PicLock.setNoSelect(false);
	        PicLock.setNoResize(false);
	    }
	}
}

//Saving the presentation file
pTemplate.write("Unlocked.pptx");