code stringlengths 3 1.18M | language stringclasses 1
value |
|---|---|
package net.coobird.thumbnailator.resizers;
import java.awt.Dimension;
/**
* This class provides factory methods which provides suitable {@link Resizer}s
* for a given situation.
*
* <dl>
* <dt>{@code Resizer}s returned by this {@code ResizerFactory}:</dt>
* <dd>
* The {@link Resizer}s returned by this {@link ResizerFactory} depends upon
* the size of the source and destination images. The conditions and the
* {@link Resizer}s returned are as follows:
*
* <ul>
* <li>Default via {@link #getResizer()}
* <ul><li>{@link ProgressiveBilinearResizer}</li></ul>
* </li>
* <li>Destination image has the same dimensions as the source image via
* {@link #getResizer(Dimension, Dimension)}
* <ul><li>{@link NullResizer}</li></ul>
* </li>
* <li>Both the width and height of the destination image is larger than the
* source image via {@link #getResizer(Dimension, Dimension)}
* <ul><li>{@link BicubicResizer}</li></ul>
* </li>
* <li>Both the width and height of the destination image is smaller in the
* source image by a factor larger than 2,
* via {@link #getResizer(Dimension, Dimension)}
* <ul><li>{@link ProgressiveBilinearResizer}</li></ul>
* </li>
* <li>Both the width and height of the destination image is smaller in the
* source image not by a factor larger than 2,
* via {@link #getResizer(Dimension, Dimension)}
* <ul><li>{@link BilinearResizer}</li></ul>
* </li>
* <li>Other conditions not described via
* {@link #getResizer(Dimension, Dimension)}
* <ul><li>{@link ProgressiveBilinearResizer}</li></ul>
* </li>
* </ul>
* </dd>
* </dl>
*
* <DL>
* <DT><B>Usage:</B></DT>
* <DD>
* The following example code demonstrates how to use {@link DefaultResizerFactory}
* in order to obtain the optimal {@link Resizer}, and using that in order to
* perform the resizing operation.
* <p>
* <pre>
BufferedImage sourceImage = new BufferedImageBuilder(400, 400).build();
BufferedImage destImage = new BufferedImageBuilder(200, 200).build();
Dimension sourceSize = new Dimension(sourceImage.getWidth(), sourceImage.getHeight());
Dimension destSize = new Dimension(destImage.getWidth(), destImage.getHeight());
// Obtain the optimal Resizer for this resizing operation.
Resizer resizer = DefaultResizerFactory.getInstance().getResizer(sourceSize, destSize);
// Perform the resizing using the Resizer obtained from the ResizerFactory.
resizer.resize(sourceImage, destImage);
* </pre>
* </DD>
* </DL>
* When a specific {@link Resizer} is required, the {@link Resizers}
* {@code enum} is another way to obtain {@link Resizer}s.
* <p>
*
* @see Resizers
*
* @author coobird
* @since 0.4.0
*
*/
public class DefaultResizerFactory implements ResizerFactory
{
private static final DefaultResizerFactory INSTANCE = new DefaultResizerFactory();
/**
* This class is not intended to be instantiated via the constructor.
*/
private DefaultResizerFactory() {}
/**
* Returns an instance of this class.
*
* @return An instance of this class.
*/
public static ResizerFactory getInstance()
{
return INSTANCE;
}
public Resizer getResizer()
{
return Resizers.PROGRESSIVE;
}
public Resizer getResizer(Dimension originalSize, Dimension thumbnailSize)
{
int origWidth = originalSize.width;
int origHeight = originalSize.height;
int thumbWidth = thumbnailSize.width;
int thumbHeight = thumbnailSize.height;
if (thumbWidth < origWidth && thumbHeight < origHeight)
{
if (thumbWidth < (origWidth / 2) && thumbHeight < (origHeight / 2))
{
return Resizers.PROGRESSIVE;
}
else
{
return Resizers.BILINEAR;
}
}
else if (thumbWidth > origWidth && thumbHeight > origHeight)
{
return Resizers.BICUBIC;
}
else if (thumbWidth == origWidth && thumbHeight == origHeight)
{
return Resizers.NULL;
}
else
{
return getResizer();
}
}
}
| Java |
/**
* This package provides classes which perform image resizing operations which
* is used to create thumbnails with Thumbnailator.
*/
package net.coobird.thumbnailator.resizers;
| Java |
package net.coobird.thumbnailator.resizers;
import java.awt.RenderingHints;
import java.awt.image.BufferedImage;
import java.util.Collections;
import java.util.Map;
/**
* Image resizer class using bicubic interpolation for the resizing operation.
*
* @author coobird
*
*/
public class BicubicResizer extends AbstractResizer
{
/**
* Instantiates a {@link BicubicResizer} with default rendering hints.
*/
public BicubicResizer()
{
this(Collections.<RenderingHints.Key, Object>emptyMap());
}
/**
* Instantiates a {@link BicubicResizer} with the specified rendering hints.
*
* @param hints Additional rendering hints to apply.
*/
public BicubicResizer(Map<RenderingHints.Key, Object> hints)
{
super(RenderingHints.VALUE_INTERPOLATION_BICUBIC, hints);
}
/**
* <p>
* Resizes an image using bicubic interpolation.
* </p>
* <p>
* If the source and/or destination image is {@code null}, then a
* {@link NullPointerException} will be thrown.
* </p>
*
* @param srcImage The source image.
* @param destImage The destination image.
*
* @throws NullPointerException When the source and/or the destination
* image is {@code null}.
*/
@Override
public void resize(BufferedImage srcImage, BufferedImage destImage)
throws NullPointerException
{
super.resize(srcImage, destImage);
}
}
| Java |
package net.coobird.thumbnailator.resizers;
import java.awt.image.BufferedImage;
/**
* This enum can be used to select a specific {@link Resizer} in order
* to perform a resizing operation.
* <p>
* The instance held by a value of this enum is a single instance. When using
* specific implementations of {@link Resizer}s, it is preferable to obtain
* an instance of a {@link Resizer} through this enum or the
* {@link DefaultResizerFactory} class in order to prevent many instances of the
* {@link Resizer} class implementations from being instantiated.
* <p>
* <DL>
* <DT><B>Usage:</B></DT>
* <DD>
* The following example code demonstrates how to use the {@link Resizers} enum
* in order to resize an image using bilinear interpolation:
* <p>
* <pre>
BufferedImage sourceImage = new BufferedImageBuilder(400, 400).build();
BufferedImage destImage = new BufferedImageBuilder(200, 200).build();
Resizers.BILINEAR.resize(sourceImage, destImage);
* </pre>
* </DD>
* </DL>
*
* @see DefaultResizerFactory
*
* @author coobird
*
*/
public enum Resizers implements Resizer
{
/**
* A {@link Resizer} which does not perform resizing operations. The source
* image will be drawn at the origin of the destination image.
*/
NULL(new NullResizer()),
/**
* A {@link Resizer} which performs resizing operations using
* bilinear interpolation.
*/
BILINEAR(new BilinearResizer()),
/**
* A {@link Resizer} which performs resizing operations using
* bicubic interpolation.
*/
BICUBIC(new BicubicResizer()),
/**
* A {@link Resizer} which performs resizing operations using
* progressive bilinear scaling.
* <p>
* For details on this technique, refer to the documentation of the
* {@link ProgressiveBilinearResizer} class.
*/
PROGRESSIVE(new ProgressiveBilinearResizer())
;
private final Resizer resizer;
private Resizers(Resizer resizer)
{
this.resizer = resizer;
}
public void resize(BufferedImage srcImage, BufferedImage destImage)
{
resizer.resize(srcImage, destImage);
}
}
| Java |
package net.coobird.thumbnailator.resizers;
import java.awt.image.BufferedImage;
/**
* This interface is implemented by classes which perform resizing operations.
*
* @author coobird
*
*/
public interface Resizer
{
/**
* Resizes an image.
* <p>
* The source image is resized to fit the dimensions of the destination
* image and drawn.
*
* @param srcImage The source image.
* @param destImage The destination image.
*/
public void resize(BufferedImage srcImage, BufferedImage destImage);
}
| Java |
package net.coobird.thumbnailator.resizers;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.image.BufferedImage;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
/**
* A class which performs a resize operation on a source image and outputs the
* result to a destination image.
*
* @author coobird
*
*/
public abstract class AbstractResizer implements Resizer
{
/**
* Rendering hints to use when resizing an image.
*/
protected final Map<RenderingHints.Key, Object> RENDERING_HINTS;
/**
* Field used to hold the rendering hints in an unmodifiable form.
*/
protected final Map<RenderingHints.Key, Object> UNMODIFIABLE_RENDERING_HINTS;
protected static final RenderingHints.Key KEY_INTERPOLATION =
RenderingHints.KEY_INTERPOLATION;
/**
* Initializes the {@link AbstractResizer}.
*
* @param interpolationValue The rendering hint value to use for the
* interpolation hint.
* @param hints Other rendering hints to add.
*/
protected AbstractResizer(
Object interpolationValue,
Map<RenderingHints.Key, Object> hints
)
{
RENDERING_HINTS = new HashMap<RenderingHints.Key, Object>();
RENDERING_HINTS.put(KEY_INTERPOLATION, interpolationValue);
if (
hints.containsKey(KEY_INTERPOLATION)
&& !interpolationValue.equals(hints.get(KEY_INTERPOLATION))
)
{
throw new IllegalArgumentException("Cannot change the " +
"RenderingHints.KEY_INTERPOLATION value.");
}
RENDERING_HINTS.putAll(hints);
UNMODIFIABLE_RENDERING_HINTS = Collections.unmodifiableMap(RENDERING_HINTS);
}
/**
* <p>
* Performs a resize operation from a source image and outputs to a
* destination image.
* </p>
* <p>
* If the source or destination image is {@code null}, then a
* {@link NullPointerException} will be thrown.
* </p>
*
* @param srcImage The source image.
* @param destImage The destination image.
*
* @throws NullPointerException When the source and/or the destination
* image is {@code null}.
*/
public void resize(BufferedImage srcImage, BufferedImage destImage)
{
performChecks(srcImage, destImage);
int width = destImage.getWidth();
int height = destImage.getHeight();
Graphics2D g = destImage.createGraphics();
g.setRenderingHints(RENDERING_HINTS);
g.drawImage(srcImage, 0, 0, width, height, null);
g.dispose();
}
/**
* Performs checks on the source and destination image to see if they are
* images which can be processed.
*
* @param srcImage The source image.
* @param destImage The destination image.
*/
protected void performChecks(BufferedImage srcImage, BufferedImage destImage)
{
if (srcImage == null || destImage == null)
{
throw new NullPointerException(
"The source and/or destination image is null."
);
}
}
/**
* Returns the rendering hints that the resizer uses.
* <p>
* The keys and values used for the rendering hints are those defined in
* the {@link RenderingHints} class.
*
* @see RenderingHints
* @return Rendering hints used when resizing the image.
*/
public Map<RenderingHints.Key, Object> getRenderingHints()
{
return UNMODIFIABLE_RENDERING_HINTS;
}
}
| Java |
package net.coobird.thumbnailator.resizers;
import java.awt.RenderingHints;
import java.awt.image.BufferedImage;
import java.util.Collections;
import java.util.Map;
/**
* Image resizer class using bilinear interpolation for the resizing operation.
*
* @author coobird
*
*/
public class BilinearResizer extends AbstractResizer
{
/**
* Instantiates a {@link BilinearResizer} with default rendering hints.
*/
public BilinearResizer()
{
this(Collections.<RenderingHints.Key, Object>emptyMap());
}
/**
* Instantiates a {@link BilinearResizer} with the specified rendering
* hints.
*
* @param hints Additional rendering hints to apply.
*/
public BilinearResizer(Map<RenderingHints.Key, Object> hints)
{
super(RenderingHints.VALUE_INTERPOLATION_BILINEAR, hints);
}
/**
* <p>
* Resizes an image using bilinear interpolation.
* </p>
* <p>
* If the source and/or destination image is {@code null}, then a
* {@link NullPointerException} will be thrown.
* </p>
*
* @param srcImage The source image.
* @param destImage The destination image.
*
* @throws NullPointerException When the source and/or the destination
* image is {@code null}.
*/
@Override
public void resize(BufferedImage srcImage, BufferedImage destImage)
throws NullPointerException
{
super.resize(srcImage, destImage);
}
}
| Java |
package net.coobird.thumbnailator.builders;
import java.awt.Dimension;
import java.awt.image.BufferedImage;
import java.util.Collections;
import java.util.List;
import net.coobird.thumbnailator.ThumbnailParameter;
import net.coobird.thumbnailator.filters.ImageFilter;
import net.coobird.thumbnailator.resizers.DefaultResizerFactory;
import net.coobird.thumbnailator.resizers.FixedResizerFactory;
import net.coobird.thumbnailator.geometry.Region;
import net.coobird.thumbnailator.resizers.Resizer;
import net.coobird.thumbnailator.resizers.ResizerFactory;
/**
* A builder for generating {@link ThumbnailParameter}.
* <p>
* The default values assigned to the {@link ThumbnailParameter} created by
* the {@link ThumbnailParameterBuilder} are as follows:
* <p>
* <dl>
* <dt>width</dt>
* <dd>Unassigned. Must be set by the {@link #size(int, int)} method.</dd>
* <dt>height</dt>
* <dd>Unassigned. Must be set by the {@link #size(int, int)} method.</dd>
* <dt>scaling factor</dt>
* <dd>Unassigned. Must be set by the {@link #scale(double)} method or
* {@link #scale(double, double)} method.</dd>
* <dt>source region</dt>
* <dd>Uses the entire source image.</dd>
* <dt>image type</dt>
* <dd>See {@link ThumbnailParameter#DEFAULT_IMAGE_TYPE}. Same as
* {@link BufferedImage#TYPE_INT_ARGB}.</dd>
* <dt>aspect ratio</dt>
* <dd>Maintain the aspect ratio of the original image.</dd>
* <dt>output quality</dt>
* <dd>See {@link ThumbnailParameter#DEFAULT_QUALITY}.</dd>
* <dt>output format</dt>
* <dd>See {@link ThumbnailParameter#ORIGINAL_FORMAT}. Maintains the same
* image format as the original image.</dd>
* <dt>output format type</dt>
* <dd>See {@link ThumbnailParameter#DEFAULT_FORMAT_TYPE}. Uses the default
* format type of the codec used to create the thumbnail image.</dd>
* <dt>image filters</dt>
* <dd>None.</dd>
* <dt>resizer factory</dt>
* <dd>{@link DefaultResizerFactory} is used.</dd>
* <dt>resizer</dt>
* <dd>The default {@link Resizer} returned by the {@link ResizerFactory}.</dd>
* <dt>use of Exif metadata for orientation</dt>
* <dd>Use the Exif metadata to determine the orientation of the thumbnail.</dd>
* </dl>
*
* @author coobird
*
*/
public final class ThumbnailParameterBuilder
{
private static final int UNINITIALIZED = -1;
private int width = UNINITIALIZED;
private int height = UNINITIALIZED;
private double widthScalingFactor = Double.NaN;
private double heightScalingFactor = Double.NaN;
private int imageType = ThumbnailParameter.DEFAULT_IMAGE_TYPE;
private boolean keepAspectRatio = true;
private float thumbnailQuality = ThumbnailParameter.DEFAULT_QUALITY;
private String thumbnailFormat = ThumbnailParameter.ORIGINAL_FORMAT;
private String thumbnailFormatType = ThumbnailParameter.DEFAULT_FORMAT_TYPE;
private List<ImageFilter> filters = Collections.emptyList();
private ResizerFactory resizerFactory = DefaultResizerFactory.getInstance();
private Region sourceRegion = null;
private boolean fitWithinDimensions = true;
private boolean useExifOrientation = true;
/**
* Creates an instance of a {@link ThumbnailParameterBuilder}.
*/
public ThumbnailParameterBuilder()
{
}
/**
* Sets the image type fo the thumbnail.
*
* @param type The image type of the thumbnail.
* @return A reference to this object.
*/
public ThumbnailParameterBuilder imageType(int type)
{
imageType = type;
return this;
}
/**
* Sets the size of the thumbnail.
*
* @param size The dimensions of the thumbnail.
* @return A reference to this object.
*/
public ThumbnailParameterBuilder size(Dimension size)
{
size(size.width, size.height);
return this;
}
/**
* Sets the size of the thumbnail.
*
* @param width The width of the thumbnail.
* @param height The height of the thumbnail.
* @return A reference to this object.
* @throws IllegalArgumentException If the widht or height is less than 0.
*/
public ThumbnailParameterBuilder size(int width, int height)
{
if (width < 0)
{
throw new IllegalArgumentException("Width must be greater than 0.");
}
if (height < 0)
{
throw new IllegalArgumentException("Height must be greater than 0.");
}
this.width = width;
this.height = height;
return this;
}
/**
* Sets the scaling factor of the thumbnail.
*
* @param scalingFactor The scaling factor of the thumbnail.
* @return A reference to this object.
* @throws IllegalArgumentException If the scaling factor is not a
* rational number, or if it is less
* than {@code 0.0}.
*/
public ThumbnailParameterBuilder scale(double scalingFactor)
{
return scale(scalingFactor, scalingFactor);
}
/**
* Sets the scaling factor of the thumbnail.
*
* @param widthScalingFactor The scaling factor to use for the width
* when creating the thumbnail.
* @param heightScalingFactor The scaling factor to use for the height
* when creating the thumbnail.
* @return A reference to this object.
* @throws IllegalArgumentException If the scaling factor is not a
* rational number, or if it is less
* than {@code 0.0}.
* @since 0.3.10
*/
public ThumbnailParameterBuilder scale(double widthScalingFactor, double heightScalingFactor)
{
if (widthScalingFactor <= 0.0 || heightScalingFactor <= 0.0)
{
throw new IllegalArgumentException("Scaling factor is less than or equal to 0.");
}
else if (Double.isNaN(widthScalingFactor) || Double.isInfinite(widthScalingFactor))
{
throw new IllegalArgumentException("Scaling factor must be a rational number.");
}
else if (Double.isNaN(heightScalingFactor) || Double.isInfinite(heightScalingFactor))
{
throw new IllegalArgumentException("Scaling factor must be a rational number.");
}
this.widthScalingFactor = widthScalingFactor;
this.heightScalingFactor = heightScalingFactor;
return this;
}
/**
* Sets the region of the source image to use when creating a thumbnail.
*
* @param sourceRegion The region of the source image to use when
* creating a thumbnail.
* @return A reference to this object.
* @since 0.3.4
*/
public ThumbnailParameterBuilder region(Region sourceRegion)
{
this.sourceRegion = sourceRegion;
return this;
}
/**
* Sets whether or not the thumbnail is to maintain the aspect ratio of
* the original image.
*
* @param keep {@code true} if the aspect ratio of the original image
* is to be maintained in the thumbnail, {@code false}
* otherwise.
* @return A reference to this object.
*/
public ThumbnailParameterBuilder keepAspectRatio(boolean keep)
{
this.keepAspectRatio = keep;
return this;
}
/**
* Sets the compression quality setting of the thumbnail.
* <p>
* An acceptable value is in the range of {@code 0.0f} to {@code 1.0f},
* where {@code 0.0f} is for the lowest quality setting and {@code 1.0f} for
* the highest quality setting.
* <p>
* If the default compression quality is to be used, then the value
* {@link ThumbnailParameter#DEFAULT_QUALITY} should be used.
*
* @param quality The compression quality setting of the thumbnail.
* @return A reference to this object.
*/
public ThumbnailParameterBuilder quality(float quality)
{
this.thumbnailQuality = quality;
return this;
}
/**
* Sets the output format of the thumbnail.
*
* @param format The output format of the thumbnail.
* @return A reference to this object.
*/
public ThumbnailParameterBuilder format(String format)
{
this.thumbnailFormat = format;
return this;
}
/**
* Sets the output format type of the thumbnail.
*
* @param formatType The output format type of the thumbnail.
* @return A reference to this object.
*/
public ThumbnailParameterBuilder formatType(String formatType)
{
this.thumbnailFormatType = formatType;
return this;
}
/**
* Sets the {@link ImageFilter}s to apply to the thumbnail.
* <p>
* These filters will be applied after the original image is resized.
*
* @param filters The output format type of the thumbnail.
* @return A reference to this object.
*/
public ThumbnailParameterBuilder filters(List<ImageFilter> filters)
{
if (filters == null)
{
throw new NullPointerException("Filters is null.");
}
this.filters = filters;
return this;
}
/**
* Sets the {@link Resizer} to use when performing the resizing operation
* to create the thumbnail.
* <p>
* Calling this method after {@link #resizerFactory(ResizerFactory)} will
* cause the {@link ResizerFactory} used by the resulting
* {@link ThumbnailParameter} to only return the specified {@link Resizer}.
*
* @param resizer The {@link Resizer} to use when creating the
* thumbnail.
* @return A reference to this object.
*/
public ThumbnailParameterBuilder resizer(Resizer resizer)
{
if (resizer == null)
{
throw new NullPointerException("Resizer is null.");
}
this.resizerFactory = new FixedResizerFactory(resizer);
return this;
}
/**
* Sets the {@link ResizerFactory} to use to obtain a {@link Resizer} when
* performing the resizing operation to create the thumbnail.
* <p>
* Calling this method after {@link #resizer(Resizer)} could result in
* {@link Resizer}s not specified in the {@code resizer} method to be used
* when creating thumbnails.
*
*
* @param resizerFactory The {@link ResizerFactory} to use when obtaining
* a {@link Resizer} to create the thumbnail.
* @return A reference to this object.
* @since 0.4.0
*/
public ThumbnailParameterBuilder resizerFactory(ResizerFactory resizerFactory)
{
if (resizerFactory == null)
{
throw new NullPointerException("Resizer is null.");
}
this.resizerFactory = resizerFactory;
return this;
}
/**
* Sets whether or not the thumbnail should fit within the specified
* dimensions.
*
* @param fit {@code true} if the thumbnail should be sized to fit
* within the specified dimensions, if the thumbnail
* is going to exceed those dimensions.
* @return A reference to this object.
* @since 0.4.0
*/
public ThumbnailParameterBuilder fitWithinDimensions(boolean fit)
{
this.fitWithinDimensions = fit;
return this;
}
/**
* Sets whether or not the Exif metadata should be used to determine the
* orientation of the thumbnail.
*
* @param use {@code true} if the Exif metadata should be used
* to determine the orientation of the thumbnail,
* {@code false} otherwise.
* @return A reference to this object.
* @since 0.4.3
*/
public ThumbnailParameterBuilder useExifOrientation(boolean use)
{
this.useExifOrientation = use;
return this;
}
/**
* Returns a {@link ThumbnailParameter} from the parameters which are
* currently set.
* <p>
* This method will throw a {@link IllegalArgumentException} required
* parameters for the {@link ThumbnailParameter} have not been set.
*
* @return A {@link ThumbnailParameter} with parameters set through
* the use of this builder.
* @throws IllegalStateException If neither the size nor the scaling
* factor has been set.
*/
public ThumbnailParameter build()
{
if (!Double.isNaN(widthScalingFactor))
{
// If scaling factor has been set.
return new ThumbnailParameter(
widthScalingFactor,
heightScalingFactor,
sourceRegion,
keepAspectRatio,
thumbnailFormat,
thumbnailFormatType,
thumbnailQuality,
imageType,
filters,
resizerFactory,
fitWithinDimensions,
useExifOrientation
);
}
else if (width != UNINITIALIZED && height != UNINITIALIZED)
{
return new ThumbnailParameter(
new Dimension(width, height),
sourceRegion,
keepAspectRatio,
thumbnailFormat,
thumbnailFormatType,
thumbnailQuality,
imageType,
filters,
resizerFactory,
fitWithinDimensions,
useExifOrientation
);
}
else
{
throw new IllegalStateException(
"The size nor the scaling factor has been set."
);
}
}
}
| Java |
package net.coobird.thumbnailator.builders;
import java.awt.Dimension;
import java.awt.image.BufferedImage;
/**
* A builder for creating {@link BufferedImage} with specified parameters.
*
* @author coobird
*
*/
public final class BufferedImageBuilder
{
/**
* The default image type of the {@link BufferedImage}s to be created
* by this builder.
*/
private static final int DEFAULT_TYPE = BufferedImage.TYPE_INT_ARGB;
/**
* The image type to use for the {@link BufferedImage} that is to be
* created.
*/
private int imageType;
/**
* The width to use for the {@link BufferedImage} that is to be created.
*/
private int width;
/**
* The height to use for the {@link BufferedImage} that is to be created.
*/
private int height;
/**
* Instantiates a {@code BufferedImageBuilder} with the specified size, and
* the default image type.
*
* @param size The size of the {@link BufferedImage} to build.
*/
public BufferedImageBuilder(Dimension size)
{
this(size.width, size.height);
}
/**
* Instantiates a {@code BufferedImageBuilder} with the specified size and
* image type.
*
* @param size The size of the {@link BufferedImage} to build.
* @param imageType The image type of the {@link BufferedImage} to build.
*/
public BufferedImageBuilder(Dimension size, int imageType)
{
this(size.width, size.height, imageType);
}
/**
* Instantiates a {@code BufferedImageBuilder} with the specified size, and
* the default image type.
*
* @param width The width of the {@link BufferedImage} to build.
* @param height The height of the {@link BufferedImage} to build.
*/
public BufferedImageBuilder(int width, int height)
{
this(width, height, DEFAULT_TYPE);
}
/**
* Instantiates a {@code BufferedImageBuilder} with the specified size and
* image type.
*
* @param width The width of the {@link BufferedImage} to build.
* @param height The height of the {@link BufferedImage} to build.
* @param imageType The image type of the {@link BufferedImage} to build.
*/
public BufferedImageBuilder(int width, int height, int imageType)
{
size(width, height);
imageType(imageType);
}
/**
* Generates a new {@code BufferedImage}.
*
* @return Returns a newly created {@link BufferedImage} from the
* parameters set in the {@link BufferedImageBuilder}.
*/
public BufferedImage build()
{
return new BufferedImage(width, height, imageType);
}
/**
* Sets the type of the image of the {@link BufferedImage}.
*
* @param imageType The image type to use.
* @return This {@link BufferedImageBuilder} instance.
*/
public BufferedImageBuilder imageType(int imageType)
{
this.imageType = imageType;
return this;
}
/**
* Sets the size for the {@code BufferedImage}.
*
* @param width The width of the image to create.
* @param height The height of the image to create.
* @return This {@link BufferedImageBuilder} instance.
*/
public BufferedImageBuilder size(int width, int height)
{
width(width);
height(height);
return this;
}
/**
* Sets the width for the {@link BufferedImage}.
*
* @param width The width of the image to create.
* @return This {@link BufferedImageBuilder} instance.
*/
public BufferedImageBuilder width(int width)
{
if (width <= 0)
{
throw new IllegalArgumentException(
"Width must be greater than 0."
);
}
this.width = width;
return this;
}
/**
* Sets the height for the {@link BufferedImage}.
*
* @param height The height of the image to create.
* @return This {@link BufferedImageBuilder} instance.
*/
public BufferedImageBuilder height(int height)
{
if (height <= 0)
{
throw new IllegalArgumentException(
"Height must be greater than 0."
);
}
this.height = height;
return this;
}
}
| Java |
/**
* This package provides classes which provides convenient builders for classes
* which are used by Thumbnailator.
*/
package net.coobird.thumbnailator.builders;
| Java |
package net.coobird.thumbnailator.filters;
import java.awt.image.BufferedImage;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import net.coobird.thumbnailator.util.BufferedImages;
/**
* An {@link ImageFilter} which will apply multiple {@link ImageFilter}s in a
* specific order.
*
* @author coobird
*
*/
public final class Pipeline implements ImageFilter
{
/**
* A list of image filters to apply.
*/
private final List<ImageFilter> filtersToApply;
/**
* An unmodifiable list of image filters to apply.
* Used by the {@link #getFilters()} method.
*
* This object is created by Collections.unmodifiableList which provides
* an unmodifiable view of the original list.
*
* Therefore, any changes to the original list will also be "visible" from
* this list as well.
*/
private final List<ImageFilter> unmodifiableFiltersToApply;
/**
* Instantiates a new {@link Pipeline} with no image filters to apply.
*/
public Pipeline()
{
this(Collections.<ImageFilter>emptyList());
}
/**
* Instantiates a new {@link Pipeline} with an array of {@link ImageFilter}s
* to apply.
*
* @param filters An array of {@link ImageFilter}s to apply.
*/
public Pipeline(ImageFilter... filters)
{
this(Arrays.asList(filters));
}
/**
* Instantiates a new {@link Pipeline} with a list of {@link ImageFilter}s
* to apply.
*
* @param filters A list of {@link ImageFilter}s to apply.
*/
public Pipeline(List<ImageFilter> filters)
{
if (filters == null)
{
throw new NullPointerException("Cannot instantiate with a null" +
"list of image filters.");
}
filtersToApply = new ArrayList<ImageFilter>(filters);
unmodifiableFiltersToApply =
Collections.unmodifiableList(filtersToApply);
}
/**
* Adds an {@code ImageFilter} to the pipeline.
*/
public void add(ImageFilter filter)
{
if (filter == null)
{
throw new NullPointerException("An image filter must not be null.");
}
filtersToApply.add(filter);
}
/**
* Adds an {@code ImageFilter} to the beginning of the pipeline.
*/
public void addFirst(ImageFilter filter)
{
if (filter == null)
{
throw new NullPointerException("An image filter must not be null.");
}
filtersToApply.add(0, filter);
}
/**
* Adds a {@code List} of {@code ImageFilter}s to the pipeline.
*
* @param filters A list of filters to add to the pipeline.
*/
public void addAll(List<ImageFilter> filters)
{
if (filters == null)
{
throw new NullPointerException("A list of image filters must not be null.");
}
filtersToApply.addAll(filters);
}
/**
* Returns a list of {@link ImageFilter}s which will be applied by this
* {@link Pipeline}.
*
* @return A list of filters which are applied by this
* pipeline.
*/
public List<ImageFilter> getFilters()
{
return unmodifiableFiltersToApply;
}
public BufferedImage apply(BufferedImage img)
{
if (filtersToApply.isEmpty())
{
return img;
}
BufferedImage image = BufferedImages.copy(img);
for (ImageFilter filter : filtersToApply)
{
image = filter.apply(image);
}
return image;
}
}
| Java |
package net.coobird.thumbnailator.filters;
import java.awt.image.BufferedImage;
/**
* This interface is to be implemented by classes which performs an image
* filtering operation on a {@link BufferedImage}.
* <p>
* The general contract for classes implementing {@link ImageFilter} is that
* they should not change the contents of the {@link BufferedImage} which is
* given as the argument for the {@link #apply(BufferedImage)} method.
* <p>
* The filter should make a copy of the given {@link BufferedImage}, and
* perform the filtering operations on the copy, then return the copy.
*
* @author coobird
*
*/
public interface ImageFilter
{
/**
* Applies a image filtering operation on an image.
*
* @param img The image to apply the filtering on.
* @return The resulting image after applying this filter.
*/
public BufferedImage apply(BufferedImage img);
}
| Java |
package net.coobird.thumbnailator.filters;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import net.coobird.thumbnailator.builders.BufferedImageBuilder;
/**
* An image filter which will add a color tint to an image.
*
* @author coobird
*
*/
public final class Colorize implements ImageFilter
{
/**
* The color to tint a target image with.
*/
private final Color c;
/**
* Instantiates this filter with the color to use to tint the target image
* with.
* <p>
* Note: If the provided {@link Color} does not have an alpha channel
* (transparency channel), then the target image will be painted with an
* opaque color, resulting in an image with only the specified color.
*
* @param c Color to tint with.
*/
public Colorize(Color c)
{
this.c = c;
}
/**
* Instantiates this filter with the color to use to tint the target image
* with and the transparency level provided as a {@code float} ranging from
* {@code 0.0f} to {@code 1.0f}, where {@code 0.0f} indicates completely
* transparent, and {@code 1.0f} indicates completely opaque.
*
* @param c Color to tint with.
* @param alpha The opacity of the tint.
*/
public Colorize(Color c, float alpha)
{
this(c, (int)(255 * alpha));
}
/**
* Instantiates this filter with the color to use to tint the target image
* with and the transparency level provided as a {@code int} ranging from
* {@code 0} to {@code 255}, where {@code 0} indicates completely
* transparent, and {@code 255} indicates completely opaque.
*
* @param c Color to tint with.
* @param alpha The opacity of the tint.
*/
public Colorize(Color c, int alpha)
{
if (alpha > 255 || alpha < 0)
{
throw new IllegalArgumentException(
"Specified alpha value is outside the range of allowed " +
"values.");
}
int r = c.getRed();
int g = c.getGreen();
int b = c.getBlue();
int a = alpha;
this.c = new Color(r, g, b, a);
}
public BufferedImage apply(BufferedImage img)
{
int width = img.getWidth();
int height = img.getHeight();
BufferedImage newImage = new BufferedImageBuilder(width, height).build();
Graphics2D g = newImage.createGraphics();
g.drawImage(img, 0, 0, null);
g.setColor(c);
g.fillRect(0, 0, width, height);
g.dispose();
return newImage;
}
}
| Java |
package net.coobird.thumbnailator.filters;
import java.awt.AlphaComposite;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.image.BufferedImage;
import net.coobird.thumbnailator.geometry.Position;
import net.coobird.thumbnailator.util.BufferedImages;
/**
* An {@link ImageFilter} which will overlay a text caption to an image.
*
* @author coobird
*
*/
public class Caption implements ImageFilter
{
/**
* The text of the caption.
*/
private final String caption;
/**
* The font of text to add.
*/
private final Font font;
/**
* The color of the text to add.
*/
private final Color c;
/**
* The opacity level of the text to add.
* <p>
* The value should be between {@code 0.0f} to {@code 1.0f}, where
* {@code 0.0f} is completely transparent, and {@code 1.0f} is completely
* opaque.
*/
private final float alpha;
/**
* The position at which the text should be drawn.
*/
private final Position position;
/**
* The insets for the text to draw.
*/
private final int insets;
/**
* Instantiates a filter which adds a text caption to an image.
*
* @param caption The text of the caption.
* @param font The font of the caption.
* @param c The color of the caption.
* @param alpha The opacity level of caption.
* <p>
* The value should be between {@code 0.0f} and
* {@code 1.0f}, where {@code 0.0f} is completely
* transparent, and {@code 1.0f} is completely opaque.
* @param position The position of the caption.
* @param insets The inset size around the caption.
*/
public Caption(String caption, Font font, Color c, float alpha,
Position position, int insets)
{
this.caption = caption;
this.font = font;
this.c = c;
this.alpha = alpha;
this.position = position;
this.insets = insets;
}
/**
* Instantiates a filter which adds a text caption to an image.
* <p>
* The opacity of the caption will be 100% opaque.
*
* @param caption The text of the caption.
* @param font The font of the caption.
* @param c The color of the caption.
* @param position The position of the caption.
* @param insets The inset size around the caption.
*/
public Caption(String caption, Font font, Color c, Position position,
int insets)
{
this.caption = caption;
this.font = font;
this.c = c;
this.alpha = 1.0f;
this.position = position;
this.insets = insets;
}
public BufferedImage apply(BufferedImage img)
{
BufferedImage newImage = BufferedImages.copy(img);
Graphics2D g = newImage.createGraphics();
g.setFont(font);
g.setColor(c);
g.setComposite(
AlphaComposite.getInstance(AlphaComposite.SRC_OVER, alpha)
);
int imageWidth = img.getWidth();
int imageHeight = img.getHeight();
int captionWidth = g.getFontMetrics().stringWidth(caption);
int captionHeight = g.getFontMetrics().getHeight() / 2;
Point p = position.calculate(
imageWidth, imageHeight, captionWidth, 0,
insets, insets, insets, insets
);
double yRatio = p.y / (double)img.getHeight();
int yOffset = (int)((1.0 - yRatio) * captionHeight);
g.drawString(caption, p.x, p.y + yOffset);
g.dispose();
return newImage;
}
}
| Java |
package net.coobird.thumbnailator.filters;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import net.coobird.thumbnailator.builders.BufferedImageBuilder;
/**
* A class containing flip transformation filters.
*
* @author coobird
*
*/
public class Flip {
/**
* An image filter which performs a horizontal flip of the image.
*/
public static final ImageFilter HORIZONTAL = new ImageFilter() {
public BufferedImage apply(BufferedImage img) {
int width = img.getWidth();
int height = img.getHeight();
BufferedImage newImage =
new BufferedImageBuilder(width, height).build();
Graphics g = newImage.getGraphics();
g.drawImage(img, width, 0, 0, height, 0, 0, width, height, null);
g.dispose();
return newImage;
};
};
/**
* An image filter which performs a vertical flip of the image.
*/
public static final ImageFilter VERTICAL = new ImageFilter() {
public BufferedImage apply(BufferedImage img) {
int width = img.getWidth();
int height = img.getHeight();
BufferedImage newImage =
new BufferedImageBuilder(width, height).build();
Graphics g = newImage.getGraphics();
g.drawImage(img, 0, height, width, 0, 0, 0, width, height, null);
g.dispose();
return newImage;
};
};
}
| Java |
package net.coobird.thumbnailator.filters;
import java.awt.AlphaComposite;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.image.BufferedImage;
import net.coobird.thumbnailator.builders.BufferedImageBuilder;
import net.coobird.thumbnailator.geometry.Position;
/**
* This class applies a watermark to an image.
*
* @author coobird
*
*/
public class Watermark implements ImageFilter
{
/**
* The position of the watermark.
*/
private final Position position;
/**
* The watermark image.
*/
private final BufferedImage watermarkImg;
/**
* The opacity of the watermark.
*/
private final float opacity;
/**
* Instantiates a filter which applies a watermark to an image.
*
* @param position The position of the watermark.
* @param watermarkImg The watermark image.
* @param opacity The opacity of the watermark.
* <p>
* The value should be between {@code 0.0f} and
* {@code 1.0f}, where {@code 0.0f} is completely
* transparent, and {@code 1.0f} is completely
* opaque.
*/
public Watermark(Position position, BufferedImage watermarkImg,
float opacity)
{
if (position == null)
{
throw new NullPointerException("Position is null.");
}
if (watermarkImg == null)
{
throw new NullPointerException("Watermark image is null.");
}
if (opacity > 1.0f || opacity < 0.0f)
{
throw new IllegalArgumentException("Opacity is out of range of " +
"between 0.0f and 1.0f.");
}
this.position = position;
this.watermarkImg = watermarkImg;
this.opacity = opacity;
}
public BufferedImage apply(BufferedImage img)
{
int width = img.getWidth();
int height = img.getHeight();
int type = img.getType();
BufferedImage imgWithWatermark =
new BufferedImageBuilder(width, height, type).build();
int watermarkWidth = watermarkImg.getWidth();
int watermarkHeight = watermarkImg.getHeight();
Point p = position.calculate(
width, height, watermarkWidth, watermarkHeight,
0, 0, 0, 0
);
Graphics2D g = imgWithWatermark.createGraphics();
// Draw the actual image.
g.drawImage(img, 0, 0, null);
// Draw the watermark on top.
g.setComposite(
AlphaComposite.getInstance(AlphaComposite.SRC_OVER, opacity)
);
g.drawImage(watermarkImg, p.x, p.y, null);
g.dispose();
return imgWithWatermark;
}
}
| Java |
/**
* This package provides classes which perform filtering operations on images,
* such as adding watermark, text captions, and color tints.
*/
package net.coobird.thumbnailator.filters;
| Java |
package net.coobird.thumbnailator.filters;
import java.awt.AlphaComposite;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
/**
* An image filter which will make an image transparent.
* <p>
* The resulting image will always have an image type of
* {@link BufferedImage#TYPE_INT_ARGB}.
*
* @author coobird
*
*/
public class Transparency implements ImageFilter
{
/**
* The alpha composite to use when drawing the transparent image.
*/
private final AlphaComposite composite;
/**
* Instantiates a {@link Transparency} filter with the specified opacity.
*
* @param alpha The opacity of the resulting image. The value should be
* between {@code 0.0f} (transparent) to {@code 1.0f}
* (opaque), inclusive.
* @throws IllegalArgumentException If the specified opacity is outside of
* the range specified above.
*/
public Transparency(float alpha)
{
super();
if (alpha < 0.0f || alpha > 1.0f)
{
throw new IllegalArgumentException(
"The alpha must be between 0.0f and 1.0f, inclusive.");
}
this.composite = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, alpha);
}
/**
* Instantiates a {@link Transparency} filter with the specified opacity.
* <p>
* This is a convenience constructor for the
* {@link Transparency#Transparency(float)} constructor.
*
* @param alpha The opacity of the resulting image. The value should be
* between {@code 0.0f} (transparent) to {@code 1.0f}
* (opaque), inclusive.
* @throws IllegalArgumentException If the specified opacity is outside of
* the range specified above.
*/
public Transparency(double alpha)
{
this((float)alpha);
}
public BufferedImage apply(BufferedImage img)
{
int width = img.getWidth();
int height = img.getHeight();
BufferedImage finalImage =
new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
Graphics2D g = finalImage.createGraphics();
g.setComposite(composite);
g.drawImage(img, 0, 0, null);
g.dispose();
return finalImage;
}
/**
* Returns the opacity of this filter.
*
* @return The opacity in the range of {@code 0.0f} (transparent) to
* {@code 1.0f} (opaque).
*/
public float getAlpha()
{
return composite.getAlpha();
}
}
| Java |
package net.coobird.thumbnailator.filters;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.image.BufferedImage;
import net.coobird.thumbnailator.builders.BufferedImageBuilder;
/**
* A class containing rotation filters.
* <p>
* Aside from the three {@link Rotator}s provided as class constants, a
* {@link Rotator} which performs a rotation by an arbituary angle can be
* obtained through the {@link Rotation#newRotator(double)} method.
*
* @author coobird
*
*/
public class Rotation
{
/**
* This class is not intended to be instantiated.
*/
private Rotation() {}
/**
* An {@link ImageFilter} which applies a rotation to an image.
* <p>
* An instance of a {@link Rotator} can be obtained through the
* {@link Rotation#newRotator(double)} method.
*
* @author coobird
*
*/
public abstract static class Rotator implements ImageFilter
{
/**
* This class is not intended to be instantiated.
*/
private Rotator() {}
}
/**
* Creates a new instance of {@code Rotator} which rotates an image at
* the specified angle.
* <p>
* When the {@link Rotator} returned by this method is applied, the image
* will be rotated clockwise by the specified angle.
*
* @param angle The angle at which the instance of {@code Rotator}
* is to rotate a image it acts upon.
* @return An instance of {@code Rotator} which will rotate
* a given image.
*/
public static Rotator newRotator(final double angle)
{
Rotator r = new Rotator() {
private double[] calculatePosition(double x, double y, double angle)
{
angle = Math.toRadians(angle);
double nx = (Math.cos(angle) * x) - (Math.sin(angle) * y);
double ny = (Math.sin(angle) * x) + (Math.cos(angle) * y);
return new double[] {nx, ny};
}
public BufferedImage apply(BufferedImage img)
{
int width = img.getWidth();
int height = img.getHeight();
BufferedImage newImage;
double[][] newPositions = new double[4][];
newPositions[0] = calculatePosition(0, 0, angle);
newPositions[1] = calculatePosition(width, 0, angle);
newPositions[2] = calculatePosition(0, height, angle);
newPositions[3] = calculatePosition(width, height, angle);
double minX = Math.min(
Math.min(newPositions[0][0], newPositions[1][0]),
Math.min(newPositions[2][0], newPositions[3][0])
);
double maxX = Math.max(
Math.max(newPositions[0][0], newPositions[1][0]),
Math.max(newPositions[2][0], newPositions[3][0])
);
double minY = Math.min(
Math.min(newPositions[0][1], newPositions[1][1]),
Math.min(newPositions[2][1], newPositions[3][1])
);
double maxY = Math.max(
Math.max(newPositions[0][1], newPositions[1][1]),
Math.max(newPositions[2][1], newPositions[3][1])
);
int newWidth = (int)Math.round(maxX - minX);
int newHeight = (int)Math.round(maxY - minY);
newImage = new BufferedImageBuilder(newWidth, newHeight).build();
Graphics2D g = newImage.createGraphics();
/*
* TODO consider RenderingHints to use.
* The following are hints which have been chosen to give
* decent image quality. In the future, there may be a need
* to have a way to change these settings.
*/
g.setRenderingHint(
RenderingHints.KEY_INTERPOLATION,
RenderingHints.VALUE_INTERPOLATION_BILINEAR
);
g.setRenderingHint(
RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON
);
double w = newWidth / 2.0;
double h = newHeight / 2.0;
g.rotate(Math.toRadians(angle), w, h);
int centerX = (int)Math.round((newWidth - width) / 2.0);
int centerY = (int)Math.round((newHeight - height) / 2.0);
g.drawImage(img, centerX, centerY, null);
g.dispose();
return newImage;
}
};
return r;
}
/**
* A {@code Rotator} which will rotate a specified image to the left 90
* degrees.
*/
public static final Rotator LEFT_90_DEGREES = newRotator(-90);
/**
* A {@code Rotator} which will rotate a specified image to the right 90
* degrees.
*/
public static final Rotator RIGHT_90_DEGREES = newRotator(90);
/**
* A {@code Rotator} which will rotate a specified image to the 180 degrees.
*/
public static final Rotator ROTATE_180_DEGREES = newRotator(180);
}
| Java |
package net.coobird.thumbnailator.filters;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Point;
import java.awt.image.BufferedImage;
import net.coobird.thumbnailator.geometry.Position;
/**
* An {@link ImageFilter} which will enclose an image into a specified
* enclosing image.
* <p>
* The intended use of this {@code ImageFilter} is to take an image and place
* it inside of a larger image, creating a border around the original image.
* This can be useful when the dimensions of a thumbnail must always be the
* same dimensions, and the original images are of differing dimensions.
* <p>
* The fill color used for the enclosing image can be specified, along with
* whether or not to crop an image if it is larger than the enclosing image.
*
* @author coobird
* @since 0.3.2
*
*/
public class Canvas implements ImageFilter
{
/**
* The width of the enclosing image.
*/
private final int width;
/**
* The width of the enclosing image.
*/
private final int height;
/**
* The positioning of the enclosed image.
*/
private final Position position;
/**
* The fill color for the background.
*/
private final Color fillColor;
/**
* Whether or not to crop the enclosed image if the enclosing image is
* smaller than the enclosed image.
*/
private final boolean crop;
/**
* Instantiates a {@code Canvas} filter.
* <p>
* No fill color will be applied to the filtered image. If the image to
* filter does not have a transparency channel, the image will be filled
* black.
* <p>
* Crops the enclosed image if the enclosing image is smaller.
*
* @param width The width of the filtered image.
* @param height The height of the filtered image.
* @param position The position to place the enclosed image.
*/
public Canvas(int width, int height, Position position)
{
this(width, height, position, true, null);
}
/**
* Instantiates a {@code Canvas} filter.
* <p>
* No fill color will be applied to the filtered image. If the image to
* filter does not have a transparency channel, the image will be filled
* black.
*
* @param width The width of the filtered image.
* @param height The height of the filtered image.
* @param position The position to place the enclosed image.
* @param crop Whether or not to crop the enclosed image if the
* enclosed image has dimensions which are larger than
* the specified {@code width} and {@code height}.
*/
public Canvas(int width, int height, Position position, boolean crop)
{
this(width, height, position, crop, null);
}
/**
* Instantiates a {@code Canvas} filter.
* <p>
* Crops the enclosed image if the enclosing image is smaller.
*
* @param width The width of the filtered image.
* @param height The height of the filtered image.
* @param position The position to place the enclosed image.
* @param fillColor The color to fill portions of the image which is
* not covered by the enclosed image. Portions of the
* image which is transparent will be filled with
* the specified color as well.
*/
public Canvas(int width, int height, Position position, Color fillColor)
{
this(width, height, position, true, fillColor);
}
/**
* Instantiates a {@code Canvas} filter.
*
* @param width The width of the filtered image.
* @param height The height of the filtered image.
* @param position The position to place the enclosed image.
* @param crop Whether or not to crop the enclosed image if the
* enclosed image has dimensions which are larger than
* the specified {@code width} and {@code height}.
* @param fillColor The color to fill portions of the image which is
* not covered by the enclosed image. Portions of the
* image which is transparent will be filled with
* the specified color as well.
*/
public Canvas(int width, int height, Position position, boolean crop, Color fillColor)
{
super();
this.width = width;
this.height = height;
this.position = position;
this.crop = crop;
this.fillColor = fillColor;
}
public BufferedImage apply(BufferedImage img)
{
int widthToUse = width;
int heightToUse = height;
/*
* To prevent cropping when cropping is disabled, if the dimension of
* the enclosed image exceeds the dimension of the enclosing image,
* then the enclosing image will have its dimension enlarged.
*
*/
if (!crop && img.getWidth() > width)
{
widthToUse = img.getWidth();
}
if (!crop && img.getHeight() > height)
{
heightToUse = img.getHeight();
}
Point p = position.calculate(
widthToUse, heightToUse, img.getWidth(), img.getHeight(),
0, 0, 0, 0
);
BufferedImage finalImage =
new BufferedImage(widthToUse, heightToUse, img.getType());
Graphics g = finalImage.getGraphics();
if (fillColor == null && !img.getColorModel().hasAlpha())
{
/*
* Fulfills the specification to use a black fill color for images
* w/o alpha, if the fill color isn't specified.
*/
g.setColor(Color.black);
g.fillRect(0, 0, width, height);
}
else if (fillColor != null)
{
g.setColor(fillColor);
g.fillRect(0, 0, widthToUse, heightToUse);
}
g.drawImage(img, p.x, p.y, null);
g.dispose();
return finalImage;
}
}
| Java |
package net.coobird.thumbnailator.name;
import net.coobird.thumbnailator.ThumbnailParameter;
/**
* This class is used to rename file names.
*
* @author coobird
*
*/
public abstract class Rename
{
/**
* A {@code Rename} which does not alter the given file name.
* <p>
* Note: The {@link #apply(String, ThumbnailParameter)} method does not use
* the {@code param} parameter. A value of {@code null} for {@code param} is
* permitted.
* <p>
* <dt>Example</dt>
* <ul>
* <li>Before: {@code picture.jpg}</li>
* <li>After: {@code picture.jpg}</li>
* </ul>
*/
public static final Rename NO_CHANGE = new Rename() {
@Override
public String apply(String name, ThumbnailParameter param)
{
return name;
}
};
/**
* Appends {@code thumbnail.} to the beginning of the file name.
* <p>
* Note: The {@link #apply(String, ThumbnailParameter)} method does not use
* the {@code param} parameter. A value of {@code null} for {@code param} is
* permitted.
* <p>
* <dt>Example</dt>
* <ul>
* <li>Before: {@code picture.jpg}</li>
* <li>After: {@code thumbnail.picture.jpg}</li>
* </ul>
*/
public static final Rename PREFIX_DOT_THUMBNAIL = new Rename() {
@Override
public String apply(String fileName, ThumbnailParameter param)
{
return appendPrefix(fileName, "thumbnail.");
}
};
/**
* Appends {@code thumbnail-} to the beginning of the file name.
* <p>
* Note: The {@link #apply(String, ThumbnailParameter)} method does not use
* the {@code param} parameter. A value of {@code null} for {@code param} is
* permitted.
* <p>
* <dt>Example</dt>
* <ul>
* <li>Before: {@code picture.jpg}</li>
* <li>After: {@code thumbnail-picture.jpg}</li>
* </ul>
*
* @deprecated Please use the correctly spelled
* {@link Rename#PREFIX_HYPHEN_THUMBNAIL}. This constant
* will be removed in Thumbnailator 0.5.0.
*/
@Deprecated
public static final Rename PREFIX_HYPTHEN_THUMBNAIL = Rename.PREFIX_HYPHEN_THUMBNAIL;
/**
* Appends {@code thumbnail-} to the beginning of the file name.
* <p>
* Note: The {@link #apply(String, ThumbnailParameter)} method does not use
* the {@code param} parameter. A value of {@code null} for {@code param} is
* permitted.
* <p>
* <dt>Example</dt>
* <ul>
* <li>Before: {@code picture.jpg}</li>
* <li>After: {@code thumbnail-picture.jpg}</li>
* </ul>
*/
public static final Rename PREFIX_HYPHEN_THUMBNAIL = new Rename() {
@Override
public String apply(String fileName, ThumbnailParameter param)
{
return appendPrefix(fileName, "thumbnail-");
}
};
/**
* Appends {@code .thumbnail} to the file name prior to the extension of
* the file.
* <p>
* Note: The {@link #apply(String, ThumbnailParameter)} method does not use
* the {@code param} parameter. A value of {@code null} for {@code param} is
* permitted.
* <p>
* <dt>Example</dt>
* <ul>
* <li>Before: {@code picture.jpg}</li>
* <li>After: {@code picture.thumbnail.jpg}</li>
* </ul>
*/
public static final Rename SUFFIX_DOT_THUMBNAIL = new Rename() {
@Override
public String apply(String fileName, ThumbnailParameter param)
{
return appendSuffix(fileName, ".thumbnail");
}
};
/**
* Appends {@code -thumbnail} to the file name prior to the extension of
* the file.
* <p>
* Note: The {@link #apply(String, ThumbnailParameter)} method does not use
* the {@code param} parameter. A value of {@code null} for {@code param} is
* permitted.
* <p>
* <dt>Example</dt>
* <ul>
* <li>Before: {@code picture.jpg}</li>
* <li>After: {@code picture-thumbnail.jpg}</li>
* </ul>
*
* @deprecated Please use the correctly spelled
* {@link Rename#SUFFIX_HYPHEN_THUMBNAIL}. This constant
* will be removed in Thumbnailator 0.5.0.
*/
@Deprecated
public static final Rename SUFFIX_HYPTHEN_THUMBNAIL = Rename.SUFFIX_HYPHEN_THUMBNAIL;
/**
* Appends {@code -thumbnail} to the file name prior to the extension of
* the file.
* <p>
* Note: The {@link #apply(String, ThumbnailParameter)} method does not use
* the {@code param} parameter. A value of {@code null} for {@code param} is
* permitted.
* <p>
* <dt>Example</dt>
* <ul>
* <li>Before: {@code picture.jpg}</li>
* <li>After: {@code picture-thumbnail.jpg}</li>
* </ul>
*/
public static final Rename SUFFIX_HYPHEN_THUMBNAIL = new Rename() {
@Override
public String apply(String fileName, ThumbnailParameter param)
{
return appendSuffix(fileName, "-thumbnail");
}
};
/**
* The default constructor is intended only to be called implicitly
* by the classes implementing the functionality of the {@link Rename}
* class.
*/
protected Rename() {}
/**
* Applies the function performed by this {@code Rename} on the
* specified name and thumbnail creation parameters.
*
* @param name Name to apply the function on.
* <em>The file name should not include the directory
* in which the file resides in.</em>
* @param param Parameters used to create the thumbnail.
* @return The name after the function has been applied.
*/
public abstract String apply(String name, ThumbnailParameter param);
/**
* Appends a suffix to a filename.
*
* @param fileName File name to add a suffix on.
* @param suffix The suffix to add.
* @return File name with specified suffixed affixed.
*/
protected String appendSuffix(String fileName, String suffix)
{
String newFileName = "";
int indexOfDot = fileName.lastIndexOf('.');
if (indexOfDot != -1)
{
newFileName = fileName.substring(0, indexOfDot);
newFileName += suffix;
newFileName += fileName.substring(indexOfDot);
}
else
{
newFileName = fileName + suffix;
}
return newFileName;
}
/**
* Appends a prefix to a filename.
*
* @param fileName File name to add a prefix on.
* @param prefix The prefix to add.
* @return File name with the specified prefix affixed.
*/
protected String appendPrefix(String fileName, String prefix)
{
return prefix + fileName;
}
}
| Java |
/**
* This package contains classes used to generate file names when saving
* thumbnail images to files.
*/
package net.coobird.thumbnailator.name;
| Java |
package net.coobird.thumbnailator.name;
import java.io.File;
import java.io.IOException;
import java.util.Formatter;
import java.util.Iterator;
/**
* This class is used to produce file names based on a given format string
* and an internal counter which increments every time a new file name
* is produced.
*
* @author coobird
*
*/
public class ConsecutivelyNumberedFilenames implements Iterable<File>
{
/**
* The iterator to return upon the {@link #iterator()} method being called.
*/
private final Iterator<File> iter;
/**
* Instantiates an {@code ConsecutivelyNumberedFilenames} object which
* returns {@link File}s with file names which are consecutively numbered
* beginning from {@code 0}.
* <p>
* <h3>File name sequence</h3>
* <ol>
* <li><code>0</code></li>
* <li><code>1</code></li>
* <li><code>2</code></li>
* <li><code>3</code></li>
* </ol>
* and so on.
*/
public ConsecutivelyNumberedFilenames()
{
this.iter = new ConsecutivelyNumberedFilenamesIterator(new File("").getParentFile(), "%d", 0);
}
/**
* Instantiates an {@code ConsecutivelyNumberedFilenames} object which
* returns {@link File}s with file names which are consecutively numbered
* beginning from the given value.
* <p>
* <h3>File name sequence</h3>
* For a case where the given value is {@code 5}:
* <ol>
* <li><code>5</code></li>
* <li><code>6</code></li>
* <li><code>7</code></li>
* <li><code>8</code></li>
* </ol>
* and so on.
*
* @param start The value from which to start counting.
*/
public ConsecutivelyNumberedFilenames(int start)
{
this.iter = new ConsecutivelyNumberedFilenamesIterator(new File("").getParentFile(), "%d", start);
}
/**
* Instantiates an {@code ConsecutivelyNumberedFilenames} object which
* returns {@link File}s with file names which are consecutively numbered
* beginning from {@code 0}, with the directory specified.
* <p>
* <h3>File name sequence</h3>
* For a case where the parent directory is {@code /foo/bar/}:
* <ol>
* <li><code>/foo/bar/0</code></li>
* <li><code>/foo/bar/1</code></li>
* <li><code>/foo/bar/2</code></li>
* <li><code>/foo/bar/3</code></li>
* </ol>
* and so on.
*
* @param dir The directory in which the files are to be located.
* @throws IOException If the specified directory path is not a directory,
* or if does not exist.
*/
public ConsecutivelyNumberedFilenames(File dir) throws IOException
{
checkDirectory(dir);
this.iter = new ConsecutivelyNumberedFilenamesIterator(dir, "%d", 0);
}
/**
* Instantiates an {@code ConsecutivelyNumberedFilenames} object which
* returns {@link File}s with file names which are based on a format string.
* The numbering will be consecutive from {@code 0}.
* <p>
* The format string should contain the string {@code %d} which will be
* replaced with a consecutively counted number. Additional formatting
* can be applied. For more details, please refer to the section on
* <em>Numeric</em> formatting in the Java API specification for the
* {@link Formatter} class.
* <p>
* <h3>File name sequence</h3>
* For a case where the format string is {@code image-%d}:
* <ol>
* <li><code>image-0</code></li>
* <li><code>image-1</code></li>
* <li><code>image-2</code></li>
* <li><code>image-3</code></li>
* </ol>
* and so on.
*
* @param format The format string to use.
*/
public ConsecutivelyNumberedFilenames(String format)
{
this.iter = new ConsecutivelyNumberedFilenamesIterator(new File("").getParentFile(), format, 0);
}
/**
* Instantiates an {@code ConsecutivelyNumberedFilenames} object which
* returns {@link File}s with file names which are consecutively numbered
* beginning from from the given value, with the directory specified.
* <p>
* <h3>File name sequence</h3>
* For a case where the parent directory is {@code /foo/bar/}, and the
* specified value is {@code 5}:
* <ol>
* <li><code>/foo/bar/5</code></li>
* <li><code>/foo/bar/6</code></li>
* <li><code>/foo/bar/7</code></li>
* <li><code>/foo/bar/8</code></li>
* </ol>
* and so on.
*
* @param dir The directory in which the files are to be located.
* @param start The value from which to start counting.
* @throws IOException If the specified directory path is not a directory,
* or if does not exist.
*/
public ConsecutivelyNumberedFilenames(File dir, int start) throws IOException
{
checkDirectory(dir);
this.iter = new ConsecutivelyNumberedFilenamesIterator(dir, "%d", start);
}
/**
* Instantiates an {@code ConsecutivelyNumberedFilenames} object which
* returns {@link File}s with file names which are based on a format string,
* located in the directory specified. The numbering will be consecutively
* counted from {@code 0}.
* <p>
* The format string should contain the string {@code %d} which will be
* replaced with a consecutively counted number. Additional formatting
* can be applied. For more details, please refer to the section on
* <em>Numeric</em> formatting in the Java API specification for the
* {@link Formatter} class.
* <p>
* <h3>File name sequence</h3>
* For a case where the parent directory is {@code /foo/bar/},
* with the format string {@code image-%d}:
* <ol>
* <li><code>/foo/bar/image-0</code></li>
* <li><code>/foo/bar/image-1</code></li>
* <li><code>/foo/bar/image-2</code></li>
* <li><code>/foo/bar/image-3</code></li>
* </ol>
* and so on.
*
* @param dir The directory in which the files are to be located.
* @param format The format string to use.
* @throws IOException If the specified directory path is not a directory,
* or if does not exist.
*/
public ConsecutivelyNumberedFilenames(File dir, String format) throws IOException
{
checkDirectory(dir);
this.iter = new ConsecutivelyNumberedFilenamesIterator(dir, format, 0);
}
/**
* Instantiates an {@code ConsecutivelyNumberedFilenames} object which
* returns {@link File}s with file names which are based on a format string.
* The numbering will be consecutive from the specified value.
* <p>
* The format string should contain the string {@code %d} which will be
* replaced with a consecutively counted number. Additional formatting
* can be applied. For more details, please refer to the section on
* <em>Numeric</em> formatting in the Java API specification for the
* {@link Formatter} class.
* <p>
* <h3>File name sequence</h3>
* For a case where the parent directory is {@code /foo/bar/}, and the
* specified value is {@code 5}, with the format string {@code image-%d}:
* <ol>
* <li><code>image-5</code></li>
* <li><code>image-6</code></li>
* <li><code>image-7</code></li>
* <li><code>image-8</code></li>
* </ol>
* and so on.
*
* @param format The format string to use.
* @param start The value from which to start counting.
*/
public ConsecutivelyNumberedFilenames(String format, int start)
{
this.iter = new ConsecutivelyNumberedFilenamesIterator(new File("").getParentFile(), format, start);
}
/**
* Instantiates an {@code ConsecutivelyNumberedFilenames} object which
* returns {@link File}s with file names which are based on a format string,
* located in the directory specified. The numbering will be consecutive
* from the specified value.
* <p>
* The format string should contain the string {@code %d} which will be
* replaced with a consecutively counted number. Additional formatting
* can be applied. For more details, please refer to the section on
* <em>Numeric</em> formatting in the Java API specification for the
* {@link Formatter} class.
* <p>
* <h3>File name sequence</h3>
* For a case where the parent directory is {@code /foo/bar/}, and the
* specified value is {@code 5}, with format string {@code image-%d}:
* <ol>
* <li><code>/foo/bar/image-5</code></li>
* <li><code>/foo/bar/image-6</code></li>
* <li><code>/foo/bar/image-7</code></li>
* <li><code>/foo/bar/image-8</code></li>
* </ol>
* and so on.
*
* @param dir The directory in which the files are to be located.
* @param format The format string to use.
* @param start The value from which to start counting.
* @throws IOException If the specified directory path is not a directory,
* or if does not exist.
*/
public ConsecutivelyNumberedFilenames(File dir, String format, int start) throws IOException
{
checkDirectory(dir);
this.iter = new ConsecutivelyNumberedFilenamesIterator(dir, format, start);
}
private static void checkDirectory(File dir) throws IOException
{
if (!dir.isDirectory())
{
throw new IOException(
"Specified path is not a directory or does not exist."
);
}
}
private static class ConsecutivelyNumberedFilenamesIterator implements Iterator<File>
{
private final File dir;
private final String format;
private int count;
public ConsecutivelyNumberedFilenamesIterator(File dir, String format, int start)
{
super();
this.dir = dir;
this.format = format;
this.count = start;
}
public boolean hasNext()
{
return true;
}
public File next()
{
File f = new File(dir, String.format(format, count));
count++;
return f;
}
public void remove()
{
throw new UnsupportedOperationException(
"Cannot remove elements from this iterator."
);
}
}
/**
* Returns an iterator which generates file names according to the rules
* specified by this object.
*
* @return An iterator which generates file names.
*/
public Iterator<File> iterator()
{
return iter;
}
}
| Java |
package net.coobird.thumbnailator;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import net.coobird.thumbnailator.builders.BufferedImageBuilder;
import net.coobird.thumbnailator.builders.ThumbnailParameterBuilder;
import net.coobird.thumbnailator.filters.ImageFilter;
import net.coobird.thumbnailator.makers.FixedSizeThumbnailMaker;
import net.coobird.thumbnailator.makers.ScaledThumbnailMaker;
import net.coobird.thumbnailator.name.Rename;
import net.coobird.thumbnailator.resizers.DefaultResizerFactory;
import net.coobird.thumbnailator.resizers.Resizer;
import net.coobird.thumbnailator.tasks.ThumbnailTask;
/**
* This class provides static utility methods which perform generation of
* thumbnails using Thumbnailator.
* <p>
* When images are resized, the aspect ratio of the images are preserved.
* <p>
* Note: This class does not provide good support for large images.
* For very large images, it is possible for an {@link OutOfMemoryError} to
* occur during processing.
*
* @author coobird
*
*/
public final class Thumbnailator
{
/**
* This class is not intended to be instantiated.
*/
private Thumbnailator() {}
/**
* Creates a thumbnail from parameters specified in a {@link ThumbnailTask}.
*
* @param task A {@link ThumbnailTask} to execute.
* @throws IOException Thrown when a problem occurs when creating a
* thumbnail.
*/
public static void createThumbnail(ThumbnailTask<?, ?> task) throws IOException
{
ThumbnailParameter param = task.getParam();
// Obtain the original image.
BufferedImage sourceImage = task.read();
// Decide the image type of the destination image.
int imageType = param.getType();
/*
* If the imageType indicates that the image type of the original image
* should be used in the thumbnail, then obtain the image type of the
* original.
*
* If the original type is a custom type, then the default image type
* will be used.
*/
if (param.useOriginalImageType())
{
int imageTypeToUse = sourceImage.getType();
if (imageTypeToUse == BufferedImage.TYPE_CUSTOM)
{
imageType = ThumbnailParameter.DEFAULT_IMAGE_TYPE;
}
else
{
imageType = sourceImage.getType();
}
}
BufferedImage destinationImage;
if (param.getSize() != null)
{
// Get the dimensions of the original and thumbnail images.
int destinationWidth = param.getSize().width;
int destinationHeight = param.getSize().height;
// Create the thumbnail.
destinationImage =
new FixedSizeThumbnailMaker()
.size(destinationWidth, destinationHeight)
.keepAspectRatio(param.isKeepAspectRatio())
.fitWithinDimensions(param.fitWithinDimenions())
.imageType(imageType)
.resizerFactory(param.getResizerFactory())
.make(sourceImage);
}
else if (!Double.isNaN(param.getWidthScalingFactor()))
{
// Create the thumbnail.
destinationImage =
new ScaledThumbnailMaker()
.scale(param.getWidthScalingFactor(), param.getHeightScalingFactor())
.imageType(imageType)
.resizerFactory(param.getResizerFactory())
.make(sourceImage);
}
else
{
throw new IllegalStateException("Parameters to make thumbnail" +
" does not have scaling factor nor thumbnail size specified.");
}
// Perform the image filters
for (ImageFilter filter : param.getImageFilters())
{
destinationImage = filter.apply(destinationImage);
}
// Write the thumbnail image to the destination.
task.write(destinationImage);
sourceImage.flush();
destinationImage.flush();
}
/**
* Creates a thumbnail.
* <p>
* The resulting thumbnail uses the default image type.
* <p>
* When the image is resized, the aspect ratio will be preserved.
* <p>
* When the specified dimensions does not have the same aspect ratio as the
* source image, the specified dimensions will be used as the absolute
* boundary of the thumbnail.
* <p>
* For example, if the source image of 100 pixels by 100 pixels, and the
* desired thumbnail size is 50 pixels by 100 pixels, then the resulting
* thumbnail will be 50 pixels by 50 pixels, as the constraint will be
* 50 pixels for the width, and therefore, by preserving the aspect ratio,
* the height will be required to be 50 pixels.
* </p>
*
* @param img The source image.
* @param width The width of the thumbnail.
* @param height The height of the thumbnail.
* @return Resulting thumbnail.
*/
public static BufferedImage createThumbnail(
BufferedImage img,
int width,
int height
)
{
validateDimensions(width, height);
Dimension imgSize = new Dimension(img.getWidth(), img.getHeight());
Dimension thumbnailSize = new Dimension(width, height);
Resizer resizer =
DefaultResizerFactory.getInstance()
.getResizer(imgSize, thumbnailSize);
BufferedImage thumbnailImage =
new FixedSizeThumbnailMaker(width, height, true, true)
.resizer(resizer)
.make(img);
return thumbnailImage;
}
/**
* Creates a thumbnail from an source image and writes the thumbnail to
* a destination file.
* <p>
* The image format to use for the thumbnail will be determined from the
* file extension. However, if the image format cannot be determined, then,
* the same image format as the original image will be used when writing
* the thumbnail.
*
* @param inFile The {@link File} from which image data is read.
* @param outFile The {@link File} to which thumbnail is written.
* @param width The width of the thumbnail.
* @param height The height of the thumbnail.
* @throws IOException Thrown when a problem occurs when reading from
* {@code File} representing an image file.
*/
public static void createThumbnail(
File inFile,
File outFile,
int width,
int height
) throws IOException
{
validateDimensions(width, height);
if (inFile == null)
{
throw new NullPointerException("Input file is null.");
}
else if (outFile == null)
{
throw new NullPointerException("Output file is null.");
}
if (!inFile.exists())
{
throw new IOException("Input file does not exist.");
}
Thumbnails.of(inFile)
.size(width, height)
.toFile(outFile);
}
/**
* Creates a thumbnail from an image file, and returns as a
* {@link BufferedImage}.
*
* @param f The {@link File} from which image data is read.
* @param width The width of the thumbnail.
* @param height The height of the thumbnail.
* @return The thumbnail image as a {@link BufferedImage}.
* @throws IOException Thrown when a problem occurs when reading from
* {@code File} representing an image file.
*/
public static BufferedImage createThumbnail(
File f,
int width,
int height
) throws IOException
{
validateDimensions(width, height);
if (f == null)
{
throw new NullPointerException("Input file is null.");
}
return Thumbnails.of(f).size(width, height).asBufferedImage();
}
/**
* Creates a thumbnail from an {@link Image}.
* <p>
* The resulting {@link BufferedImage} uses the default image type.
* <p>
* When the image is resized, the aspect ratio will be preserved.
* <p>
* When the specified dimensions does not have the same aspect ratio as the
* source image, the specified dimensions will be used as the absolute
* boundary of the thumbnail.
*
* @param img The source image.
* @param width The width of the thumbnail.
* @param height The height of the thumbnail.
* @return The thumbnail image as an {@link Image}.
*/
public static Image createThumbnail(
Image img,
int width,
int height
)
{
validateDimensions(width, height);
// Copy the image from Image into a new BufferedImage.
BufferedImage srcImg =
new BufferedImageBuilder(
img.getWidth(null),
img.getHeight(null)
).build();
Graphics g = srcImg.createGraphics();
g.drawImage(img, width, height, null);
g.dispose();
return createThumbnail(srcImg, width, height);
}
/**
* Creates a thumbnail from image data streamed from an {@link InputStream}
* and streams the data out to an {@link OutputStream}.
* <p>
* The thumbnail will be stored in the same format as the original image.
*
* @param is The {@link InputStream} from which to obtain
* image data.
* @param os The {@link OutputStream} to send thumbnail data to.
* @param width The width of the thumbnail.
* @param height The height of the thumbnail.
* @throws IOException Thrown when a problem occurs when reading from
* {@code File} representing an image file.
*/
public static void createThumbnail(
InputStream is,
OutputStream os,
int width,
int height
) throws IOException
{
Thumbnailator.createThumbnail(
is, os, ThumbnailParameter.ORIGINAL_FORMAT, width, height);
}
/**
* Creates a thumbnail from image data streamed from an {@link InputStream}
* and streams the data out to an {@link OutputStream}, with the specified
* format for the output data.
*
* @param is The {@link InputStream} from which to obtain
* image data.
* @param os The {@link OutputStream} to send thumbnail data to.
* @param format The image format to use to store the thumbnail data.
* @param width The width of the thumbnail.
* @param height The height of the thumbnail.
* @throws IOException Thrown when a problem occurs when reading from
* {@code File} representing an image file.
* @throws IllegalArgumentException If the specified output format is
* not supported.
*/
public static void createThumbnail(
InputStream is,
OutputStream os,
String format,
int width,
int height
) throws IOException
{
validateDimensions(width, height);
if (is == null)
{
throw new NullPointerException("InputStream is null.");
}
else if (os == null)
{
throw new NullPointerException("OutputStream is null.");
}
Thumbnails.of(is)
.size(width, height)
.outputFormat(format)
.toOutputStream(os);
}
/**
* Creates thumbnails from a specified {@link Collection} of {@link File}s.
* The filenames of the resulting thumbnails are determined by applying
* the specified {@link Rename}.
* <p>
* The order of the thumbnail {@code File}s in the returned
* {@code Collection} will be the same as the order as the source list.
*
* @param files A {@code Collection} containing {@code File} objects
* of image files.
* @param rename The renaming function to use.
* @param width The width of the thumbnail.
* @param height The height of the thumbnail.
* @throws IOException Thrown when a problem occurs when reading from
* {@code File} representing an image file.
*
* @deprecated This method has been deprecated in favor of using the
* {@link Thumbnails#fromFiles(Iterable)} interface.
* This method will be removed in 0.5.0, and will not be
* further maintained.
*/
public static Collection<File> createThumbnailsAsCollection(
Collection<? extends File> files,
Rename rename,
int width,
int height
)
throws IOException
{
validateDimensions(width, height);
if (files == null)
{
throw new NullPointerException("Collection of Files is null.");
}
if (rename == null)
{
throw new NullPointerException("Rename is null.");
}
ArrayList<File> resultFiles = new ArrayList<File>();
ThumbnailParameter param =
new ThumbnailParameterBuilder()
.size(width, height)
.build();
for (File inFile : files)
{
File outFile =
new File(inFile.getParent(), rename.apply(inFile.getName(), param));
createThumbnail(inFile, outFile, width, height);
resultFiles.add(outFile);
}
return Collections.unmodifiableList(resultFiles);
}
/**
* Creates thumbnails from a specified {@code Collection} of {@code File}s.
* The filenames of the resulting thumbnails are determined by applying
* the specified {@code Rename} function.
*
* @param files A {@code Collection} containing {@code File} objects
* of image files.
* @param rename The renaming function to use.
* @param width The width of the thumbnail.
* @param height The height of the thumbnail.
* @throws IOException Thrown when a problem occurs when reading from
* {@code File} representing an image file.
*
* @deprecated This method has been deprecated in favor of using the
* {@link Thumbnails#fromFiles(Iterable)} interface.
* This method will be removed in 0.5.0, and will not be
* further maintained.
*/
public static void createThumbnails(
Collection<? extends File> files,
Rename rename,
int width,
int height
)
throws IOException
{
validateDimensions(width, height);
if (files == null)
{
throw new NullPointerException("Collection of Files is null.");
}
if (rename == null)
{
throw new NullPointerException("Rename is null.");
}
ThumbnailParameter param =
new ThumbnailParameterBuilder()
.size(width, height)
.build();
for (File inFile : files)
{
File outFile =
new File(inFile.getParent(), rename.apply(inFile.getName(), param));
createThumbnail(inFile, outFile, width, height);
}
}
/**
* Performs validation on the specified dimensions.
* <p>
* If any of the dimensions are less than or equal to 0, an
* {@code IllegalArgumentException} is thrown with an message specifying the
* reason for the exception.
* <p>
* This method is used to perform a check on the output dimensions of a
* thumbnail for the {@link Thumbnails#createThumbnail} methods.
*
* @param width The width to validate.
* @param height The height to validate.
*/
private static void validateDimensions(int width, int height)
{
if (width <= 0 && height <= 0)
{
throw new IllegalArgumentException(
"Destination image dimensions must not be less than " +
"0 pixels."
);
}
else if (width <= 0 || height <= 0)
{
String dimension = width == 0 ? "width" : "height";
throw new IllegalArgumentException(
"Destination image " + dimension + " must not be " +
"less than or equal to 0 pixels."
);
}
}
}
| Java |
/**
* This package contains utilities classes used by Thumbnailator.
*/
package net.coobird.thumbnailator.util;
| Java |
package net.coobird.thumbnailator.util;
import java.util.Arrays;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import javax.imageio.ImageIO;
import javax.imageio.ImageWriter;
import net.coobird.thumbnailator.ThumbnailParameter;
/**
* A utility class for Thumbnailator.
*
* @author coobird
*
*/
public final class ThumbnailatorUtils
{
/**
* This class is not intended to be instantiated.
*/
private ThumbnailatorUtils() {}
/**
* Returns a {@link List} of supported output formats.
*
* @return A {@link List} of supported output formats. If no formats
* are supported, an empty list is returned.
*/
public static List<String> getSupportedOutputFormats()
{
String[] formats = ImageIO.getWriterFormatNames();
if (formats == null)
{
return Collections.emptyList();
}
else
{
return Arrays.asList(formats);
}
}
/**
* Returns whether a specified format is supported for output.
*
* @param format The format to check whether it is supported or not.
* @return {@code true} if the format is supported, {@code false}
* otherwise.
*/
public static boolean isSupportedOutputFormat(String format)
{
if (format == ThumbnailParameter.ORIGINAL_FORMAT)
{
return true;
}
for (String supportedFormat : getSupportedOutputFormats())
{
if (supportedFormat.equals(format))
{
return true;
}
}
return false;
}
/**
* Returns a {@link List} of supported output formats types for a specified
* output format.
*
* @return A {@link List} of supported output formats types. If no
* formats types are supported, or if compression is not
* supported for the specified format, then an empty list
* is returned.
*/
public static List<String> getSupportedOutputFormatTypes(String format)
{
if (format == ThumbnailParameter.ORIGINAL_FORMAT)
{
return Collections.emptyList();
}
Iterator<ImageWriter> writers = ImageIO.getImageWritersByFormatName(format);
if (!writers.hasNext())
{
return Collections.emptyList();
}
String[] types;
try
{
types = writers.next().getDefaultWriteParam().getCompressionTypes();
}
catch (UnsupportedOperationException e)
{
return Collections.emptyList();
}
if (types == null)
{
return Collections.emptyList();
}
else
{
return Arrays.asList(types);
}
}
/**
* Returns whether a specified format type is supported for a specified
* output format.
*
* @param format The format to check whether it is supported or not.
* @param type The format type to check whether it is supported or not.
* @return {@code true} if the format type is supported by the
* specified supported format, {@code false} otherwise.
*/
public static boolean isSupportedOutputFormatType(String format, String type)
{
if (!isSupportedOutputFormat(format))
{
return false;
}
if (format == ThumbnailParameter.ORIGINAL_FORMAT
&& type == ThumbnailParameter.DEFAULT_FORMAT_TYPE)
{
return true;
}
else if (format == ThumbnailParameter.ORIGINAL_FORMAT
&& type != ThumbnailParameter.DEFAULT_FORMAT_TYPE)
{
return false;
}
else if (type == ThumbnailParameter.DEFAULT_FORMAT_TYPE)
{
return true;
}
for (String supportedType : getSupportedOutputFormatTypes(format))
{
if (supportedType.equals(type))
{
return true;
}
}
return false;
}
}
| Java |
package net.coobird.thumbnailator.util.exif;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import javax.imageio.ImageReader;
import javax.imageio.metadata.IIOMetadata;
import javax.imageio.metadata.IIOMetadataNode;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
/**
* An utility class used to obtain the orientation information from a given
* Exif metadata.
*
* @author coobird
*
*/
public final class ExifUtils
{
private static final String EXIF_MAGIC_STRING = "Exif";
/**
* This class should not be instantiated.
*/
private ExifUtils() {};
/**
* Returns the orientation obtained from the Exif metadata.
*
* @param reader An {@link ImageReader} which is reading the
* target image.
* @param imageIndex The index of the image from which the Exif
* metadata should be read from.
* @return The orientation information obtained from the
* Exif metadata, as a {@link Orientation} enum.
* @throws IOException When an error occurs during reading.
* @throws IllegalArgumentException If the {@link ImageReader} does not
* have the target image set, or if the
* reader does not have a JPEG open.
*/
public static Orientation getExifOrientation(ImageReader reader, int imageIndex) throws IOException
{
IIOMetadata metadata = reader.getImageMetadata(imageIndex);
Node rootNode = metadata.getAsTree("javax_imageio_jpeg_image_1.0");
NodeList childNodes = rootNode.getChildNodes();
// Look for the APP1 containing Exif data, and retrieve it.
for (int i = 0; i < childNodes.getLength(); i++)
{
if ("markerSequence".equals(childNodes.item(i).getNodeName()))
{
NodeList markerSequenceChildren = childNodes.item(i).getChildNodes();
for (int j = 0; j < markerSequenceChildren.getLength(); j++)
{
IIOMetadataNode metadataNode = (IIOMetadataNode)(markerSequenceChildren.item(j));
byte[] bytes = (byte[])metadataNode.getUserObject();
if (bytes == null)
{
continue;
}
byte[] magicNumber = new byte[4];
ByteBuffer.wrap(bytes).get(magicNumber);
if (EXIF_MAGIC_STRING.equals(new String(magicNumber)))
{
return getOrientationFromExif(bytes);
}
}
}
}
return null;
}
private static Orientation getOrientationFromExif(byte[] exifData)
{
// Needed to make byte-wise reading easier.
ByteBuffer buffer = ByteBuffer.wrap(exifData);
byte[] exifId = new byte[4];
buffer.get(exifId);
if (!EXIF_MAGIC_STRING.equals(new String(exifId)))
{
return null;
}
// read the \0 after the Exif
buffer.get();
// read the padding byte
buffer.get();
byte[] tiffHeader = new byte[8];
buffer.get(tiffHeader);
/*
* The first 2 bytes of the TIFF header contains either:
* "II" for Intel byte alignment (little endian), or
* "MM" for Motorola byte alignment (big endian)
*/
ByteOrder bo;
if (tiffHeader[0] == 'I' && tiffHeader[1] == 'I')
{
bo = ByteOrder.LITTLE_ENDIAN;
}
else
{
bo = ByteOrder.BIG_ENDIAN;
}
byte[] numFields = new byte[2];
buffer.get(numFields);
int nFields = ByteBuffer.wrap(numFields).order(bo).getShort();
byte[] ifd = new byte[12];
for (int i = 0; i < nFields; i++)
{
buffer.get(ifd);
IfdStructure ifdStructure = readIFD(ifd, bo);
// Return the orientation from the orientation IFD
if (ifdStructure.getTag() == 0x0112)
{
return Orientation.typeOf(ifdStructure.getOffsetValue());
}
}
return null;
}
private static IfdStructure readIFD(byte[] ifd, ByteOrder bo)
{
ByteBuffer buffer = ByteBuffer.wrap(ifd).order(bo);
short tag = buffer.getShort();
short type = buffer.getShort();
int count = buffer.getInt();
IfdType ifdType = IfdType.typeOf(type);
int offsetValue = 0;
/*
* Per section 4.6.2 of the Exif Spec, if value is smaller than
* 4 bytes, it will exist in the earlier byte.
*/
int byteSize = count * ifdType.size();
if (byteSize <= 4) {
if (ifdType == IfdType.SHORT)
{
for (int i = 0; i < count; i++)
{
offsetValue = (int)buffer.getShort();
}
}
else if (ifdType == IfdType.BYTE || ifdType == IfdType.ASCII || ifdType == IfdType.UNDEFINED)
{
for (int i = 0; i < count; i++)
{
offsetValue = (int)buffer.get();
}
}
else
{
offsetValue = buffer.getInt();
}
}
else
{
offsetValue = buffer.getInt();
}
return new IfdStructure(tag, type, count, offsetValue);
}
}
| Java |
package net.coobird.thumbnailator.util.exif;
/**
* IFD structure as defined in Section 4.6.2 of the Exif Specification
* version 2.3.
*
* @author coobird
*
*/
public class IfdStructure
{
private final int tag;
private final IfdType type;
private final int count;
private final int offsetValue;
/**
* Instantiates a IFD with the given attributes.
*
* @param tag The tag element.
* @param type The type element.
* @param count The count of values.
* @param offsetValue The offset or value.
*/
public IfdStructure(int tag, int type, int count, int offsetValue)
{
super();
this.tag = tag;
this.type = IfdType.typeOf(type);
this.count = count;
this.offsetValue = offsetValue;
}
/**
* Returns the tag element in the IFD structure.
* @return An integer representation of the tag element.
* Should be a value between 0x00 to 0xFF.
*/
public int getTag()
{
return tag;
}
/**
* Returns the type element in the IFD structure.
* @return An {@link IfdType} enum indicating the type.
*/
public IfdType getType()
{
return type;
}
/**
* Returns the count element in the IFD structure, indicating the number
* of values the value field..
* @return A count indicating the number of values.
*/
public int getCount()
{
return count;
}
/**
* Returns either the offset or value of the IFD.
* @return Either the offset or value. The type of the returned value
* can be determined by the return of the {@link #isOffset()}
* or {@link #isValue()} method.
*/
public int getOffsetValue()
{
return offsetValue;
}
/**
* Returns whether the value returned by the {@link #getOffsetValue()}
* method is an actual value.
* @return {@code true} if the value returned by the
* {@link #getOffsetValue()} method is a value, {@code false}
* otherwise.
*/
public boolean isValue()
{
/*
* The offsetValue field contains a value if the size of the value is
* less than or equal to 4 bytes see "Value Offset" in Section 4.6.3
* of the Exif version 2.3 specification.
*/
return type.size() * count <= 4;
}
/**
* Returns whether the value returned by the {@link #getOffsetValue()}
* method is an offset value.
* @return {@code true} if the value returned by the
* {@link #getOffsetValue()} method is a offset value,
* {@code false} otherwise.
*/
public boolean isOffset()
{
return !isValue();
}
/**
* Returns the calculated hash code for this object.
* @return Hash code for this object.
*/
@Override
public int hashCode()
{
final int prime = 31;
int result = 1;
result = prime * result + count;
result = prime * result + offsetValue;
result = prime * result + tag;
result = prime * result + ((type == null) ? 0 : type.hashCode());
return result;
}
/**
* Returns whether this object is equal to the given object.
* @return {@code true} if the given object and this object is
* equivalent, {@code false} otherwise.
*/
@Override
public boolean equals(Object obj)
{
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
IfdStructure other = (IfdStructure) obj;
if (count != other.count)
return false;
if (offsetValue != other.offsetValue)
return false;
if (tag != other.tag)
return false;
if (type != other.type)
return false;
return true;
}
/**
* Returns a textual {@link String} reprensentation of this object.
* @return A textual representation of this object.
*/
@Override
public String toString()
{
return "IfdStructure [tag=" + Integer.toHexString(tag) +
", type=" + type + ", count=" + count +
", offsetValue=" + offsetValue + "]";
}
}
| Java |
/**
* This package contains utilities classes used to handle Exif metadata.
*/
package net.coobird.thumbnailator.util.exif;
| Java |
package net.coobird.thumbnailator.util.exif;
/**
* This enum corresponds to the types of data present in an IFD,
* as defined in Section 4.6.2 of the Exif Specification version 2.3.
*
* @author coobird
*
*/
public enum IfdType
{
/**
* An 8-bit unsigned integer value.
*/
BYTE(1, 1),
/**
* An 8-bit value containing a single 7-bit ASCII character.
* The final byte is NULL-terminated.
*/
ASCII(2, 1),
/**
* A 16-bit unsigned integer value.
*/
SHORT(3, 2),
/**
* A 32-bit unsigned integer value.
*/
LONG(4, 4),
/**
* Two {@link #LONG} values, where the first {@code LONG} is the
* numerator, while the second {@code LONG} is the denominator.
*/
RATIONAL(5, LONG.size() * 2),
/**
* An 8-bit value which can be value as defined elsewhere.
*/
UNDEFINED(7, 1),
/**
* A 32-bit signed integer value using 2's complement.
*/
SLONG(9, 4),
/**
* Two {@link #SLONG} values, where the first {@code SLONG} is the
* numerator, while the second {@code SLONG} is the denominator.
*/
SRATIONAL(5, SLONG.size() * 2),
;
private int value;
private int size;
private IfdType(int value, int size)
{
this.value = value;
this.size = size;
}
/**
* Returns the size in bytes for this IFD type.
* @return Size in bytes for this IFD type.
*/
public int size()
{
return size;
}
/**
* Returns the IFD type as a type value.
* @return IFD type as a type value.
*/
public int value()
{
return value;
}
/**
* Returns the {@link IfdType} corresponding to the given IFD type value.
*
* @param value The IFD type value.
* @return {@link IfdType} corresponding to the IDF type value.
* Return {@code null} if the given value does not
* correspond to a valid {@link IfdType}.
*/
public static IfdType typeOf(int value)
{
for (IfdType type : IfdType.values())
{
if (type.value == value)
{
return type;
}
}
return null;
}
/**
* Returns a textual {@link String} reprensentation of this enum.
* @return A textual representation of this enum.
*/
@Override
public String toString()
{
return "IfdType [type=" + this.name() + ", value=" + value + ", size=" + size + "]";
}
}
| Java |
package net.coobird.thumbnailator.util.exif;
/**
* Representation for the Orientation (Tag 274) in the Exif metadata, as
* defined in Section 4.6.4 of the Exif Specification version 2.3.
*
* @author coobird
*
*/
public enum Orientation
{
/**
* Orientation 1.
* <ul>
* <li>First row: visual top of the image</li>
* <li>First column: visual left-hand side of the image</li>
* </ul>
*/
TOP_LEFT(1),
/**
* Orientation 2.
* <ul>
* <li>First row: visual top of the image</li>
* <li>First column: visual right-hand side of the image</li>
* </ul>
*/
TOP_RIGHT(2),
/**
* Orientation 3.
* <ul>
* <li>First row: visual bottom of the image</li>
* <li>First column: visual right-hand side of the image</li>
* </ul>
*/
BOTTOM_RIGHT(3),
/**
* Orientation 4.
* <ul>
* <li>First row: visual bottom of the image</li>
* <li>First column: visual left-hand side of the image</li>
* </ul>
*/
BOTTOM_LEFT(4),
/**
* Orientation 5.
* <ul>
* <li>First row: visual left-hand side of the image</li>
* <li>First column: visual top of the image</li>
* </ul>
*/
LEFT_TOP(5),
/**
* Orientation 6.
* <ul>
* <li>First row: visual right-hand side of the image</li>
* <li>First column: visual top of the image</li>
* </ul>
*/
RIGHT_TOP(6),
/**
* Orientation 7.
* <ul>
* <li>First row: visual right-hand side of the image</li>
* <li>First column: visual bottom of the image</li>
* </ul>
*/
RIGHT_BOTTOM(7),
/**
* Orientation 8.
* <ul>
* <li>First row: visual left-hand side of the image</li>
* <li>First column: visual bottom of the image</li>
* </ul>
*/
LEFT_BOTTOM(8),
;
private int value;
private Orientation(int value)
{
this.value = value;
}
/**
* Returns the {@link Orientation} corresponding to the given orientation
* value.
*
* @param value The orientation value.
* @return {@link Orientation} corresponding to the orientation
* value. Return {@code null} if the given value does not
* correspond to a valid {@link Orientation}.
*/
public static Orientation typeOf(int value)
{
for (Orientation orientation : Orientation.values())
{
if (orientation.value == value)
{
return orientation;
}
}
return null;
}
/**
* Returns a textual {@link String} reprensentation of this enum.
* @return A textual representation of this enum.
*/
@Override
public String toString()
{
return "Orientation [type=" + value + "]";
}
}
| Java |
package net.coobird.thumbnailator.util.exif;
import net.coobird.thumbnailator.filters.Flip;
import net.coobird.thumbnailator.filters.ImageFilter;
import net.coobird.thumbnailator.filters.Pipeline;
import net.coobird.thumbnailator.filters.Rotation;
/**
* An utility class which returns a suitable {@link ImageFilter} to perform
* the transformations necessary to properly orient an image according to the
* Exif metadata.
*
* @author coobird
*
*/
public final class ExifFilterUtils
{
/**
* This class should not be instantiated.
*/
private ExifFilterUtils() {};
/**
* Returns a {@link ImageFilter} which will perform the transformations
* required to properly orient the thumbnail according to the Exif
* orientation.
*
* @param orientation The Exif orientation
* @return {@link ImageFilter}s required to properly
* orient the image.
*/
public static ImageFilter getFilterForOrientation(Orientation orientation)
{
Pipeline filters = new Pipeline();
if (orientation == Orientation.TOP_RIGHT)
{
filters.add(Flip.HORIZONTAL);
}
else if (orientation == Orientation.BOTTOM_RIGHT)
{
filters.add(Rotation.ROTATE_180_DEGREES);
}
else if (orientation == Orientation.BOTTOM_LEFT)
{
filters.add(Rotation.ROTATE_180_DEGREES);
filters.add(Flip.HORIZONTAL);
}
else if (orientation == Orientation.LEFT_TOP)
{
filters.add(Rotation.RIGHT_90_DEGREES);
filters.add(Flip.HORIZONTAL);
}
else if (orientation == Orientation.RIGHT_TOP)
{
filters.add(Rotation.RIGHT_90_DEGREES);
}
else if (orientation == Orientation.RIGHT_BOTTOM)
{
filters.add(Rotation.LEFT_90_DEGREES);
filters.add(Flip.HORIZONTAL);
}
else if (orientation == Orientation.LEFT_BOTTOM)
{
filters.add(Rotation.LEFT_90_DEGREES);
}
return filters;
}
}
| Java |
package net.coobird.thumbnailator.util;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
/**
* This class provides convenience methods for using {@link BufferedImage}s.
*
* @author coobird
*
*/
public final class BufferedImages
{
/**
* This class is not intended to be instantiated.
*/
private BufferedImages() {}
/**
* Returns a {@link BufferedImage} which is a graphical copy of the
* specified image.
*
* @param img The image to copy.
* @return A copy of the specified image.
*/
public static BufferedImage copy(BufferedImage img)
{
return copy(img, img.getType());
}
/**
* Returns a {@link BufferedImage} with the specified image type, where the
* graphical content is a copy of the specified image.
*
* @param img The image to copy.
* @param imageType The image type for the image to return.
* @return A copy of the specified image.
*/
public static BufferedImage copy(BufferedImage img, int imageType)
{
int width = img.getWidth();
int height = img.getHeight();
BufferedImage newImage = new BufferedImage(width, height, imageType);
Graphics g = newImage.createGraphics();
g.drawImage(img, 0, 0, null);
g.dispose();
return newImage;
}
} | Java |
package net.coobird.thumbnailator.test;
import java.awt.image.BufferedImage;
import java.awt.image.Raster;
public final class BufferedImageComparer
{
public static final boolean isSame(BufferedImage img0, BufferedImage img1)
{
int width0 = img0.getWidth();
int height0 = img0.getHeight();
int width1 = img1.getWidth();
int height1 = img1.getHeight();
if (width0 != width1 || height0 != height1)
{
throw new AssertionError("Width and/or height do not match.");
}
if (!img0.getColorModel().equals(img1.getColorModel()))
{
String message = "Color models do not match. [%s, %s]";
message = String.format(message, img0.getColorModel(), img1.getColorModel());
throw new AssertionError(message);
}
if (!img0.getSampleModel().equals(img1.getSampleModel()))
{
String message = "Sample models do not match. [%s, %s]";
message = String.format(message, img0.getSampleModel(), img1.getSampleModel());
throw new AssertionError(message);
}
if (img0.getType() != img1.getType())
{
String message = "Image types do not match. [%d, %d]";
message = String.format(message, img0.getType(), img1.getType());
throw new AssertionError(message);
}
/*
* Check the RGB data.
*/
for (int i = 0; i < width0; i++)
{
for (int j = 0; j < height0; j++)
{
if (img0.getRGB(i, j) != img1.getRGB(i, j))
{
String message = "Pixels do not match. location: (%d, %d), rgb: (%d, %d)";
message = String.format(message, i, j, img0.getRGB(i, j), img1.getRGB(i, j));
throw new AssertionError(message);
}
}
}
/*
* Check the raw data.
*/
Raster d0 = img0.getData();
Raster d1 = img1.getData();
if (d0.getNumBands() != d1.getNumBands())
{
String message = "Number of bands do not match. [%d, %d]";
message = String.format(message, d0.getNumBands(), d1.getNumBands());
throw new AssertionError(message);
}
for (int i = 0; i < width0; i++)
{
for (int j = 0; j < height0; j++)
{
int[] i0 = new int[d0.getNumBands()];
int[] i1 = new int[d1.getNumBands()];
d0.getPixel(i, j, i0);
d1.getPixel(i, j, i1);
for (int k = 0; k < d0.getNumBands(); k++)
{
if (i0[k] != i1[k])
{
String message = "Pixels do not match. rgb: (%d, %d), band: %d";
message = String.format(message, i, j, k);
throw new AssertionError(message);
}
}
}
}
return true;
}
// Checks if the pixels are similar.
public static final boolean isRGBSimilar(BufferedImage img0, BufferedImage img1)
{
int width0 = img0.getWidth();
int height0 = img0.getHeight();
int width1 = img1.getWidth();
int height1 = img1.getHeight();
if (width0 != width1 || height0 != height1)
{
throw new AssertionError("Width and/or height do not match.");
}
/*
* Check the RGB data.
*/
for (int i = 0; i < width0; i++)
{
for (int j = 0; j < height0; j++)
{
int v0 = img0.getRGB(i, j);
int v1 = img1.getRGB(i, j);
int r0 = (v0 << 8) >>> 24;
int r1 = (v1 << 8) >>> 24;
int g0 = (v0 << 16) >>> 24;
int g1 = (v1 << 16) >>> 24;
int b0 = (v0 << 24) >>> 24;
int b1 = (v1 << 24) >>> 24;
if (r0 != r1 || g0 != g1 || b0 != b1)
{
String message = "Pixels do not match. location: (%d, %d), rgb: ([%d, %d, %d], [%d, %d, %d])";
message = String.format(message, i, j, r0, g0, b0, r1, g1, b1);
throw new AssertionError(message);
}
}
}
return true;
}
}
| Java |
package net.coobird.thumbnailator.test;
import static org.junit.Assert.assertEquals;
import java.awt.Color;
import java.awt.Point;
import java.awt.image.BufferedImage;
import java.util.Arrays;
import java.util.List;
public class BufferedImageAssert {
/**
* Checks if the 3x3 pattern matches the given image.
*
* @param img The image to check.
* @param pattern The pattern that should be present.
* @return If the pattern is present in the image.
*/
public static void assertMatches(BufferedImage img, float[] pattern) {
if (pattern.length != 9) {
throw new IllegalArgumentException("Pattern must be of length 9.");
}
int width = img.getWidth();
int height = img.getHeight();
List<Point> points = Arrays.asList(
new Point(0, 0),
new Point(width / 2 - 1, 0),
new Point(width - 1, 0),
new Point(0, height / 2 - 1),
new Point(width / 2 - 1, height / 2 - 1),
new Point(width - 1, height / 2 - 1),
new Point(0, height - 1),
new Point(width / 2 - 1, height - 1),
new Point(width - 1, height - 1)
);
for (int i = 0; i < 9; i++) {
Point p = points.get(i);
Color c = pattern[i] == 0 ? Color.white : Color.black;
assertEquals(c.getRGB(), img.getRGB(p.x, p.y));
}
}
}
| Java |
/**
* Copyright (c) 2011 Basil Shikin, VintageRadio Project
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.vintagephone.model.podcaster;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import android.util.Log;
public class Podcaster
{
private static final String TAG = "Podcaster";
private static final String KEY_URL = "podcast.url";
private static final String KEY_UPDATE_HOURS = "podcast.update_hours";
private static final String PROPERTIES_FILE = "podcast.properties";
private final File m_targetFolder;
private final Properties m_properties;
private final ScheduledExecutorService m_executor;
public Podcaster( final File targetFolder )
{
m_targetFolder = targetFolder;
m_properties = new Properties();
m_executor = Executors.newScheduledThreadPool( 1 );
}
public void initialize()
{
try
{
loadProperties();
final String updateHoursStr = m_properties.getProperty( KEY_UPDATE_HOURS, "3" );
final int updateHours = Integer.parseInt( updateHoursStr );
final String sourceUrl = m_properties.getProperty( KEY_URL );
if ( sourceUrl == null ) throw new IOException("no_podcast_url");
final PodcastDownloadTask downloadTask = new PodcastDownloadTask( sourceUrl, m_targetFolder );
m_executor.scheduleAtFixedRate( downloadTask, updateHours*60*60, updateHours*60*60, TimeUnit.SECONDS );
}
catch (IOException e)
{
Log.e(TAG, "Unable to read podcast settins", e );
}
}
private void loadProperties() throws IOException
{
InputStream is = null;
try
{
final File propertiesFile = new File( m_targetFolder, PROPERTIES_FILE );
is = new FileInputStream( propertiesFile );
m_properties.load( is );
}
finally
{
if ( is != null ) is.close();
}
}
}
| Java |
/**
* Copyright (c) 2011 Basil Shikin, VintageRadio Project
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.vintagephone.model.podcaster;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.URL;
import android.util.Log;
/**
* This task is used to download lastet edition of the podcast into specified folder.
*
* @author Basil Shikin
*
*/
class PodcastDownloadTask
implements Runnable
{
private static final String Tag = "PodcastDownloadTask";
private final String m_sourceUrl;
private final File m_targetFolder;
private final byte[] m_buffer = new byte[ 50*1024 ];
public PodcastDownloadTask(String sourceUrl, File targetFolder)
{
m_sourceUrl = sourceUrl;
m_targetFolder = targetFolder;
}
@Override
public void run()
{
try
{
final String podcastXml = readPodcastXml();
Log.i( Tag, "Read podcast XML (" + podcastXml.length() + " bytes" );
final String downloadUrl = parseDownloadUrl( podcastXml );
Log.i( Tag, "Last podcast item located at \"" + downloadUrl + "\"" );
cleanOldPodcastFiles();
final File destinationFile = createDestinationFile( downloadUrl );
downloadToFile( downloadUrl, destinationFile );
Log.i( Tag, "Last podcast downloaded to \"" + destinationFile.getAbsolutePath() + "\"" );
}
catch (IOException e)
{
Log.e( Tag, "Unable to read podcast", e );
}
}
private void cleanOldPodcastFiles()
{
final File[] files = m_targetFolder.listFiles( new FilenameFilter() {
public boolean accept(File dir, String filename)
{
return filename.toLowerCase().endsWith(".mp3");
}
});
if ( files != null && files.length > 0 )
{
for ( File file : files )
{
final boolean deleted = file.delete();
if ( !deleted ) Log.w( Tag, "Unable to delete " + file.getAbsolutePath() );
}
}
}
private void downloadToFile(String downloadUrl, File destinationFile) throws IOException
{
final URL podcastXml = new URL( downloadUrl );
InputStream podcastStream = null;
OutputStream fileStream = null;
try
{
podcastStream = podcastXml.openStream();
fileStream = new FileOutputStream( destinationFile );
int read = podcastStream.read( m_buffer );
int totalRead = read;
int printCounter = 0;
while ( read > 0 )
{
fileStream.write( m_buffer, 0, read );
read = podcastStream.read( m_buffer );
totalRead += read;
if ( totalRead > printCounter * 500*1024 )
{
Log.d( Tag, "Reading podcast, so far " + totalRead/1024 + " Kb");
printCounter += 1;
}
}
Log.d( Tag, "Podcast read. Total " + totalRead/(1024*1024) + " Mb");
}
finally
{
if ( podcastStream != null ) podcastStream.close();
if ( fileStream != null ) fileStream.close();
}
}
private File createDestinationFile(String downloadUrl) throws IOException
{
final int slashIx = downloadUrl.lastIndexOf('/');
if ( slashIx > 0 )
{
final String fileName = downloadUrl.substring( slashIx );
final File result = new File( m_targetFolder, fileName );
if ( result.exists() )
{
final boolean deleted = result.delete();
if ( !deleted ) Log.w( Tag, "Unable to delete " + result.getAbsolutePath() );
}
else
{
result.createNewFile();
}
return result;
}
else
{
throw new IllegalArgumentException("Malformed podcast URL: " + downloadUrl );
}
}
private String parseDownloadUrl(String podcastXml)
{
final int itemIx = podcastXml.indexOf("<item>");
if ( itemIx > 0 )
{
final int enclosureIx = podcastXml.indexOf("<enclosure", itemIx );
if ( enclosureIx > 0 )
{
final String urlAttr = "url=\"";
final int urlStart = podcastXml.indexOf( urlAttr, enclosureIx );
final int urlEnd = podcastXml.indexOf( "\"", urlStart + urlAttr.length() + 1);
if ( urlStart > 0 && urlEnd > urlStart )
{
return podcastXml.substring( urlStart + urlAttr.length(), urlEnd );
}
else
{
Log.e( Tag, "No url start and end found in podcast XML");
}
}
else
{
Log.e( Tag, "No <enclosure> found in podcast XML");
}
}
else
{
Log.e( Tag, "No <item> found in podcast XML");
}
return null;
}
private String readPodcastXml() throws IOException
{
final URL podcastXml = new URL( m_sourceUrl );
final StringBuffer result = new StringBuffer();
InputStream podcastStream = null;
BufferedReader podcastReader = null;
try
{
podcastStream = podcastXml.openStream();
podcastReader = new BufferedReader( new InputStreamReader( podcastStream ) );
String inputLine;
while ( (inputLine = podcastReader.readLine()) != null)
{
result.append( inputLine );
}
}
finally
{
if ( podcastStream != null ) podcastStream.close();
if ( podcastReader != null ) podcastReader.close();
}
return result.toString();
}
}
| Java |
/**
* Copyright (c) 2011 Basil Shikin, VintageRadio Project
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.vintagephone.model;
public enum MusicFolder
{
ONE,
TWO,
THREE,
FOUR;
}
| Java |
/**
* Copyright (c) 2011 Basil Shikin, VintageRadio Project
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.vintagephone.model.hardware.ioio;
import ioio.lib.api.IOIO;
import ioio.lib.api.IOIOFactory;
import ioio.lib.api.exception.ConnectionLostException;
import android.util.Log;
/**
*
* Based on implementation in AbstractIOIOActivity
*
*/
public class IOIOThreadBase extends Thread {
/** Subclasses should use this field for controlling the IOIO. */
protected IOIO m_ioio;
private boolean m_abort = false;
/** Not relevant to subclasses. */
@Override
public final void run() {
super.run();
while (true) {
try {
synchronized (this) {
if (m_abort) {
break;
}
m_ioio = IOIOFactory.create();
}
m_ioio.waitForConnect();
setup();
while (true) {
loop();
}
} catch (ConnectionLostException e) {
if (m_abort) {
break;
}
} catch (Exception e) {
Log.e("AbstractIOIOActivity",
"Unexpected exception caught", e);
m_ioio.disconnect();
break;
} finally {
try {
m_ioio.waitForDisconnect();
} catch (InterruptedException e) {
}
}
}
}
/**
* Subclasses should override this method for performing operations to
* be done once as soon as IOIO communication is established. Typically,
* this will include opening pins and modules using the openXXX()
* methods of the {@link #m_ioio} field.
*/
protected void setup() throws ConnectionLostException {
}
/**
* Subclasses should override this method for performing operations to
* be done repetitively as long as IOIO communication persists.
* Typically, this will be the main logic of the application, processing
* inputs and producing outputs.
*/
protected void loop() throws ConnectionLostException {
}
/** Not relevant to subclasses. */
public synchronized final void abort() {
m_abort = true;
if (m_ioio != null) {
m_ioio.disconnect();
}
}
} | Java |
/**
* Copyright (c) 2011 Basil Shikin, VintageRadio Project
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.vintagephone.model.hardware.ioio;
import ioio.lib.api.AnalogInput;
import ioio.lib.api.DigitalInput;
import ioio.lib.api.DigitalInput.Spec.Mode;
import ioio.lib.api.exception.ConnectionLostException;
import org.vintagephone.model.hardware.RadioHardwareListener;
import android.util.Log;
public class IOIORadioHardwareThread
extends IOIOThreadBase
{
private static final String TAG = "IOIORadioHardwareThread";
private static final float VOLUME_CHANGE_THRESHOLD = 0.05F;
private static final int SKIP_VOLUME_COUNT = 100;
private static final int VOLUME_READ_ATTEMPTS = 10;
// Sensors
private AnalogInput m_volumeSensor;
private DigitalInput m_onSensor;
private DigitalInput[] m_buttonSensors;
private DigitalInput m_rotASensor;
private DigitalInput m_rotBSensor;
// States
private float m_volume;
private boolean m_isOn;
private boolean[] m_buttonStates;
private boolean m_rotAOn;
private boolean m_rotBOn;
private int m_rotPosition;
private int m_skipVolumeCount;
// Listeners
private RadioHardwareListener m_hardwareListener;
private DebugListener m_debugListener;
public void setListener(RadioHardwareListener listener)
{
m_hardwareListener = listener;
if ( m_hardwareListener != null )
{
m_hardwareListener.onStateChanged( m_isOn );
m_hardwareListener.volumeChanged( m_volume );
}
}
public void setDebugListener(DebugListener debugListener)
{
m_debugListener = debugListener;
}
@Override
protected void setup() throws ConnectionLostException
{
super.setup();
m_onSensor = m_ioio.openDigitalInput( 4, Mode.PULL_DOWN );
m_volumeSensor = m_ioio.openAnalogInput( 33 );
m_buttonSensors = new DigitalInput[4];
m_buttonSensors[0] = m_ioio.openDigitalInput( 11, Mode.PULL_UP );
m_buttonSensors[1] = m_ioio.openDigitalInput( 12, Mode.PULL_UP );
m_buttonSensors[2] = m_ioio.openDigitalInput( 13, Mode.PULL_UP );
m_buttonSensors[3] = m_ioio.openDigitalInput( 14, Mode.PULL_UP );
m_buttonStates = new boolean[4];
for ( int i = 0; i < m_buttonStates.length; i++ ) m_buttonStates[i] = true; // All on by default
m_rotASensor = m_ioio.openDigitalInput( 5, Mode.PULL_UP );
m_rotBSensor = m_ioio.openDigitalInput( 6, Mode.PULL_UP );
}
@Override
protected void loop() throws ConnectionLostException
{
boolean stateChanged = false;
try
{
stateChanged |= processOnButton();
if ( m_isOn )
{
stateChanged |= processSongRot();
stateChanged |= processVolumePot();
stateChanged |= processStationButtons();
Thread.sleep( 5 );
}
else
{
Thread.sleep( 50 );
}
}
catch ( ConnectionLostException e)
{
if ( m_isOn )
{
m_isOn = false;
if ( m_hardwareListener != null ) m_hardwareListener.onStateChanged( false );
}
throw e;
}
catch (InterruptedException e)
{
return;
}
if ( stateChanged )
{
final String hardwareState = buildStateString();
if ( m_debugListener != null ) m_debugListener.printDebugMessage( "Device state: " + hardwareState );
Log.d( TAG, "Device state: " + hardwareState );
}
}
private boolean processStationButtons() throws InterruptedException, ConnectionLostException
{
boolean stateChanged = false;
for ( int i = 0; i < m_buttonStates.length; i++ )
{
final boolean newState = m_buttonSensors[i].read();
if ( newState != m_buttonStates[i] )
{
stateChanged = true;
m_buttonStates[i] = newState;
// If button is pressed
if ( newState )
{
if ( m_hardwareListener != null ) m_hardwareListener.buttonPressed( i );
}
}
}
return stateChanged;
}
private boolean processVolumePot() throws InterruptedException, ConnectionLostException
{
boolean stateChanged = false;
if ( m_skipVolumeCount - 1 < 1 )
{
float volumeReading = 0;
for ( int i = 0; i < VOLUME_READ_ATTEMPTS; i++ )
{
volumeReading += m_volumeSensor.read();
}
volumeReading = volumeReading/VOLUME_READ_ATTEMPTS;
final float newVolume = 1 - volumeReading;
if ( Math.abs( newVolume - m_volume ) > VOLUME_CHANGE_THRESHOLD )
{
stateChanged = true;
m_volume = newVolume;
if ( m_hardwareListener != null ) m_hardwareListener.volumeChanged( newVolume );
}
m_skipVolumeCount = SKIP_VOLUME_COUNT;
}
m_skipVolumeCount -= 1;
return stateChanged;
}
private boolean processOnButton() throws InterruptedException, ConnectionLostException
{
boolean stateChanged = false;
final boolean isOnNow = m_onSensor.read();
if ( isOnNow != m_isOn )
{
stateChanged = true;
m_isOn = isOnNow;
if ( m_hardwareListener != null ) m_hardwareListener.onStateChanged( isOnNow );
}
return stateChanged;
}
private boolean processSongRot() throws ConnectionLostException, InterruptedException
{
boolean stateChanged = false;
final boolean newRotA = m_rotASensor.read();
final boolean newRotB = m_rotBSensor.read();
if ( m_rotAOn == true && newRotA == false )
{
stateChanged = true;
if ( newRotB )
{
m_rotPosition += 1;
}
else
{
m_rotPosition -= 1;
}
if ( m_hardwareListener != null ) m_hardwareListener.songSelectorChanged( m_rotPosition );
}
m_rotAOn = newRotA;
m_rotBOn = newRotB;
return stateChanged;
}
private String buildStateString()
{
final StringBuffer result = new StringBuffer("[");
result.append("on: ").append( m_isOn );
result.append(", volume: ").append( m_volume );
result.append(", buttons: ");
for ( int i = 0; i < m_buttonStates.length; i++ )
{
result.append( m_buttonStates[i] ? 1 : 0 );
}
result.append(", selector: ").append( m_rotPosition ).append( ": ");
result.append( "[" ).append( m_rotAOn ? 1 : 0 ).append( "|" ).append( m_rotBOn ? 1 : 0 );
result.append("]");
return result.toString();
}
public interface DebugListener
{
void printDebugMessage( final String message );
}
}
| Java |
/**
* Copyright (c) 2011 Basil Shikin, VintageRadio Project
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.vintagephone.model.hardware;
/**
* This interface defines a listener for radio hardware events.
*
* @author Basil Shikin
*
*/
public interface RadioHardwareListener
{
void onStateChanged(boolean isOnNow);
void volumeChanged(float newVolume);
void buttonPressed(int buttonNo);
void songSelectorChanged(int rotPosition);
}
| Java |
/**
* Copyright (c) 2011 Basil Shikin, VintageRadio Project
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.vintagephone.model.hardware;
import org.vintagephone.model.RadioControlListener;
import org.vintagephone.model.hardware.ioio.IOIORadioHardwareThread;
/**
* This class contains support for radio hardware interaction
* @author Basil Shikin
*
*/
public class RadioHardwareControl
implements RadioHardwareListener
{
private final IOIORadioHardwareThread m_hardwareThread;
private RadioControlListener m_listener;
private int m_lastRotPosition;
public RadioHardwareControl()
{
m_hardwareThread = new IOIORadioHardwareThread();
}
public void initialize()
{
m_hardwareThread.setListener( this );
m_hardwareThread.start();
}
public void setListener( RadioControlListener listener )
{
m_listener = listener;
}
@Override
public void onStateChanged(boolean isOnNow)
{
if ( m_listener != null ) m_listener.offStateChaneged( !isOnNow );
}
@Override
public void volumeChanged(float newVolume)
{
if ( m_listener != null ) m_listener.volumeChanged( Math.round( 100F*newVolume ) );
}
@Override
public void buttonPressed(int buttonNo)
{
if (m_listener != null ) m_listener.folderChanged( buttonNo );
}
@Override
public void songSelectorChanged(int rotPosition)
{
if ( rotPosition != m_lastRotPosition )
{
if ( m_listener != null ) m_listener.songChanged( rotPosition > m_lastRotPosition );
}
m_lastRotPosition = rotPosition;
}
}
| Java |
/**
* Copyright (c) 2011 Basil Shikin, VintageRadio Project
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.vintagephone.model.player;
import java.io.File;
import java.io.FileFilter;
import java.lang.ref.SoftReference;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.vintagephone.model.MusicFolder;
import org.vintagephone.model.Song;
public class PlayerUtils
{
private static final Map<String, SoftReference<Song>> s_songCache = new HashMap<String, SoftReference<Song>>();
private static final String s_musicFolderBase = "/sdcard/VintageRadio";
private static final String s_folderOne = "Jazz";
private static final String s_folderTwo = "Piano";
private static final String s_folderThree = "Misc";
private static final String s_folderFour = "News";
public static List<Song> loadFolderSongs(MusicFolder folder)
{
final File folderFile = resolveFolderFile( folder );
final File[] files = folderFile.listFiles( new FileFilter() {
public boolean accept(File pathname) {
return pathname.getName().endsWith(".mp3");
}
} );
if ( files != null && files.length > 0 )
{
final List<Song> result = new ArrayList<Song>( files.length );
for ( File file : files )
{
final Song song;
final String path = file.getAbsolutePath();
final SoftReference<Song> songRef = s_songCache.get( path );
if ( songRef != null && songRef.get() != null )
{
song = songRef.get();
}
else
{
song = new Song( file );
s_songCache.put( path, new SoftReference<Song>( song ) );
}
if ( song == null ) throw new RuntimeException("Programming error: no song for \"" + path + "\"");
result.add( song );
}
return result;
}
else
{
return Collections.emptyList();
}
}
public static File resolveFolderFile(MusicFolder folder)
{
switch ( folder) {
case ONE:
return new File( s_musicFolderBase, s_folderOne );
case TWO:
return new File( s_musicFolderBase, s_folderTwo );
case THREE:
return new File( s_musicFolderBase, s_folderThree );
case FOUR:
return new File( s_musicFolderBase, s_folderFour );
default:
throw new IllegalArgumentException("Unknown foldeer: " + folder);
}
}
}
| Java |
/**
* Copyright (c) 2011 Basil Shikin, VintageRadio Project
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.vintagephone.model.player;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.vintagephone.model.MusicFolder;
import org.vintagephone.model.Song;
import org.vintagephone.model.player.Player.NextSongCallback;
import android.content.Context;
import android.media.AudioManager;
import android.util.Log;
/**
* This class is used to track available songs and feed properly feed next
* song to the player
* @author Basil Shikin
*
*/
public class PlayerControl
{
protected static final String Tag = "PlayerControl";
// Parent objects
private final Context m_context;
// Controlled objects
private final Object m_songControlLock = new Object();
private final PlayerMediaScanner m_scanner;
private final Player m_player;
// State variables
private MusicFolder m_activeFolder;
private Song m_activeSong;
private final Map<MusicFolder, Song> m_activeSongs = new HashMap<MusicFolder, Song>();
private final Map<MusicFolder, List<Song>> m_folderSongs = new HashMap<MusicFolder, List<Song>>();
public PlayerControl( Context context )
{
m_context = context;
m_scanner = new PlayerMediaScanner( context );
m_player = new Player();
}
public void initialize()
{
}
public void setNextSongCallback( final NextSongCallback nextSongCallback )
{
m_player.setNextSongCallback( nextSongCallback );
}
public Song switchToFolder( MusicFolder folder )
{
// Determine what song to play now
final Song activeSong;
synchronized ( m_songControlLock )
{
m_activeFolder = folder;
final List<Song> folderSongs = PlayerUtils.loadFolderSongs( folder );
if ( !folderSongs.isEmpty() )
{
// Shuffle songs
if ( folder != MusicFolder.FOUR )
{
Collections.shuffle( folderSongs );
}
// Schedule a scan of folder songs
scanFolderSongs( folderSongs );
if ( m_activeSongs.get( folder ) != null )
{
final Song possibleSong = m_activeSongs.get( folder );
if ( folderSongs.contains( possibleSong ) )
{
activeSong = possibleSong;
}
else if ( !folderSongs.isEmpty() )
{
activeSong = folderSongs.get( 0 );
}
else
{
activeSong = null;
}
}
else if ( !folderSongs.isEmpty() )
{
activeSong = folderSongs.get( 0 );
}
else
{
activeSong = null;
}
if ( activeSong != null )
{
m_activeSong = activeSong;
playSong( activeSong );
}
m_activeSongs.put( folder, activeSong );
}
else
{
activeSong = null;
}
// Save songs in active folder
m_folderSongs.put( folder, folderSongs );
}
return activeSong;
}
public Song switchToNextSong()
{
synchronized ( m_songControlLock )
{
if ( m_activeSong != null )
{
final List<Song> activeFolderSongs = m_folderSongs.get( m_activeFolder );
final int currentSongIx = activeFolderSongs.indexOf( m_activeSong );
final int nextSongIx = (currentSongIx + 1) % activeFolderSongs.size();
final Song activeSong = activeFolderSongs.get( nextSongIx );
playSong(activeSong);
}
return m_activeSong;
}
}
public Song switchToPreviousSong()
{
synchronized ( m_songControlLock )
{
if ( m_activeSong != null )
{
final List<Song> activeFolderSongs = m_folderSongs.get( m_activeFolder );
final int currentSongIx = activeFolderSongs.indexOf( m_activeSong );
final int nextSongIx = currentSongIx > 0 ? currentSongIx - 1 : activeFolderSongs.size() - 1;
final Song activeSong = activeFolderSongs.get( nextSongIx );
playSong(activeSong);
}
return m_activeSong;
}
}
public Song setIsOn(boolean isOn)
{
if ( isOn )
{
Log.d(Tag, "Resuming platback...");
if ( m_activeSong != null )
{
m_player.play( m_activeSong );
}
else
{
switchToNextSong();
}
return m_activeSong;
}
else
{
Log.d(Tag, "Pausing platback...");
m_player.pause();
return null;
}
}
public void setVolume(int percent)
{
final AudioManager audioManager = (AudioManager)m_context.getSystemService(Context.AUDIO_SERVICE);
final int streamType = AudioManager.STREAM_MUSIC;
final int maxVolume = audioManager.getStreamMaxVolume( streamType );
final int newVolume = Math.round( (percent/100F)*maxVolume );
audioManager.setStreamVolume(streamType, newVolume, 0 );
}
public List<Song> getActiveFolderSongs()
{
synchronized ( m_songControlLock )
{
return m_folderSongs.get( m_activeFolder );
}
}
private void scanFolderSongs(List<Song> folderSongs)
{
for ( Song song : folderSongs )
{
m_scanner.scanSong( song );
}
}
private void playSong(Song activeSong)
{
Log.d(Tag, "Playing: " + activeSong );
if ( activeSong != null )
{
m_activeSong = activeSong;
m_activeSongs.put( m_activeFolder, activeSong);
m_player.play( activeSong );
}
else
{
m_player.stop();
}
}
}
| Java |
/**
* Copyright (c) 2011 Basil Shikin, VintageRadio Project
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.vintagephone.model.player;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import org.cmc.music.metadata.IMusicMetadata;
import org.cmc.music.metadata.MusicMetadataSet;
import org.cmc.music.myid3.MyID3;
import org.vintagephone.model.Song;
import android.content.Context;
import android.util.Log;
/**
* This class is used to scan songs for metadata
* @author Basil Shikin
*
*/
public class PlayerMediaScanner
{
private static final String Tag = "PlayerMediaScanner";
private static final Executor s_executor = Executors.newSingleThreadExecutor();
private final Context m_context;
public PlayerMediaScanner(Context context)
{
m_context = context;
}
public void scanSong( final Song song )
{
if ( !song.isScanned() )
{
s_executor.execute( new ScanSongTask( song, m_context ) );
}
}
private static class ScanSongTask
implements Runnable
{
private final Song m_song;
ScanSongTask(Song song, Context context)
{
m_song = song;
}
public void run()
{
Log.d(Tag, "Scanning " + m_song + "...");
try
{
final MusicMetadataSet mp3set = new MyID3().read( m_song.getFile() );
final IMusicMetadata mp3data = mp3set.getSimplified();
final String track = mp3data.getSongTitle();
final String album = mp3data.getAlbum();
final String artist = mp3data.getArtist();
if (track != null && album != null && artist != null)
{
m_song.setSongInformation( track, album, artist );
Log.d(Tag, "Scan of " + m_song + " completed: " + track + " - " + artist + " - " + album );
}
else
{
Log.w( Tag, "Scan of " + m_song + " failed: song seems to have bad metadata" );
}
}
catch ( Throwable e )
{
Log.e( Tag, "Scan of " + m_song + " failed", e );
}
}
}
}
| Java |
/**
* Copyright (c) 2011 Basil Shikin, VintageRadio Project
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.vintagephone.model.player;
import java.io.IOException;
import org.vintagephone.model.Song;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.util.Log;
/**
* This class represents media player that is able to scan songs and play a song.
*
* @author Basil Shikin
*
*/
public class Player
{
private static final String Tag = "Player";
// Controlled objects
private final MediaPlayer m_player;
private NextSongCallback m_nextSongCallback;
public Player()
{
m_player = new MediaPlayer();
m_player.setOnCompletionListener( new SongCompletionListener() );
}
public void setNextSongCallback(NextSongCallback nextSongCallback)
{
m_nextSongCallback = nextSongCallback;
}
/**
* Start playing given song
*
* @param song Song to play
*/
public void play( Song song )
{
Log.i( Tag, "Starting to play " + song);
try
{
m_player.reset();
m_player.setDataSource( song.getFile().getAbsolutePath() );
m_player.prepare();
m_player.start();
}
catch (IOException e)
{
Log.e( Tag, "Unable to play " + song, e);
}
}
/**
* Pause current song
*/
public void pause()
{
m_player.pause();
}
/**
* Stop playback
*/
public void stop()
{
m_player.stop();
}
/**
* This interface defines a callback that is invoked when song
* is finished playing
*
* @author Basil Shikin
*
*/
public interface NextSongCallback
{
void switchToNextSong();
}
/**
* Internal listener for next song
*
* @author Basil Shikin
*
*/
private class SongCompletionListener
implements OnCompletionListener
{
public void onCompletion(MediaPlayer player)
{
Log.i( Tag, "Song completed, switching to next song");
if ( m_nextSongCallback != null ) m_nextSongCallback.switchToNextSong();
}
}
}
| Java |
/**
* Copyright (c) 2011 Basil Shikin, VintageRadio Project
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.vintagephone.model;
import java.io.File;
/**
* This class represetns a song that could be played
*
* @author Basil Shikin
*
*/
public class Song
{
private final File m_file;
private volatile boolean m_isScanned = false;;
private String m_track;
private String m_album;
private String m_artist;
public Song(File file)
{
if ( file == null ) throw new IllegalArgumentException("No file specified");
if ( !file.isFile()) throw new IllegalArgumentException("Specified file is not a file");
m_file = file;
}
public boolean isScanned()
{
return m_isScanned;
}
public File getFile()
{
return m_file;
}
public String getTrack()
{
return m_track;
}
public String getAlbum()
{
return m_album;
}
public String getArtist()
{
return m_artist;
}
public void setSongInformation( String track, String album, String artist )
{
m_track = track;
m_album = album;
m_artist = artist;
m_isScanned = true;
}
@Override
public String toString()
{
return "[Song file:" + m_file.getAbsolutePath() + "]";
}
}
| Java |
/**
* Copyright (c) 2011 Basil Shikin, VintageRadio Project
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.vintagephone.model;
/**
* This interface defines a listener for playback control commands.
*
* @author Basil Shikin
*
*/
public interface RadioControlListener
{
/**
* Knob that selects a song was moved
*
* @param isDown True if next song is requested (knob was moved down)
*/
void songChanged( final boolean playNext );
/**
* A button that selects different folder was pressed
*
* @param buttonNumber Number of button
*/
void folderChanged( int buttonNumber );
/**
* Volume knob changed
*
* @param percent New volume (in percent)
*/
void volumeChanged( final int percent );
/**
* Radio turned on or off
*
* @param isOff True if new state is 'off'
*/
void offStateChaneged( final boolean isOff );
}
| Java |
/**
* Copyright (c) 2011 Basil Shikin, VintageRadio Project
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.vintagephone.model;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import org.vintagephone.model.hardware.RadioHardwareControl;
import org.vintagephone.model.player.Player.NextSongCallback;
import org.vintagephone.model.player.PlayerControl;
import org.vintagephone.model.player.PlayerUtils;
import org.vintagephone.model.podcaster.Podcaster;
import org.vintagephone.view.flat.RadioDialController;
import android.content.Context;
import android.os.PowerManager;
import android.os.PowerManager.WakeLock;
import android.view.View;
/**
* This class manages radio lifecycle. It is used to respond to events
* that are generated from the player, UI and hardware.
*
* @author Basil Shikin
*
*/
public class RadioLifecycle
{
private static final String Tag = "RadioLifecycle";
private final static ExecutorService s_operationExecutor;
static
{
s_operationExecutor = Executors.newSingleThreadExecutor();
}
// Parent objects
private final Context m_context;
// Controlled objects
private final PlayerControl m_playerControl;
private final RadioDialController m_viewControl;
private final RadioHardwareControl m_hardwareControl;
private final Podcaster m_podcaster;
private final ControlListener m_controlListener;
private WakeLock m_wakeLock;
public RadioLifecycle( Context context )
{
m_context = context;
m_playerControl = new PlayerControl(context);
m_viewControl = new RadioDialController( context );
m_hardwareControl = new RadioHardwareControl();
m_podcaster = new Podcaster( PlayerUtils.resolveFolderFile( MusicFolder.FOUR ) );
m_controlListener = new ControlListener();
}
public void initialize()
{
final PowerManager pm = (PowerManager)m_context.getSystemService( Context.POWER_SERVICE );
m_wakeLock = pm.newWakeLock( PowerManager.FULL_WAKE_LOCK
| PowerManager.ACQUIRE_CAUSES_WAKEUP
| PowerManager.ON_AFTER_RELEASE, Tag );
m_playerControl.initialize();
m_viewControl.initialize();
m_hardwareControl.initialize();
m_podcaster.initialize();
switchToFolder( MusicFolder.ONE ); // Select fist folder as default
m_playerControl.setNextSongCallback( m_controlListener );
m_viewControl.setListener( m_controlListener );
m_hardwareControl.setListener( m_controlListener );
}
public View getView()
{
return m_viewControl.getView();
}
private void switchToFolder( final MusicFolder folder )
{
final Song song = m_playerControl.switchToFolder( folder );
m_viewControl.setScreenSongs(folder.ordinal(), m_playerControl.getActiveFolderSongs() );
m_viewControl.switchToScreen( folder.ordinal() );
m_viewControl.switchToSong( song );
}
private class ControlListener
implements RadioControlListener, NextSongCallback
{
public void switchToNextSong()
{
songChanged( true );
}
public void songChanged(final boolean playNext)
{
s_operationExecutor.execute( new Runnable() {
public void run()
{
if ( !m_wakeLock.isHeld() ) m_wakeLock.acquire();
if ( playNext )
{
final Song song = m_playerControl.switchToNextSong();
m_viewControl.switchToSong( song );
}
else
{
final Song song = m_playerControl.switchToPreviousSong();
m_viewControl.switchToSong( song );
}
}
} );
}
public void folderChanged(final int buttonNumber)
{
s_operationExecutor.execute( new Runnable() {
public void run()
{
if ( !m_wakeLock.isHeld() ) m_wakeLock.acquire();
final MusicFolder folder = MusicFolder.values()[ buttonNumber ];
switchToFolder( folder );
}
} );
}
public void offStateChaneged(final boolean isOff)
{
s_operationExecutor.execute( new Runnable() {
public void run()
{
if ( isOff )
{
if ( m_wakeLock.isHeld() ) m_wakeLock.release();
}
else
{
if ( !m_wakeLock.isHeld() ) m_wakeLock.acquire();
}
m_viewControl.setOff( isOff );
final Song song = m_playerControl.setIsOn( !isOff );
if ( song != null )
{
m_viewControl.switchToSong( song );
}
}
} );
}
public void volumeChanged(final int percent)
{
s_operationExecutor.execute( new Runnable() {
public void run()
{
if ( !m_wakeLock.isHeld() ) m_wakeLock.acquire();
m_viewControl.setVolume( percent );
m_playerControl.setVolume( percent );
}
} );
}
}
}
| Java |
/**
* Copyright (c) 2011 Basil Shikin, VintageRadio Project
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.vintagephone.view.flat;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.view.GestureDetector;
import android.view.GestureDetector.OnDoubleTapListener;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
public class RadioDial
extends View
{
private static final int BACKGROUND_ANIMATION_STEP = 15;
// Parent objects
private final RadioDialController m_controller;
// Controlled objects
private final GestureDetector m_gestureDetector;
private final RadioScreen[] m_screens;
// State variables
private int m_backgroundXOffset;
private int m_targetBackgroundXOffset;
private int m_backgroundStepDirection = 1;
public RadioDial(RadioDialController radioDialController, final Context context)
{
super(context);
m_controller = radioDialController;
final FlingGestureDetector flingDetector = new FlingGestureDetector( m_controller );
m_gestureDetector = new GestureDetector( context, flingDetector );
m_gestureDetector.setOnDoubleTapListener( new OnDoubleTapListener() {
public boolean onDoubleTap(MotionEvent e)
{
android.os.Process.killProcess( android.os.Process.myPid() );
return false;
}
public boolean onDoubleTapEvent(MotionEvent e) { return false; }
public boolean onSingleTapConfirmed(MotionEvent e) { return false; }
});
setOnKeyListener( new OnKeyListener() {
@Override
public boolean onKey(View arg0, int arg1, KeyEvent event) {
if ( event.getAction() != KeyEvent.ACTION_UP ) return true;
if ( event.getKeyCode() == KeyEvent.KEYCODE_DPAD_LEFT )
{
m_controller.onSwipeLeft();
}
else if ( event.getKeyCode() == KeyEvent.KEYCODE_DPAD_RIGHT)
{
m_controller.onSwipeRight();
}
else if ( event.getKeyCode() == KeyEvent.KEYCODE_DPAD_UP)
{
m_controller.onSwipeUp();
}
else if ( event.getKeyCode() == KeyEvent.KEYCODE_DPAD_DOWN)
{
m_controller.onSwipeDown();
}
return false;
}
});
setFocusable( true );
setFocusableInTouchMode( true );
m_screens = new RadioScreen[ RadioDialController.SCREEN_COUNT ];
for ( int i = 0; i < m_screens.length; i++ )
{
m_screens[i] = new RadioScreen(i, m_controller, context);
}
}
@Override
public void draw(Canvas canvas)
{
canvas.save();
canvas.setDensity( Bitmap.DENSITY_NONE );
float py = this.getHeight()/2.0f;
float px = this.getWidth()/2.0f;
canvas.rotate(180, px, py);
boolean invalidate = false;
// Draw screens
for ( int i = 0; i < m_screens.length; i++ )
{
final RadioScreen screen = m_screens[i];
final int screenOffset = m_backgroundXOffset + i*screen.getWidth();
// If screen is visible
if ( screenOffset + screen.getWidth() > 0 && screenOffset < getWidth() )
{
canvas.save();
canvas.translate( screenOffset, 0 );
screen.draw( canvas );
invalidate |= screen.prepareAnimationState();
canvas.restore();
}
}
invalidate |= prepareAnimationState();
if ( invalidate )
{
invalidate();
}
}
@Override
public boolean onTouchEvent(MotionEvent event)
{
return m_gestureDetector.onTouchEvent(event);
}
@Override
public boolean isClickable()
{
return true;
}
@Override
public boolean isInTouchMode()
{
return true;
}
void showSong( int songNumber, int screen)
{
m_screens[ screen ].showSong(songNumber);
invalidate();
}
void showScreen( int number )
{
final int screenOffset = calculateBackgroundOffset( number );
if ( m_backgroundXOffset == screenOffset) return;
if ( screenOffset > m_backgroundXOffset )
{
m_backgroundStepDirection = BACKGROUND_ANIMATION_STEP;
}
else
{
m_backgroundStepDirection = -BACKGROUND_ANIMATION_STEP;
}
m_targetBackgroundXOffset = screenOffset;
invalidate();
}
private int calculateBackgroundOffset(int number)
{
return -number*m_screens[number].getWidth();
}
private boolean prepareAnimationState()
{
boolean bgNeedsRepaint = false;
if ( isMovingBackground() )
{
m_backgroundXOffset += m_backgroundStepDirection;
bgNeedsRepaint = true;
}
else
{
if ( m_backgroundXOffset != m_targetBackgroundXOffset )
{
bgNeedsRepaint = true;
}
m_backgroundXOffset = m_targetBackgroundXOffset;
}
return bgNeedsRepaint;
}
private boolean isMovingBackground()
{
return Math.abs( m_targetBackgroundXOffset - m_backgroundXOffset ) > BACKGROUND_ANIMATION_STEP/2;
}
private static class FlingGestureDetector
extends GestureDetector.SimpleOnGestureListener
{
private static final int SWIPE_X_MIN_DISTANCE = 80;
private static final int SWIPE_Y_MIN_DISTANCE = 40;
private static final int SWIPE_MAX_OFF_PATH = 250;
private static final int SWIPE_X_THRESHOLD_VELOCITY = 60;
private static final int SWIPE_Y_THRESHOLD_VELOCITY = 60;
private final RadioDialController m_controller;
FlingGestureDetector(RadioDialController controller)
{
m_controller = controller;
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY)
{
try
{
if (Math.abs(e1.getY() - e2.getY()) > SWIPE_MAX_OFF_PATH) return false;
if(e1.getX() - e2.getX() > SWIPE_X_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_X_THRESHOLD_VELOCITY)
{
m_controller.onSwipeLeft();
}
else if (e2.getX() - e1.getX() > SWIPE_X_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_X_THRESHOLD_VELOCITY)
{
m_controller.onSwipeRight();
}
else if(e1.getY() - e2.getY() > SWIPE_Y_MIN_DISTANCE && Math.abs(velocityY) > SWIPE_Y_THRESHOLD_VELOCITY)
{
m_controller.onSwipeDown();
}
else if (e2.getY() - e1.getY() > SWIPE_Y_MIN_DISTANCE && Math.abs(velocityY) > SWIPE_Y_THRESHOLD_VELOCITY)
{
m_controller.onSwipeUp();
}
}
catch (Exception e) {}
return super.onFling(e1, e2, velocityX, velocityY);
}
@Override
public boolean onDown(MotionEvent e) {
return true;
}
}
}
| Java |
/**
* Copyright (c) 2011 Basil Shikin, VintageRadio Project
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.vintagephone.view.flat;
import java.util.List;
import org.vintagephone.R;
import org.vintagephone.model.RadioControlListener;
import org.vintagephone.model.Song;
import android.content.Context;
import android.content.res.Resources;
import android.util.Log;
import android.view.View;
@SuppressWarnings("unchecked")
public class RadioDialController
{
public static final int SCREEN_COUNT = 4;
private static final String Tag = "RadioDialController";
// Parent objects
final Context m_context;
// Controlled bojecxts
private final RadioDial m_view;
// State objects
private int m_activeScreen = 0;
private int[] m_activeSong = new int[ SCREEN_COUNT ];
private List<Song>[] m_screenSongs = new List[ SCREEN_COUNT ];
private RadioControlListener m_listener;
private int m_volume;
private boolean m_isOff;
public RadioDialController(Context context)
{
m_context = context;
m_view = new RadioDial( this, context );
}
/**
* Attach a listener for application UI events
*
* @param listener Listener to attach
*/
public void setListener(RadioControlListener listener)
{
m_listener = listener;
}
public void initialize()
{
}
public View getView()
{
return m_view;
}
public int getVolume()
{
return m_volume;
}
public boolean getIsOff()
{
return m_isOff;
}
public void setVolume(int volume)
{
m_volume = volume;
m_view.postInvalidate();
}
public void setOff(boolean isOff)
{
m_isOff = isOff;
m_view.postInvalidate();
}
public void setScreenSongs( final int screen, final List<Song> songs )
{
m_screenSongs[ screen ] = songs;
}
public void switchToSong( final Song song)
{
final int screen = m_activeScreen;
final int songNumber = m_screenSongs[ screen ].indexOf( song );
if ( songNumber >= 0 )
{
m_activeSong[screen] = songNumber;
m_view.post(new Runnable() {
public void run()
{
m_view.showSong( m_activeSong[m_activeScreen], m_activeScreen );
}
} );
}
}
public void switchToScreen(int screen)
{
Log.d( Tag, "Showing screen " + screen );
m_activeScreen = screen;
m_view.post(new Runnable() {
public void run()
{
m_view.showScreen( m_activeScreen );
}
} );
}
void onSwipeLeft()
{
Log.d( Tag, "Handling left swipe..." );
final int newFolder = m_activeScreen - 1;
if ( newFolder >= 0 )
{
if ( m_listener != null ) m_listener.folderChanged( newFolder );
}
}
void onSwipeRight()
{
Log.d( Tag, "Handling right swipe..." );
final int newFolder = m_activeScreen + 1;
if ( newFolder < SCREEN_COUNT )
{
if ( m_listener != null ) m_listener.folderChanged( newFolder );
}
}
void onSwipeUp()
{
Log.d( Tag, "Handling swipe up..." );
if ( m_listener != null ) m_listener.songChanged( true );
}
void onSwipeDown()
{
Log.d( Tag, "Handling swipe down..." );
if ( m_listener != null ) m_listener.songChanged( false );
}
String getScreenTitle(int screen)
{
final Resources resources = m_context.getResources();
switch ( screen)
{
case 0: return resources.getString( R.string.folder_one_name );
case 1: return resources.getString( R.string.folder_two_name );
case 2: return resources.getString( R.string.folder_three_name );
case 3: return resources.getString( R.string.folder_four_name );
default: throw new IllegalArgumentException("Unknown screen: " + screen );
}
}
List<Song> getScreenSongs( int screen)
{
return m_screenSongs[ screen ];
}
int getActiveSong(int screen)
{
return m_activeSong[screen];
}
}
| Java |
/**
* Copyright (c) 2011 Basil Shikin, VintageRadio Project
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.vintagephone.view.flat;
import java.util.List;
import org.vintagephone.R;
import org.vintagephone.model.Song;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Paint.Style;
import android.graphics.Rect;
import android.graphics.Typeface;
/**
* This class defines a single radio dial.
*
* @author Basil Shikin
*
*/
class RadioScreen
{
private static final int SONG_DISTANCE = 90;
private static final int SONG_ANIMATION_STEP = 2;
// Parent objects
private final int m_screenNumber;
private final RadioDialController m_controller;
private final Bitmap m_background;
private final Bitmap m_volumeSelector;
private final int m_width;
private final int m_height;
private final Paint m_bitmapPaint;
private final Paint m_screenTitleFgPaint;
private final Paint m_screenTitleBgPaint;
private final Paint m_songNamePaint;
private final Paint m_detailsPaint;
// State variables
private int m_songNameYOffset;
private int m_targetSongNameYOffset;
private int m_songNameStepDirection;
// Constants
private final String m_noSongsString;
private final String m_scanningString;
public RadioScreen(int screenNumber, final RadioDialController radioDialController, final Context context)
{
m_screenNumber = screenNumber;
m_controller = radioDialController;
m_background = BitmapFactory.decodeResource( context.getResources(), R.drawable.dial );
m_width = m_background.getWidth();
m_height = m_background.getHeight();
m_volumeSelector = BitmapFactory.decodeResource( context.getResources(), R.drawable.selector );
m_bitmapPaint = new Paint();
m_bitmapPaint.setColor( Color.BLACK );
m_bitmapPaint.setStyle( Style.FILL );
m_bitmapPaint.setFilterBitmap( true );
m_songNamePaint = new Paint();
m_songNamePaint.setColor( Color.rgb( 68, 0, 0) );
m_songNamePaint.setAntiAlias( true );
m_songNamePaint.setTextSize( 24F );
m_songNamePaint.setTypeface( Typeface.createFromAsset( context.getAssets(), "fonts/optima-bold.ttf" ) );
m_screenTitleFgPaint = new Paint();
m_screenTitleFgPaint.setColor( Color.rgb( 22, 22, 22) );
m_screenTitleFgPaint.setAntiAlias( true );
m_screenTitleFgPaint.setTextSize( 12.5F );
m_screenTitleFgPaint.setTypeface( Typeface.createFromAsset( context.getAssets(), "fonts/optima-bold.ttf" ) );
m_screenTitleBgPaint = new Paint();
m_screenTitleBgPaint.setColor( Color.argb( 100, 255, 255, 255 ) );
m_screenTitleBgPaint.setAntiAlias( true );
m_screenTitleBgPaint.setTextSize( 12.5F );
m_screenTitleBgPaint.setTypeface( Typeface.createFromAsset( context.getAssets(), "fonts/optima-bold.ttf" ) );
m_detailsPaint = new Paint();
m_detailsPaint.setColor( Color.rgb( 68, 0, 0) );
m_detailsPaint.setTextSize( 18F );
m_detailsPaint.setAntiAlias( true );
m_detailsPaint.setTypeface( Typeface.createFromAsset( context.getAssets(), "fonts/optima-normal.ttf" ) );
m_noSongsString = context.getResources().getString( R.string.no_songs );
m_scanningString = context.getResources().getString( R.string.scanning );
}
void draw(Canvas canvas)
{
canvas.drawBitmap( m_background, 0, 0, m_bitmapPaint );
if ( m_controller.getIsOff() )
{
canvas.drawBitmap( m_volumeSelector, 20, 154, m_bitmapPaint );
}
else
{
final float xOffset = 55 + 235*(m_controller.getVolume()/100F);
canvas.drawBitmap( m_volumeSelector, xOffset, 154, m_bitmapPaint );
}
canvas.save();
canvas.clipRect( 0, 60, m_width - 20, m_height - 100);
renderScreenText( canvas );
canvas.restore();
renderScreenTitle( canvas );
}
void showSong( int songNumber )
{
final int songOffset = calculateSongOffset( songNumber );
if ( m_songNameYOffset == songOffset ) return;
if ( Math.abs( songOffset - m_songNameYOffset ) < 4*SONG_DISTANCE )
{
if ( songOffset > m_songNameYOffset )
{
m_songNameStepDirection = SONG_ANIMATION_STEP;
}
else
{
m_songNameStepDirection = -SONG_ANIMATION_STEP;
}
}
else
{
// Do not move more then four songs.
m_songNameYOffset = songOffset;
}
m_targetSongNameYOffset = songOffset;
}
int getWidth()
{
return m_width;
}
boolean prepareAnimationState()
{
boolean songNeedsRepaint = false;
for ( int screen = 0; screen < RadioDialController.SCREEN_COUNT; screen +=1 )
{
if ( isMovingSongName( screen ) )
{
m_songNameYOffset += m_songNameStepDirection;
songNeedsRepaint = true;
}
else
{
if ( m_songNameYOffset != m_targetSongNameYOffset )
{
songNeedsRepaint = true;
}
m_songNameYOffset = m_targetSongNameYOffset;
}
}
return songNeedsRepaint;
}
private void renderScreenTitle(Canvas canvas)
{
final String text = m_controller.getScreenTitle( m_screenNumber );
final Rect rect = new Rect();
m_screenTitleBgPaint.getTextBounds( text.toCharArray(), 0, text.length(), rect);
final int fontX = (300 - rect.width() );
final int fontY = 50;
canvas.drawText( text, fontX, fontY + 1, m_screenTitleBgPaint);
canvas.drawText( text, fontX, fontY, m_screenTitleFgPaint);
}
private void renderScreenText(Canvas canvas)
{
final int fontX = 20;
final int fontY = -m_songNameYOffset + 100;
final List<Song> screenSongs = m_controller.getScreenSongs( m_screenNumber );
if ( screenSongs != null && !screenSongs.isEmpty() )
{
for ( int i = 0; i < screenSongs.size(); i++ )
{
final Song song = screenSongs.get( i );
final int offsetY = i*SONG_DISTANCE;
renderSongAtFor( song, fontX, fontY + offsetY, canvas);
}
}
else
{
canvas.drawText( m_noSongsString, fontX, fontY, m_songNamePaint);
}
}
private void renderSongAtFor(Song song, int fontX, int fontY, Canvas canvas)
{
if ( song.isScanned() )
{
canvas.drawText( song.getTrack(), fontX, fontY, m_songNamePaint);
canvas.drawText( song.getArtist(), fontX, fontY + 24, m_detailsPaint);
}
else
{
canvas.drawText( m_scanningString, fontX, fontY, m_songNamePaint);
}
}
private boolean isMovingSongName( int screen )
{
return Math.abs( m_targetSongNameYOffset - m_songNameYOffset ) > SONG_ANIMATION_STEP/2;
}
private int calculateSongOffset(int songNumber)
{
return songNumber * SONG_DISTANCE;
}
}
| Java |
/**
* Copyright (c) 2011 Basil Shikin, VintageRadio Project
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.vintagephone.view.opengl.shapes;
import android.util.Log;
public class Cylinder
extends ShapeBase
{
private final static float PI = (float)Math.PI;
private int m_slices = 40;
private float m_radius = 3;
private float m_height = 3;
public void setRadius( float radius )
{
m_radius = radius;
}
@Override
protected void loadShape()
{
final float delta = (2*PI)/m_slices;
float[] vertices = new float [ 3*2*m_slices ];
float theta = delta;
float x, z;
short ix = 0;
for ( int i = 0; i < 2*m_slices; i += 2, ix += 6 )
{
x = m_radius*(float)Math.cos(theta);
z = m_radius*(float)Math.sin(theta);
Log.d("--> " + i, theta + ": (" + x + "," + z + ")");
Log.d("--> " + i + 1, theta + ": (" + x + "," + z + ")");
vertices[ix + X] = x;
vertices[ix + Y] = 0;
vertices[ix + Z] = z;
vertices[ix + 3 + X] = x; // x
vertices[ix + 3 + Y] = m_height; // y
vertices[ix + 3 + Z] = z;
theta += delta;
}
short[] indicies = new short[ 6*m_slices ];
ix = 0;
short b0 = 0;
short b1 = 1;
short b0n = b0;
short b1n = 1;
int verticiesCount = 2*m_slices;
for ( short i = 0; i < m_slices; i += 1, ix += 6 )
{
b0n = (short)((b0 + 2) % verticiesCount);
b1n = (short)((b1 + 2) % verticiesCount);
indicies[ ix + 0 ] = b0n;
indicies[ ix + 1 ] = b0;
indicies[ ix + 2 ] = b1;
indicies[ ix + 3 ] = b0n;
indicies[ ix + 4 ] = b1n;
indicies[ ix + 5 ] = b1;
b0 = b0n;
b1 = b1n;
Log.d("--> " + i, "[" + indicies[ ix + 0 ] + ", " + indicies[ ix + 1 ] + ", " + indicies[ ix + 2 ] + "]" +
"[" + indicies[ ix + 3 ] + ", " + indicies[ ix + 4 ] + ", " + indicies[ ix + 5 ] + "]" );
}
setVertices(vertices);
setIndices( indicies );
}
}
| Java |
/**
* Copyright (c) 2011 Basil Shikin, VintageRadio Project
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.vintagephone.view.opengl.shapes;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.FloatBuffer;
import java.nio.ShortBuffer;
import javax.microedition.khronos.opengles.GL10;
/**
* This is a base for an OpenGL shape
*
* @author Basil Shikin
*
*/
public abstract class ShapeBase
{
private final static float[] s_defaultColor = new float[] { 1.0f, 1.0f, 1.0f, 1.0f };
protected static int X = 0;
protected static int Y = 1;
protected static int Z = 2;
private FloatBuffer m_vertices = null;
private ShortBuffer m_indices = null;
private int m_indiciesSize = 0;
private FloatBuffer m_colors = null;
/**
* Draw the shape.
*
* @param gl Open GL context to use
*/
public void draw(GL10 gl)
{
// gl.glFrontFace(GL10.GL_CCW);
// gl.glEnable(GL10.GL_CULL_FACE);
// gl.glCullFace(GL10.GL_BACK);
gl.glEnableClientState(GL10.GL_VERTEX_ARRAY);
// Specifies the location and data format of an array of vertex
// coordinates to use when rendering.
gl.glVertexPointer(3, GL10.GL_FLOAT, 0, m_vertices);
// Set flat color
gl.glColor4f(s_defaultColor[0], s_defaultColor[1], s_defaultColor[2], s_defaultColor[3]);
// Smooth color
if (m_colors != null)
{
// Enable the color array buffer to be used during rendering.
gl.glEnableClientState(GL10.GL_COLOR_ARRAY);
gl.glColorPointer(4, GL10.GL_FLOAT, 0, m_colors);
}
gl.glDrawElements(GL10.GL_TRIANGLES, m_indiciesSize, GL10.GL_UNSIGNED_SHORT, m_indices);
gl.glColor4f(1f, 0f, 0f, 1f);
gl.glDrawElements(GL10.GL_LINE_LOOP, m_indiciesSize, GL10.GL_UNSIGNED_SHORT, m_indices);
gl.glDisableClientState(GL10.GL_VERTEX_ARRAY);
// gl.glDisable(GL10.GL_CULL_FACE);
}
protected abstract void loadShape();
/**
* Set the vertices.
*
* @param vertices
*/
protected void setVertices(float... vertices)
{
// a float is 4 bytes, therefore we multiply the number if
// vertices with 4.
ByteBuffer vbb = ByteBuffer.allocateDirect(vertices.length * 4);
vbb.order(ByteOrder.nativeOrder());
m_vertices = vbb.asFloatBuffer();
m_vertices.put(vertices);
m_vertices.position(0);
}
/**
* Set the indices.
*
* @param indices
*/
protected void setIndices(int... indices)
{
short[] shorts = new short[ indices.length ];
for ( int i = 0; i < indices.length; i++ ) shorts[i] = (short)indices[i];
setIndices( shorts );
}
/**
* Set the indices.
*
* @param indices
*/
protected void setIndices(short... indices)
{
// short is 2 bytes, therefore we multiply the number if
// vertices with 2.
ByteBuffer ibb = ByteBuffer.allocateDirect(indices.length * 2);
ibb.order(ByteOrder.nativeOrder());
m_indices = ibb.asShortBuffer();
m_indices.put(indices);
m_indices.position(0);
m_indiciesSize = indices.length;
}
protected void setColors(float... colors)
{
// float has 4 bytes.
final ByteBuffer cbb = ByteBuffer.allocateDirect(colors.length * 4);
cbb.order(ByteOrder.nativeOrder());
m_colors = cbb.asFloatBuffer();
m_colors.put(colors);
m_colors.position(0);
}
}
| Java |
/**
* Copyright (c) 2011 Basil Shikin, VintageRadio Project
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.vintagephone.view.opengl.shapes;
import java.util.ArrayList;
import java.util.Collection;
import javax.microedition.khronos.opengles.GL10;
/**
* This class represents a collection of shapes that could be rendered
*
* @author Basil Shikin
*
*/
public class Container
extends ShapeBase
{
private final Collection<ShapeBase> m_children = new ArrayList<ShapeBase>();
public void addChild( ShapeBase child )
{
m_children.add( child );
}
@Override
public void draw(GL10 gl)
{
for ( ShapeBase shape : m_children )
{
shape.draw( gl );
}
}
@Override
public void loadShape()
{
for ( ShapeBase shape : m_children )
{
shape.loadShape();
}
}
}
| Java |
/**
* Copyright (c) 2011 Basil Shikin, VintageRadio Project
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.vintagephone.view.opengl.scene;
import org.vintagephone.view.opengl.shapes.Container;
import org.vintagephone.view.opengl.shapes.Cylinder;
public class RadioDial
extends Container
{
private Cylinder m_outerCylinder;
private Cylinder m_innerCylinder;
@Override
public void loadShape()
{
m_outerCylinder = new Cylinder();
m_outerCylinder.setRadius( 3 );
addChild( m_outerCylinder );
m_innerCylinder = new Cylinder();
m_innerCylinder.setRadius( 2 );
addChild( m_innerCylinder );
super.loadShape();
}
}
| Java |
/**
* Copyright (c) 2011 Basil Shikin, VintageRadio Project
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.vintagephone.view.opengl.scene;
import org.vintagephone.view.opengl.shapes.Container;
public class RadioFace
{
private final Container m_container;
public RadioFace( final Container container )
{
m_container = container;
}
public void initialize()
{
m_container.addChild( new RadioDial() );
m_container.loadShape();
}
}
| Java |
package org.vintagephone.view.opengl;
/**
* Copyright (c) 2011 Basil Shikin, VintageRadio Project
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.opengles.GL10;
import org.vintagephone.view.opengl.shapes.Container;
import android.opengl.GLSurfaceView.Renderer;
import android.opengl.GLU;
public class OpenGLRenderer
implements Renderer
{
private final Container m_root;
public OpenGLRenderer()
{
m_root = new Container();
}
public Container getRoot()
{
return m_root;
}
public void onSurfaceCreated(GL10 gl, EGLConfig config)
{
gl.glClearColor(0.0f, 0.0f, 0.0f, 0.5f); // Background is black
gl.glShadeModel(GL10.GL_SMOOTH);
gl.glClearDepthf(1.0f);
gl.glEnable(GL10.GL_DEPTH_TEST);
gl.glDepthFunc(GL10.GL_LEQUAL);
gl.glHint(GL10.GL_PERSPECTIVE_CORRECTION_HINT, GL10.GL_NICEST);
}
public void onDrawFrame(GL10 gl)
{
gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT);
gl.glLoadIdentity();
gl.glTranslatef(0, -5, -10);
// Draw our scene.
m_root.draw(gl);
}
public void onSurfaceChanged(GL10 gl, int width, int height)
{
// Sets the current view port to the new size.
gl.glViewport(0, 0, width, height);
// Select the projection matrix
gl.glMatrixMode(GL10.GL_PROJECTION);
// Reset the projection matrix
gl.glLoadIdentity();
// Calculate the aspect ratio of the window
GLU.gluPerspective(gl, 90.0f, (float) width / (float) height, 0.1f,
1000.0f);
// Select the modelview matrix
gl.glMatrixMode(GL10.GL_MODELVIEW);
// Reset the modelview matrix
gl.glLoadIdentity();
}
}
| Java |
package org.vintagephone;
import org.vintagephone.model.RadioLifecycle;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
public class RadioActivity extends Activity
{
private RadioLifecycle m_lifecycle;
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
// Remove the title bar from the window.
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
// Make the windows into full screen mode.
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
m_lifecycle = new RadioLifecycle( this );
m_lifecycle.initialize();
// Render view
final View view = m_lifecycle.getView();
setContentView( view );
view.requestFocus();
}
} | Java |
/**
* Copyright (c) 2011 Basil Shikin, VintageRadio Project
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.vintagephone;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
public class StartupIntentReceiver
extends BroadcastReceiver
{
@Override
public void onReceive(Context context, Intent intent)
{
final Intent activityIntent = new Intent( context, RadioActivity.class );
activityIntent.addFlags( Intent.FLAG_ACTIVITY_NEW_TASK );
context.startActivity(activityIntent);
}
} | Java |
/**
* Copyright (c) 2011 Basil Shikin, VintageRadio Project
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.vintagephone;
import org.vintagephone.model.hardware.ioio.IOIORadioHardwareThread;
import org.vintagephone.model.hardware.ioio.IOIORadioHardwareThread.DebugListener;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
public class DebugActivity extends Activity implements DebugListener
{
private IOIORadioHardwareThread m_hardwareThread;
private TextView m_statusView;
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.debug);
m_statusView = (TextView) findViewById(R.id.statusText );
m_statusView.setText( "Initializing with Debug...");
m_hardwareThread = new IOIORadioHardwareThread();
m_hardwareThread.setDebugListener( this );
m_hardwareThread.start();
}
@Override
public void printDebugMessage(final String message)
{
m_statusView.post( new Runnable()
{
public void run()
{
m_statusView.setText( message );
}
} );
}
}
| Java |
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)
/**
* Write a description of class Play here.
*
* @author (Karen Gonzalez)
* @version (25/05/14)
*/
public class Play extends BotonesMenu
{
/**Variables de instancia de la clase play*/
private CatchWorld m;
/**Constructor de la clase play*/
public Play(CatchWorld mundo)
{
m = mundo;
}
/**Metodo actua donde verificamos si el mouse esta tocando el boton*/
public void act()
{
MouseInfo mouse = Greenfoot.getMouseInfo();
if(mouse!=null)
{
if(Greenfoot.mouseClicked(this))
m.nivel1();
}
}
}
| Java |
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)
import java.awt.Color;
import java.util.List;
/**
* An actor class that can display a scoreboard, using Greenfoot's
* UserInfo class.
*
* You typically use this by including some code into the world for when your game ends:
*
* <pre>
* addObject(new ScoreBoard(800, 600), getWidth() / 2, getHeight() / 2);
* </pre>
*
* Where 800 by 600 should be replaced by the desired size of the score board.
*
* @author Neil Brown
* @version 1.0
*/
/**Clase importada de Greenfoot*/
public class ScoreBoard extends Actor
{
// The vertical gap between user images in the scoreboard:
private static final int GAP = 10;
// The height of the "All Players"/"Near Me" text at the top:
private static final int HEADER_TEXT_HEIGHT = 25;
// The main text color:
private static final Color MAIN_COLOR = new Color(0x60, 0x60, 0x60); // dark grey
// The score color:
private static final Color SCORE_COLOR = new Color(0xB0, 0x40, 0x40); // orange-y
// The background colors:
private static final Color BACKGROUND_COLOR = new Color(0xFF, 0xFF, 0xFF, 0xB0);
private static final Color BACKGROUND_HIGHLIGHT_COLOR = new Color(180, 230, 255, 0xB0);
/**
* Constructor for objects of class ScoreBoard.
* <p>
* You can specify the width and height that the score board should be, but
* a minimum width of 600 will be enforced.
*/
public ScoreBoard(int width, int height)
{
setImage(new GreenfootImage(Math.max(600, width), height));
drawScores();
}
private void drawString(String text, int x, int y, Color color, int height)
{
getImage().drawImage(new GreenfootImage(text, height, color, new Color (0, true)), x, y);
}
private void drawScores()
{
// 50 pixels is the max height of the user image
final int pixelsPerUser = 50 + 2*GAP;
// Calculate how many users we have room for:
final int numUsers = ((getImage().getHeight() - (HEADER_TEXT_HEIGHT + 10)) / pixelsPerUser);
final int topSpace = getImage().getHeight() - (numUsers * pixelsPerUser) - GAP;
getImage().setColor(BACKGROUND_COLOR);
getImage().fill();
drawString("All Players", 100, topSpace - HEADER_TEXT_HEIGHT - 5, MAIN_COLOR, HEADER_TEXT_HEIGHT);
drawString("Near You", 100 + getImage().getWidth() / 2, topSpace - HEADER_TEXT_HEIGHT - 5, MAIN_COLOR, HEADER_TEXT_HEIGHT);
drawUserPanel(GAP, topSpace, (getImage().getWidth() / 2) - GAP, topSpace + numUsers * pixelsPerUser, UserInfo.getTop(numUsers));
drawUserPanel(GAP + getImage().getWidth() / 2, topSpace, getImage().getWidth() - GAP, topSpace + numUsers * pixelsPerUser, UserInfo.getNearby(numUsers));
}
private void drawUserPanel(int left, int top, int right, int bottom, List users)
{
getImage().setColor(MAIN_COLOR);
getImage().drawRect(left, top, right - left, bottom - top);
if (users == null)
return;
UserInfo me = UserInfo.getMyInfo();
int y = top + GAP;
for (Object obj : users)
{
UserInfo playerData = (UserInfo)obj;
Color c;
if (me != null && playerData.getUserName().equals(me.getUserName()))
{
// Highlight our row in a sky blue colour:
c = BACKGROUND_HIGHLIGHT_COLOR;
}
else
{
c = BACKGROUND_COLOR;
}
getImage().setColor(c);
getImage().fillRect(left + 5, y - GAP + 1, right - left - 10, 50 + 2*GAP - 1);
int x = left + 10;
drawString("#" + Integer.toString(playerData.getRank()), x, y+18, MAIN_COLOR, 14);
x += 50;
drawString(Integer.toString(playerData.getScore()), x, y+18, SCORE_COLOR, 14);
x += 80;
getImage().drawImage(playerData.getUserImage(), x, y);
x += 55;
drawString(playerData.getUserName(), x, y + 18, MAIN_COLOR, 14);
y += 50 + 2*GAP;
}
}
}
| Java |
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)
/**
* Write a description of class Dulce here.
*
* @author (Karen Gonzalez)
* @version (29/05/14)
*/
public class Dulce extends Bonus
{
public Dulce()
{
}
public void act()
{
}
}
| Java |
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)
import java.awt.Font; //
import java.awt.Color;
/**
* Write a description of class CatchWorld here.
*
* @author (Karen Gonzalez)
* @version (29/05/14)
*/
public class CatchWorld extends World
{
/**Variables de instancia*/
private Plataforma plataforma;
private Piña pina;
private Llave key;
private Leon leon;
private Fresa fresa;
private Jugador jugador;
private Roca roca;
private int nivel;
private Gato gato;
public int vidas;
private Ladron ladron;
private int tam = 3;
private int t=0;
private SimpleTimer tiempoReloj;
private int randkey = Greenfoot.getRandomNumber(3);
private Vida vida;
private GreenfootSound musica;
private time tiempo;
private Martillo martillo;
/**Constructor de la clase mundo*/
public CatchWorld()
{
super(800, 600, 1);
jugador = new Pocoyo();
vidas = 3;
nivel = 1;
portada();
tiempo = new time();
}
/**Metodo que muestra la portada*/
public void portada()
{
removeObjects(getObjects(Actor.class));
setBackground("pocoyo_presentacion.png");
Next sig = new Next(this);
addObject (sig, 655, 494);
}
/**Metodo que agrega la ayuda*/
public void ayuda()
{
removeObjects( getObjects(Actor.class) );
setBackground("ayuda2.jpg");
Regresar atras = new Regresar(this);
addObject(atras,163, 523);
}
/**Metodo que agrega los creditos*/
public void creditos()
{
removeObjects(getObjects(Actor.class));
setBackground("creditos.png");
Regresar atras = new Regresar(this);
addObject(atras,151,379);
}
/**Metodo que agrega los botones al menu*/
public void menu()
{
removeObjects(getObjects(Actor.class));
setBackground("menu.png");
Play play = new Play(this);
addObject(play, 524, 162);
Ayuda ayuda = new Ayuda(this);
addObject(ayuda, 633, 282);
Creditos credi = new Creditos(this);
addObject(credi, 499, 405);
Records rec = new Records(this);
addObject(rec,593,526);
}
/**Metodo para incrementar de nivel*/
public void incrementaNivel()
{
nivel++;
}
/**Metodo que regresa las vidas*/
public Vida getVida()
{
return vida;
}
/**Metodo que crea el nivel 1*/
public void nivel1()
{
musica=new GreenfootSound("temapocoyo.mp3");
musica.playLoop();
removeObjects(getObjects(Actor.class));
setBackground("fondo_original.jpg");
addObject(tiempo, 738,27);
addObject(jugador, 200, 572);
Letrero let=new Letrero ("Level 1");
addObject(let, 70 ,22);
addObject(new Plataforma(), 113 , 117);
addObject(new Plataforma(), 153 , 117);
addObject(new Plataforma(), 193 , 117);
addObject(new Plataforma(), 283 , 255);
addObject(new Plataforma(), 323 , 255);
addObject(new Plataforma(), 523 , 255);
addObject(new Plataforma(), 739 , 257);
addObject(new Plataforma(), 61 , 254);
addObject(new Plataforma(), 142, 362);
addObject(new Plataforma(), 181, 362);
addObject(new Plataforma(), 388, 389);
addObject(new Plataforma(), 427, 389);
addObject(new Plataforma(), 467, 389);
addObject(new Plataforma(), 640, 384);
addObject(new Plataforma(), 680, 384);
addObject(new Plataforma(), 47, 495);
addObject(new Plataforma(), 87, 495);
addObject(new Plataforma(), 535, 487);
addObject(new Plataforma(), 575, 487);
addObject(new Plataforma(), 232, 117);
addObject(new Plataforma(), 272, 117);
addObject(new Plataforma(), 312, 117);
addObject(new Plataforma(), 352, 117);
addObject(new Plataforma(), 391, 117);
addObject(new Plataforma(), 431 , 117);
addObject(new Plataforma(), 471 , 117);
addObject(new Plataforma(), 511 , 117);
addObject(new Plataforma(), 551 , 117);
addObject(new Plataforma(), 591 , 117);
addObject(new Plataforma(), 630 , 117);
if(randkey == 0)
{
addObject(new Llave(), 739 , 200);
}
else if(randkey == 1)
{
addObject(new Llave(), 169 , 314);
}
else if(randkey == 2)
{
addObject(new Llave(), 469 , 336);
}
else if(randkey == 3)
{
addObject(new Llave(), 465 , 68);
}
addObject(new Fresa(), 739 , 200);
addObject(new Fresa(), 169 , 314);
addObject(new Fresa(), 469 , 336);
addObject(new Fresa(), 465 , 68);
addObject(new Gato(), 109,66);
}
/**Metodo que crea el nivel 2*/
public void nivel2()
{
int nivel =2;
removeObjects(getObjects(Actor.class));
setBackground("nivel2.jpg");
Greenfoot.delay(200);
setBackground("paisaje2.jpg");
addObject(jugador, 342, 573);
addObject(tiempo, 738,27);
Letrero let=new Letrero ("Level 2");
addObject(let, 70 ,22);
addObject(new Ladron(), 610, 561);
if(randkey == 0)
{
addObject(new Llave(), 30,368);
}
else if(randkey == 1)
{
addObject(new Llave(), 288,98);
}
else if(randkey == 2)
{
addObject(new Llave(), 574,136);
}
else if(randkey == 3)
{
addObject(new Llave(), 730,466);
}
addObject(new Uva(), 30,368);
addObject(new Uva(), 288,98);
addObject(new Uva(), 574,136);
addObject(new Uva(), 730,466);
addObject(new Plataforma(), 21, 146);
addObject(new Plataforma(), 684, 514);
addObject(new Plataforma(), 289, 415);
addObject(new Plataforma(), 61, 146);
addObject(new Plataforma(), 253, 148);
addObject(new Plataforma(), 292, 148);
addObject(new Plataforma(), 124, 280);
addObject(new Plataforma(), 163, 280);//
addObject(new Plataforma(), 203, 280);
addObject(new Plataforma(), 20, 415);
addObject(new Plataforma(), 60, 415);
addObject(new Plataforma(), 61, 146);
addObject(new Plataforma(), 100, 415);
addObject(new Plataforma(), 193, 511);
addObject(new Plataforma(), 232, 511);
addObject(new Plataforma(), 411, 286);
addObject(new Plataforma(), 567, 181);
addObject(new Plataforma(), 607, 181);
addObject(new Plataforma(), 515, 423);
addObject(new Plataforma(), 555, 423);
addObject(new Plataforma(), 594, 423);
addObject(new Plataforma(), 371, 286);
addObject(new Plataforma(), 779, 314);
addObject(new Plataforma(), 739, 314);
addObject(new Plataforma(), 451, 286);
addObject(new Gato(), 29, 95);
}
/**Metodo que crea el nivel 3*/
public void nivel3()
{
int nivel = 3;
removeObjects(getObjects(Actor.class));
setBackground("nivel3.png");
Greenfoot.delay(200);
setBackground("paisaje3.jpg");
addObject(jugador, 342, 573);
addObject(tiempo, 738,27);
Letrero let=new Letrero ("Level 3");
addObject(let, 70 ,22);
addObject(new Leon(), 492, 40);
addObject(new Plataforma(), 182, 499);
addObject(new Plataforma(), 222, 499);
addObject(new Plataforma(), 515, 502);
addObject(new Plataforma(), 555, 502);
addObject(new Plataforma(), 46, 385);
addObject(new Plataforma(), 86, 385);
addObject(new Plataforma(), 125, 385);
addObject(new Plataforma(), 165, 385);
addObject(new Plataforma(), 302, 384);
addObject(new Plataforma(), 641, 384);
addObject(new Plataforma(), 680, 384);
addObject(new Plataforma(), 720, 384);
addObject(new Plataforma(), 228, 97);
addObject(new Plataforma(), 267, 97);
addObject(new Plataforma(), 307, 97);
addObject(new Plataforma(), 347, 97);
addObject(new Plataforma(), 387, 97);
addObject(new Plataforma(), 427, 97);
addObject(new Plataforma(), 467, 97);
addObject(new Plataforma(), 506, 97);
addObject(new Plataforma(), 91, 179);
addObject(new Plataforma(), 131, 179);
addObject(new Plataforma(), 170, 179);
addObject(new Plataforma(), 226, 267);
addObject(new Plataforma(), 265, 267);
addObject(new Plataforma(), 305, 267);
addObject(new Plataforma(), 463, 284);
addObject(new Plataforma(), 503, 284);
addObject(new Plataforma(), 543, 284);
addObject(new Plataforma(), 600, 194);
addObject(new Plataforma(), 640, 194);
addObject(new Plataforma(), 679, 194);
addObject(new Ladron(), 35, 562);
if(randkey == 0)
{
addObject(new Llave(), 235, 43);
}
else if(randkey == 1)
{
addObject(new Llave(), 89, 336);
}
else if(randkey == 2)
{
addObject(new Llave(), 539, 228);
}
else if(randkey == 3)
{
addObject(new Llave(), 682, 333);
}
addObject(new Piña(), 235, 43);
addObject(new Piña(), 89, 336);
addObject(new Piña(), 539, 228);
addObject(new Piña(),682, 333);
musicStop();
}
/**Metodo que despliega una imagen, que indica que perdio*/
public void pierde()
{
tiempo.start();
musicStop();
tiempo.start();
removeObjects(getObjects(Actor.class));
setBackground("perdio.jpg");
musicStop();
}
/**Metodo para desplegar una imagen, que indica que gano*/
public void Gana()
{
tiempo.start();
musicStop();
tiempo.start();
removeObjects(getObjects(Actor.class));
setBackground("ganador.jpg");
}
/**Metodo para reiniciar el juego*/
public void reinciaJuego()
{
nivel1();
}
/**Metodo que regresa la fresa*/
public Fresa getFresa()
{
return fresa;
}
/**Metodo que regresa la pina*/
public Piña getPina()
{
return pina;
}
/**Metodo que regresa el ladron*/
public Ladron getLadron()
{
return ladron;
}
/**Metodo que regresa el gato*/
public Gato getGato()
{
return gato;
}
/**Metodo que regresa la plataforma*/
public Plataforma getPlataforma()
{
return plataforma;
}
/**Metodo que regresa la roca*/
public Roca getRoca()
{
return roca;
}
/**Metodo que regresa el jugador*/
public Jugador getJugador()
{
return jugador;
}
/**Metodo que regresa el leon*/
public Leon getLeon()
{
return leon;
}
/**Metodo que regresa el martillo*/
public Martillo getMartillo()
{
return martillo;
}
/**Meetodo para tiempo*/
public SimpleTimer getTime()
{
return tiempoReloj;
}
/**Metodo para mostrar los records*/
public void records2()
{
removeObjects( getObjects(Actor.class) );
setBackground("record2.jpg");
ScoreBoard board=new ScoreBoard(500,500);
addObject(board,getWidth()/2,getHeight()/2);
Regresar atras = new Regresar(this);
addObject(atras,100,400);
this.records();
}
/**Metodo para records*/
public void records()
{
removeObjects( getObjects(Actor.class) );
//this.setBackground("RECORDSfondo.png");
java.util.List records=UserInfo.getTop(5);
// Record usuario;
UserInfo info=UserInfo.getMyInfo();
int y=50;
Letrero nombre=new Letrero(info.getUserName());
String cad=""+info.getScore();
Letrero nivel=new Letrero(cad);
Regresar atras = new Regresar(this);
addObject(atras,100,150);
Letrero let=new Letrero ("RECORDS");
addObject(let,350,30);
if(records!=null)
{
for(int i=0; i<records.size(); i++)
{
info=(UserInfo)records.get(i);
addObject(nombre,110+(nombre.getImage().getWidth()/2),y);
addObject(nivel,480+(nivel.getImage().getWidth()/2),y);
y+=50;
}
}
else
{
Letrero letrero;
letrero=new Letrero("RECORDS HO");
this.addObject(letrero,300,50);
}
}
/**Metodo para detener la musica*/
public void musicStop()
{
musica.stop();
}
}
| Java |
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)
/**
* Write a description of class Records here.
*
* @author (Karen Gonzalez)
* @version (29/05/14)
*/
public class Records extends BotonesMenu
{
/**Variable de instancia*/
private CatchWorld m;
/**Constructor de la clase mundo*/
public Records(CatchWorld mundo)
{
m = mundo;
}
/**Metodo actua donde verificamos si el mouse esta tocando el boton*/
public void act()
{
MouseInfo mouse = Greenfoot.getMouseInfo();
if(mouse!=null)
{
if(Greenfoot.mouseClicked(this))
m.records2();
}
}
} | Java |
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)
import java.awt.Color;
/**
* Write a description of class time here.
*
* @author (Karen Gonzalez)
* @version (29/05/14)
*/
public class time extends Actor
{
/**Variables de instancia*/
private boolean running = false;
private int millisElapsed;
private long lastTime = 0;
private int cambia;
/**Constructor del tiempo*/
public time()
{
int t;
t=updateImage();
}
/**Metodo que inicializa variables de instancia*/
public void start()
{
millisElapsed=0;
lastTime = 0;
}
/**Metodo que pausa el tiempo*/
public void gamePaused()
{
lastTime = 5;
}
/**Metodo para restar los segundos*/
public void restaSegundos()
{
cambia=updateImage();
cambia=cambia-5;
millisElapsed=cambia;
cambia=updateImage();
updateImage();
}
/**Actual de la clase tiempo*/
public void act()
{
timer1();
updateImage();
}
/**Metodo para */
public void timer1()
{
long time = System.currentTimeMillis();
if(lastTime != 0)
{
long diff = time - lastTime;
millisElapsed += diff;
}
lastTime = time;
}
/**Metodo que calcula minutos y segundos */
public int updateImage()
{
// Calculate minutes & seconds elapsed
int m;
int b;
int millis = millisElapsed % 1000;
int secs = (millisElapsed / 1000) % 60;
int mins = millisElapsed / 60000;
int cont=0;
// Convert these into text
String millisText = String.format("%03d", millis);
String secsText = String.format("%02d", secs);
String minsText = "" + mins;
String text = minsText + ":" + secsText ;
GreenfootImage img = new GreenfootImage(text,75,Color.orange, null);
setImage(img);
return(secs);
}
}
| Java |
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)
import java.awt.Color;
/**
* Write a description of class Letrero here.
*
* @author (Karen Gonzalez)
* @version (29/05/14)
*/
public class Letrero extends Actor
{
/**Variables de instancia*/
private String letrero;
/**Constructor de la clase letrero*/
public Letrero(String le)
{
letrero=le;
super.setImage(new GreenfootImage("" + letrero,50,Color.green, null));
}
/**imprime el letrero*/
public void act()
{
super.setImage(new GreenfootImage("" + letrero,50,Color.green,null));
}
}
| Java |
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)
/**
* Write a description of class Bala here.
*
* @author (Karen Gonzalez)
* @version (29/05/14)
*/
public class Bala extends Actor
{
/**Variables de instancia de la clase Bala*/
private boolean dir;
private CatchWorld m;
private Jugador j;
/**Constructor de la clase balaa*/
public Bala()
{
getImage().scale(30,30);
dir = false;
}
/**Metodo actua de clase bala*/
public void act()
{
m = (CatchWorld)this.getWorld();
AgregaBala();
if(getX()<=10 || this.getX() >= getWorld().getWidth()-20 || this.getY() <= 10|| this.getY()>= getWorld().getHeight()-20)
{
m.removeObject(this);
}
}
/**Metodo agrega Bala, en este metodo se añade una bala y por medio de las coordenadas del juador se lanza*/
public void AgregaBala()
{
int x, y;
if(dir==false)
{
Jugador j=((CatchWorld)getWorld()).getJugador();
turnTowards(j.getX()+2, j.getY()+2);
dir = true;
}
move(2);
}
}
| Java |
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)
/**
* Write a description of class Fresa here.
*
* @author (your name)
* @version (a version number or a date)
*/
public class Fresa extends Fruta
{
/**Metodo actua de la clase fresa, se manda llamar los metodos a ejecutar*/
public void act()
{
JugadorTomaFruta();
}
/**En este metodo se verifica el jugador toma la fresa*/
public void JugadorTomaFruta()
{
if(isTouching(Pocoyo.class))
{
getWorld().removeObject(this);
}
}
}
| Java |
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)
/**
* Write a description of class Gato here.
*
* @author (Karen Gonzalez)
* @version (29/05/14)
*/
public class Gato extends Enemigos
{
/**Variables de instancia de la clase Gato*/
private int velocidad;
private int izq;
private int arriba;
private int abajo;
private int der;
private int cont;
private int inicio;
private int aleatorio = 0;
private int dir;
private int contAtaque;
private boolean existeGato;
private Jugador jug;
private int c;
/**Constructor de la clase Gato, se inicializan las variables de instancia*/
public Gato()
{
contAtaque=0;
velocidad = 2;
izq = 1;
c=0;
der = 2;
arriba = 3;
abajo = 4;
cont = 0;
inicio = 1;
dir = 0;
existeGato=true;
getImage().scale(70,70);
}
/**Actua de la Clase gato, donde se mandan llamar los metodos para ejecutarse constantemente*/
public void act()
{
CatchWorld mundo = (CatchWorld)this.getWorld();
jug = (Jugador)mundo.getJugador();
move(2);
mueveGato();
if(jug.TocaMartillo()==true)
{
if(c >=10 )
{
ataca();
contAtaque=0;
}
cont++;
}
else
if(contAtaque >= 20 && contAtaque>=100)
{
ataca();
contAtaque=0;
}
contAtaque++;
if(getX()>=780||getY()>=580)
{
getWorld().removeObject(this);
existeGato=false;
}
if(existeGato==false)
{
mundo.addObject(new Gato(),109,66);
}
existeGato=true;
}
/**Metodo para definir los limites en X y Y del gato*/
public boolean limitesGato()
{
if(getX()>=780||getY()>=580)
{
getWorld().removeObject(this);
return false;
}
return true;
}
/**Metodo para agregar rocas, y dirigirlas al jugador*/
public void ataca()
{
getWorld().addObject(new Roca(),getX()+3,getY());
}
/**Metodo para que cuando el gato no toque la plataforma caiga */
public void gravedad()
{
setLocation(getX(), getY()+velocidad);
}
/**Metodo donde se mueve el gato, se le da una direccion aleatoriamente*/
public void mueveGato()
{
CatchWorld mundo = (CatchWorld)this.getWorld();
Jugador jugador = (Jugador)mundo.getJugador();
Actor plataforma = getOneIntersectingObject(Plataforma.class);
if (cont == 100 || inicio == 1)
{
cont = 0;
inicio = 0;
aleatorio =Greenfoot.getRandomNumber(4);
}
if(plataforma != null)
{
if(aleatorio == izq)
setLocation(getX()-2, getY());
if(aleatorio == der)
setLocation(getX()+2, getY());
}
else if(plataforma == null)
{
gravedad();
}
else if(getX()>=30 || getX()<= 700 || getY()>=37 || getY() <= 567 )
{
if(aleatorio == izq)
{
setLocation(getX()-3, getY());
}
else
if(aleatorio == der)
{
setLocation(getX()+3, getY());
}
else
if(aleatorio == arriba)
{
setLocation(getX()-3, getY()+3);
}
else
if(aleatorio == abajo)
{
setLocation(getX(), getY()-3);
}
cont++;
}
}
}
| Java |
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)
import java.awt.Font; //
import java.awt.Color;
/**
* Write a description of class Roca here.
*
* @author (Karen Gonzalez)
* @version (29/05/14)
*/
public class Roca extends Actor
{
/**Variables de instancia de Clase roca*/
private boolean dir;
/**Constructor de la clase Roca*/
public Roca( )
{
dir=false;
}
/**Metodo actua de la clase Roca, se mandan llamar a otros metodos para que se ejectuten*/
public void act()
{
atacaJugador();
if(this.getX() >= getWorld().getWidth()-20 || this.getY()>= getWorld().getHeight()-20)
{
getWorld().removeObject(this);
}
}
/**Metodo donde la roca gira hacia las coordenadas del jugador*/
public void atacaJugador()
{
if (dir==false)
{
CatchWorld mundo = (CatchWorld)this.getWorld();
Jugador jug=((CatchWorld)getWorld()).getJugador();
turnTowards(jug.getX(), jug.getY());
dir=true;
}
move(4);
}
}
| Java |
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)
/**
* Write a description of class Leon here.
*
* @author (Karen Gonzalez)
* @version (29/05/14)
*/
public class Leon extends Enemigos
{
/**Variables de instancia de la clase Leon*/
private int dirAle;
private int contAle;
private int saltaAle;
private CatchWorld m;
private Piña pina;
/**Constructor de la clase leon, inicializacion de variables de instancia*/
public Leon()
{
getImage().scale(70,70);
contAle = 0;
saltaAle = 1;
dirAle = 1;
}
/**Metodo actua de la clase Leon*/
public void act()
{
m = (CatchWorld)this.getWorld();
pina = ((CatchWorld)getWorld()).getPina();
Plataforma();
mueveLeon();
tomaLlave();
}
/**Metodo que se utiliza para mover el leon */
public void mueveLeon()
{
move(3*dirAle);
if(Greenfoot.getRandomNumber( 600 ) == 0)
{
dirAle = dirAle*-1;
}
if(getX()>=750)
{
dirAle = -1;
}
else if(getX()<50)
{
dirAle = 1;
}
}
/**Metodo para verificar el Leon este tocando la plataforma*/
public void Plataforma()
{
Actor p = getOneObjectAtOffset(-25, 25,Plataforma.class);
if(p == null)
{
gravedad();
}
else
if(p.getY() > this.getY())
{
setLocation(getX(), p.getY()-40);
}
else
setLocation(getX(), getY()+100);
}
/**Metodo para cuando el leon no toca la plataforma, caiga*/
public void gravedad()
{
if( this.getY() <= 530 )
{
setLocation(getX(), getY()+2);
}
}
/**Metodo para que el leon toque la llave*/
public void tomaLlave()
{
if(isTouching(Llave.class))
{
m.pierde();
}
}
}
| Java |
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)
/**
* Write a description of class BotonesMenu here.
*
* @author (Karen Gonzalez)
* @version (29/05/14)
*/
public class BotonesMenu extends Actor
{
/**
* Act - do whatever the BotonesMenu wants to do. This method is called whenever
* the 'Act' or 'Run' button gets pressed in the environment.
*/
public void act()
{
// Add your action code here.
}
}
| Java |
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)
/**
* Write a description of class Bonus here.
*
* @author (Karen Gonzalez )
* @version (29/05/14)
*/
public class Bonus extends Actor
{
public void act()
{
// Add your action code here.
}
}
| Java |
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)
/**
* Write a description of class Ayuda here.
*
* @author (Karen Gonzalez )
* @version (29/05/14)
*/
public class Ayuda extends BotonesMenu
{
/**Variables de instancia de la clase Ayuda*/
private CatchWorld m;
/**Constructor de la clase ayuda*/
public Ayuda(CatchWorld mundo)
{
m= mundo;
}
/**Metodo actua donde verificamos si el mouse esta tocando el boton*/
public void act()
{
MouseInfo mouse = Greenfoot.getMouseInfo();
if(mouse!=null)
{
if(Greenfoot.mouseClicked(this))
m.ayuda();
}
}
}
| Java |
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)
import java.awt.Font; //
import java.awt.Color;
/**
* Write a description of class Llave here.
*
* @author (Karen Gonzalez)
* @version (25/05/14)
*/
public class Llave extends Actor
{
/**Constructor de la clase llave, donde se redimenciona la imagen*/
public Llave()
{
getImage().scale(30,30);
}
public void act()
{
}
}
| Java |
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)
/**
* Write a description of class Regresar here.
*
* @author (Karen Gonzalez)
* @version (29/05/14)
*/
public class Regresar extends BotonesMenu
{
/**Variable de instancia*/
private CatchWorld m;
/**Constructor de la clase regresa*/
public Regresar(CatchWorld mundo)
{
m = mundo;
}
/**Metodo actua donde verificamos si el mouse esta tocando el boton*/
public void act()
{
MouseInfo mouse = Greenfoot.getMouseInfo();
if(mouse!=null)
{
if(Greenfoot.mouseClicked(this))
m.menu();
}
}
} | Java |
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)
/**
* Write a description of class Ladron here.
*
* @author (Karen Gonzalez)
* @version (29/05/14)
*/
public class Ladron extends Enemigos
{
/**Variables de instancia*/
private int contBala;
private boolean existeLadron;
private CatchWorld m;
private Jugador j;
private Bala bala;
/**Constructor de la clase ladron, inicializacion de variables*/
public Ladron()
{
getImage().scale(120,120);
contBala = 0;
bala = null;
existeLadron = true;
}
/**Metodo actua de la clase ladron*/
public void act()
{
m = (CatchWorld)this.getWorld();
move(2);
if(contBala >= 100)
{
ataca();
contBala = 0;
}
contBala ++;
if(getX()>=780||getY()>=580)
{
setLocation(35, 562);
existeLadron=false;
}
}
/**Metodo donde el ladron lanza la roca al jugador*/
public void ataca()
{
bala = new Bala();
m.addObject(bala, getX(), getY());
}
}
| Java |
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)
import java.awt.Font; //
import java.awt.Color;
/**
* Write a description of class Jugador here.
*
* @author (Karen Gonzalez)
* @version (29/05/14)
*/
public class Jugador extends Actor
{
/**Variables de instancia*/
private int nivel ;
private int salto = 0;
private int velocidad;
private int saltar;
private int piso;
private int plataformaX;
private int plataformaY;
private Plataforma plataforma;
private int toca;
private CatchWorld mundo;
private boolean llave;
private Actor cat =null;
private Actor roca=null;
private int vidas;
private Vida vidaJug;
private int bandVidas;
private Actor martillo;
private Actor bala;
private int bonusAleatorio = Greenfoot.getRandomNumber(5);
private Dulce dulce;
private Martillo mar;
private Actor cupcake;
private long lastTime= System.currentTimeMillis();
private long elapsedTime = 0;
private SimpleTimer st;
private Vida vida;
private int banVida;
private int banVida2;
private int contador;
private int contBonus;
private Bonus bonus;
private boolean bandN;
private boolean bandB;
private int inmune;
/**Inicializacion de variables de instancia*/
public Jugador()
{
mundo = (CatchWorld)this.getWorld();
banVida = 1;
banVida = 1;
velocidad = 3;
saltar = 0;
piso = 0;
vidas = 3;
toca=0;
bandN = false;
bandVidas = 0;
llave = false;
nivel = 1;
st = new SimpleTimer();
contador = 0;
contBonus = 0;
bandB = true;
inmune = 0;
vida = new Vida(" " + vidas);
}
/**Metodo que agrega un objeto vida*/
public void agregaLetrero( )
{
getWorld().addObject(vida, 358, 18);
}
/**Metodo actua donde se le manda llamar a otros metodos*/
public void act()
{
if(nivel!=4)
{
MueveJugador();
CaminaPlataforma();
if(TocaLlave())
{
CambiaNivel();
}
if(bandB == true)
{
agregaBonus();
agregaLetrero( );
bandB =false;
}
if(contBonus == 200 && bonus!=null)
{
mundo.removeObject(bonus);
bonus=null;
contBonus = 0;
}
RestaVidas();
contBonus++;
}
}
/**Metodo para cambiar de nivel*/
public int CambiaNivel()
{
switch(nivel)
{
case 1:
nivel = 2;
mundo.nivel2();
agregaLetrero( );
break;
case 2:
nivel = 3;
mundo.nivel3();
agregaLetrero( );
break;
case 3:
nivel = 4;
mundo.Gana();
break;
}
return nivel;
}
/**Metodo donde el jugador se dezplaza por todo el escenario **/
public void MueveJugador()
{
if(Greenfoot.isKeyDown ("left"))
{
if(this.getX() >= 15)
{
setImage("pizq.png");
getImage().scale(50,50);
setLocation(getX()-velocidad,getY());
}
}
else if(Greenfoot.isKeyDown ("right"))
{
if(this.getX() <= 750)
{
setImage("POCOYOderecha.png");
getImage().scale(50,50);
setLocation(getX()+velocidad,getY());
}
}
else if(Greenfoot.isKeyDown ("up") && salto == 0 && (TocandoPlataforma() || getY() >= 600-getImage().getHeight()/2-10 ))
{
if(this.getY() >= 30 )
{
salto = salto +1;
}
}
saltar();
if(salto == 25)
salto = 0;
}
/**Metodo para que salte*/
public void saltar()
{
if(salto!=0)
{
setLocation(getX(),getY()-10);
salto=salto+1;;
}
}
/**Metodo booleano donde regresa verdadero si toca la plataforma*/
public boolean TocandoPlataforma()
{
for(int i = -10; i<=10; i++)
{
if((getOneObjectAtOffset(i, getImage().getHeight()/2+5, Plataforma.class)!=null))
return true ;
}
return false;
}
/**Metodo gravedad, se manda llamar cuando el objeto no esa tocando plataforma*/
public void gravedad()
{
if( this.getY() <= 570 )
{
setLocation(getX(), getY()+velocidad);
}
}
/**Metodo para que identifique la plataforma*/
public boolean CaminaPlataforma()
{
Actor p = getOneObjectAtOffset(-20,20,Plataforma.class);
mundo= ((CatchWorld)getWorld());
if(p==null)
gravedad();
else
if(p.getY() > this.getY())
{
setLocation(getX(), p.getY()-40);
return true;
}
else
setLocation(getX(), getY()+100);
return false;
}
/***Metodo donde por medio de un numero aleatorio se agrega un bonus*/
public boolean agregaBonus()
{
Actor m = getOneIntersectingObject(Martillo.class);
if(bonusAleatorio == 1 )
{
bonus = new Dulce();
mundo.addObject(bonus, 261, 516);
}
else if(bonusAleatorio == 2)
{
bonus = new Martillo();
mundo.addObject(bonus, 261, 516);
if(m!=null)
{
getWorld().removeObject(m);
}
}
return true;
}
/**Metodo para verificar si toca el dulce*/
public boolean TocaDulce()
{
Actor p = getOneIntersectingObject(Dulce.class);
if(p!= null)
{
getWorld().removeObject(p);
return true;
}
return false;
}
/**Metodo para verificar si toca llave*/
public boolean TocaLlave()
{
if(isTouching(Llave.class))
return true;
else
return false;
}
/**Metodo para verificar si toca gato*/
public boolean TocaGato()
{
int ban=1;
if(nivel!=4){
cat = getOneIntersectingObject(Gato.class);
if(ban==1 && cat!=null)
{
return true;
}}
return false;
}
/**Metodo para verificar si toca la roca*/
public boolean TocaRoca()
{
if(nivel!=4)
{
roca = getOneIntersectingObject(Roca.class);
if(roca!=null )
{
getWorld().removeObject(roca);
return true;
}
}
return false;
}
/**Metodo para verificar si toca la bala*/
public boolean TocaBala()
{
int ban=1;
bala = getOneIntersectingObject(Bala.class);
if(ban==1 && bala!=null)
{
getWorld().removeObject(bala);
return true;
}
return false;
}
/**Metodo para verificar si toca el martillo*/
public boolean TocaMartillo()
{
Actor mar;
mar = getOneIntersectingObject(Martillo.class);
if(mar!=null)
{
getWorld().removeObject(mar);
return true;
}
return false;
}
/**Metodo donde se van restando vidas, conforme las conficiones dadas*/
public void RestaVidas()
{
int cont=0;
int banToca = 1;
if(nivel!=4){
if(bonus!=null && TocaDulce()==true)
{
vidas = vidas + 1;
}
if(TocaRoca() == true || TocaGato() == true && banToca ==1 || TocaBala()==true )
{
vidas--;
if(vidas>=0)
{
if(vidas == 0)
{
mundo.pierde();
}
else
vida.despliega("" + vidas );
}
banToca = 0;
}
}
}
}
| Java |
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)
/**
* Write a description of class Next here.
*
* @author (Karen Gonzalez)
* @version (29/05/14)
*/
public class Next extends BotonesMenu
{
/**Variables de instancia de la clase Next*/
private CatchWorld m;
/**Constructor de la clase next*/
public Next(CatchWorld mundo)
{
m = mundo;
}
/**Metodo actua donde verificamos si el mouse esta tocando el boton*/
public void act()
{
MouseInfo mouse= Greenfoot.getMouseInfo();
if(mouse!=null)
{
if( Greenfoot.mouseClicked(this))
m.menu();
}
}
}
| Java |
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)
/**
* Write a description of class Martillo here.
*
* @author (your name)
* @version (a version number or a date)
*/
public class Martillo extends Bonus
{
/**Constructor de clase martillo, unicamente se le da una nueva escala a la imagen*/
public Martillo()
{
getImage().scale(45,45);
}
public void act()
{
}
}
| Java |
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)
/**
* Write a description of class Fruta here.
*
* @author (Karen Gonzalez)
* @version (29/05/14)
*/
public class Fruta extends Actor
{
public void act()
{
}
public void JugadorTomaFruta()
{
}
}
| Java |
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)
/**
* Write a description of class Pocoyo here.
*
* @author (Karen Gonzalez)
* @version (29/05/14)
*/
public class Pocoyo extends Jugador
{
/**Metodo actua, donde se indica que ejecute los metodos de la clase super **/
public void act()
{
super.act();
}
}
| Java |
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)
/**
* Write a description of class Plataforma here.
*
* @author (Karen Gonzalez)
* @version (29/05/14)
*/
public class Plataforma extends Actor
{
/**Constructor de la clase Plataforma, se redimenciona la imagen*/
public Plataforma()
{
getImage().scale(40,40);
}
public void act()
{
}
}
| Java |
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)
import java.awt.Font; //
import java.awt.Color;
/**
* Write a description of class Vida here.
*
* @author Karen Gonzalez Almendarez
* @version (26/05/14)
*/
public class Vida extends Actor
{
/**Constructor de la vida*/
public Vida(String mensaje)
{
this.despliega(mensaje);
}
/**Metodo que muestra el mensaje de vidas*/
public void despliega(String mensaje)
{
setImage(new GreenfootImage(" Vidas=" +mensaje, 50, Color.magenta, null));
}
}
| Java |
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)
/**
* Write a description of class Piña here.
*
* @author (your name)
* @version (a version number or a date)
*/
public class Piña extends Fruta
{
private CatchWorld mundo;
private Jugador pocoyo;
private Leon leon;
public Piña()
{
getImage().scale(60,60);
}
public void act()
{
mundo = (CatchWorld)this.getWorld();
pocoyo = (Jugador)mundo.getJugador();
leon = (Leon)mundo.getLeon();
JugadorTomaFruta();
}
/**En este metodo se verifica el jugador toma la fresa*/
public void JugadorTomaFruta()
{
if(isTouching(Pocoyo.class))
{
quitaPina();
}
}
/**Metodo para quitar el objeto pina*/
public void quitaPina()
{
getWorld().removeObject(this);
}
/**Metodo donde se verifica si el leon toca la llave*/
public void TomaLeon()
{
if(this.isTouching(Leon.class))
{
quitaPina();
}
}
}
| Java |
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)
/**
* Write a description of class Creditos here.
*
* @author (Karen Gonzalez)
* @version (29/05/14)
*/
public class Creditos extends BotonesMenu
{
/**Variable de instancia*/
private CatchWorld m;
/**Constructor de la clase Creditos*/
public Creditos(CatchWorld mundo)
{
m= mundo;
}
/**Metodo actua donde verificamos si el mouse esta tocando el boton*/
public void act()
{
MouseInfo mouse = Greenfoot.getMouseInfo();
if(mouse!=null)
{
if(Greenfoot.mouseClicked(this))
m.creditos();
}
}
}
| Java |
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)
/**
* Write a description of class Enemigos here.
*
* @author (Karen Gonzalez)
* @version (29/05/14)
*/
public class Enemigos extends Actor
{
/**
* Act - do whatever the Enemigos wants to do. This method is called whenever
* the 'Act' or 'Run' button gets pressed in the environment.
*/
public void act()
{
}
}
| Java |
/**
* A simple timer class that allows you to keep track of how much time
* has passed between events.
*
* You use this class by creating a timer as a member field in your actor (or whatever):
* <pre>
*
* private SimpleTimer timer = new SimpleTimer();
* </pre>
*
* Then when you want to start the timer (for example, when a shot is fired), you call the mark() method:
*
* <pre>
*
* timer.mark();
* </pre>
*
* Thereafter, you can use the millisElapsed() method to find out how long it's been since mark()
* was called (in milliseconds, i.e. thousandths of a second). So if you want to only allow the player to fire a shot every second, you
* could write:
*
* <pre>
*
* if (timer.millisElapsed() > 1000 && Greenfoot.isKeyDown("space"))
* {
* // Code here for firing a new shot
* timer.mark(); // Reset the timer
* }
* </pre>
*
* @author Neil Brown
* @version 1.0
*/
public class SimpleTimer
{
private long lastMark = System.currentTimeMillis();
/**
* Marks the current time. You can then in future call
* millisElapsed() to find out the elapsed milliseconds
* since this mark() call was made.
*
* A second mark() call will reset the mark, and millisElapsed()
* will start increasing from zero again.
*/
public void mark()
{
lastMark = System.currentTimeMillis();
}
/**
* Returns the amount of milliseconds that have elapsed since mark()
* was last called. This timer runs irrespective of Greenfoot's
* act() cycle, so if you call it many times during the same Greenfoot frame,
* you may well get different answers.
*/
public int millisElapsed()
{
return (int) (System.currentTimeMillis() - lastMark);
}
} | Java |
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)
/**
* Write a description of class Uva here.
*
* @author (your name)
* @version (a version number or a date)
*/
public class Uva extends Fruta
{
/**Constructor de la clase uva, se redimenciona la imagen con otra escala*/
public Uva()
{
getImage().scale(50,50);
}
/**Metodo actua, donde se llamar los metodos a ejecutr¿ar*/
public void act()
{
JugadorTomaFruta();
}
/**Metodo donde se checa si el jugador toca la uva*/
public void JugadorTomaFruta()
{
if(isTouching(Pocoyo.class))
{
getWorld().removeObject(this);
}
}
}
| Java |
/*
* Copyright 2013 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.gcm.demo.app;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.gcm.GoogleCloudMessaging;
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import java.io.IOException;
import java.util.concurrent.atomic.AtomicInteger;
/**
* Main UI for the demo app.
*/
public class DemoActivity extends Activity {
public static final String EXTRA_MESSAGE = "message";
public static final String PROPERTY_REG_ID = "registration_id";
private static final String PROPERTY_APP_VERSION = "appVersion";
private static final int PLAY_SERVICES_RESOLUTION_REQUEST = 9000;
/**
* Substitute you own sender ID here. This is the project number you got
* from the API Console, as described in "Getting Started."
*/
String SENDER_ID = "Your-Sender-ID";
/**
* Tag used on log messages.
*/
static final String TAG = "GCM Demo";
TextView mDisplay;
GoogleCloudMessaging gcm;
AtomicInteger msgId = new AtomicInteger();
Context context;
String regid;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mDisplay = (TextView) findViewById(R.id.display);
context = getApplicationContext();
// Check device for Play Services APK. If check succeeds, proceed with GCM registration.
if (checkPlayServices()) {
gcm = GoogleCloudMessaging.getInstance(this);
regid = getRegistrationId(context);
if (regid.isEmpty()) {
registerInBackground();
}
} else {
Log.i(TAG, "No valid Google Play Services APK found.");
}
}
@Override
protected void onResume() {
super.onResume();
// Check device for Play Services APK.
checkPlayServices();
}
/**
* Check the device to make sure it has the Google Play Services APK. If
* it doesn't, display a dialog that allows users to download the APK from
* the Google Play Store or enable it in the device's system settings.
*/
private boolean checkPlayServices() {
int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
if (resultCode != ConnectionResult.SUCCESS) {
if (GooglePlayServicesUtil.isUserRecoverableError(resultCode)) {
GooglePlayServicesUtil.getErrorDialog(resultCode, this,
PLAY_SERVICES_RESOLUTION_REQUEST).show();
} else {
Log.i(TAG, "This device is not supported.");
finish();
}
return false;
}
return true;
}
/**
* Stores the registration ID and the app versionCode in the application's
* {@code SharedPreferences}.
*
* @param context application's context.
* @param regId registration ID
*/
private void storeRegistrationId(Context context, String regId) {
final SharedPreferences prefs = getGcmPreferences(context);
int appVersion = getAppVersion(context);
Log.i(TAG, "Saving regId on app version " + appVersion);
SharedPreferences.Editor editor = prefs.edit();
editor.putString(PROPERTY_REG_ID, regId);
editor.putInt(PROPERTY_APP_VERSION, appVersion);
editor.commit();
}
/**
* Gets the current registration ID for application on GCM service, if there is one.
* <p>
* If result is empty, the app needs to register.
*
* @return registration ID, or empty string if there is no existing
* registration ID.
*/
private String getRegistrationId(Context context) {
final SharedPreferences prefs = getGcmPreferences(context);
String registrationId = prefs.getString(PROPERTY_REG_ID, "");
if (registrationId.isEmpty()) {
Log.i(TAG, "Registration not found.");
return "";
}
// Check if app was updated; if so, it must clear the registration ID
// since the existing regID is not guaranteed to work with the new
// app version.
int registeredVersion = prefs.getInt(PROPERTY_APP_VERSION, Integer.MIN_VALUE);
int currentVersion = getAppVersion(context);
if (registeredVersion != currentVersion) {
Log.i(TAG, "App version changed.");
return "";
}
return registrationId;
}
/**
* Registers the application with GCM servers asynchronously.
* <p>
* Stores the registration ID and the app versionCode in the application's
* shared preferences.
*/
private void registerInBackground() {
new AsyncTask<Void, Void, String>() {
@Override
protected String doInBackground(Void... params) {
String msg = "";
try {
if (gcm == null) {
gcm = GoogleCloudMessaging.getInstance(context);
}
regid = gcm.register(SENDER_ID);
msg = "Device registered, registration ID=" + regid;
// You should send the registration ID to your server over HTTP, so it
// can use GCM/HTTP or CCS to send messages to your app.
sendRegistrationIdToBackend();
// For this demo: we don't need to send it because the device will send
// upstream messages to a server that echo back the message using the
// 'from' address in the message.
// Persist the regID - no need to register again.
storeRegistrationId(context, regid);
} catch (IOException ex) {
msg = "Error :" + ex.getMessage();
// If there is an error, don't just keep trying to register.
// Require the user to click a button again, or perform
// exponential back-off.
}
return msg;
}
@Override
protected void onPostExecute(String msg) {
mDisplay.append(msg + "\n");
}
}.execute(null, null, null);
}
// Send an upstream message.
public void onClick(final View view) {
if (view == findViewById(R.id.send)) {
new AsyncTask<Void, Void, String>() {
@Override
protected String doInBackground(Void... params) {
String msg = "";
try {
Bundle data = new Bundle();
data.putString("my_message", "Hello World");
data.putString("my_action", "com.google.android.gcm.demo.app.ECHO_NOW");
String id = Integer.toString(msgId.incrementAndGet());
gcm.send(SENDER_ID + "@gcm.googleapis.com", id, data);
msg = "Sent message";
} catch (IOException ex) {
msg = "Error :" + ex.getMessage();
}
return msg;
}
@Override
protected void onPostExecute(String msg) {
mDisplay.append(msg + "\n");
}
}.execute(null, null, null);
} else if (view == findViewById(R.id.clear)) {
mDisplay.setText("");
}
}
@Override
protected void onDestroy() {
super.onDestroy();
}
/**
* @return Application's version code from the {@code PackageManager}.
*/
private static int getAppVersion(Context context) {
try {
PackageInfo packageInfo = context.getPackageManager()
.getPackageInfo(context.getPackageName(), 0);
return packageInfo.versionCode;
} catch (NameNotFoundException e) {
// should never happen
throw new RuntimeException("Could not get package name: " + e);
}
}
/**
* @return Application's {@code SharedPreferences}.
*/
private SharedPreferences getGcmPreferences(Context context) {
// This sample app persists the registration ID in shared preferences, but
// how you store the regID in your app is up to you.
return getSharedPreferences(DemoActivity.class.getSimpleName(),
Context.MODE_PRIVATE);
}
/**
* Sends the registration ID to your server over HTTP, so it can use GCM/HTTP or CCS to send
* messages to your app. Not needed for this demo since the device sends upstream messages
* to a server that echoes back the message using the 'from' address in the message.
*/
private void sendRegistrationIdToBackend() {
// Your implementation here.
}
}
| Java |
/*
* Copyright 2013 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.gcm.demo.app;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.support.v4.content.WakefulBroadcastReceiver;
/**
* This {@code WakefulBroadcastReceiver} takes care of creating and managing a
* partial wake lock for your app. It passes off the work of processing the GCM
* message to an {@code IntentService}, while ensuring that the device does not
* go back to sleep in the transition. The {@code IntentService} calls
* {@code GcmBroadcastReceiver.completeWakefulIntent()} when it is ready to
* release the wake lock.
*/
public class GcmBroadcastReceiver extends WakefulBroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
// Explicitly specify that GcmIntentService will handle the intent.
ComponentName comp = new ComponentName(context.getPackageName(),
GcmIntentService.class.getName());
// Start the service, keeping the device awake while it is launching.
startWakefulService(context, (intent.setComponent(comp)));
setResultCode(Activity.RESULT_OK);
}
}
| Java |
/*
* Copyright (C) 2013 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.gcm.demo.app;
import com.google.android.gms.gcm.GoogleCloudMessaging;
import android.app.IntentService;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.SystemClock;
import android.support.v4.app.NotificationCompat;
import android.util.Log;
/**
* This {@code IntentService} does the actual handling of the GCM message.
* {@code GcmBroadcastReceiver} (a {@code WakefulBroadcastReceiver}) holds a
* partial wake lock for this service while the service does its work. When the
* service is finished, it calls {@code completeWakefulIntent()} to release the
* wake lock.
*/
public class GcmIntentService extends IntentService {
public static final int NOTIFICATION_ID = 1;
private NotificationManager mNotificationManager;
NotificationCompat.Builder builder;
public GcmIntentService() {
super("GcmIntentService");
}
public static final String TAG = "GCM Demo";
@Override
protected void onHandleIntent(Intent intent) {
Bundle extras = intent.getExtras();
GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(this);
// The getMessageType() intent parameter must be the intent you received
// in your BroadcastReceiver.
String messageType = gcm.getMessageType(intent);
if (!extras.isEmpty()) { // has effect of unparcelling Bundle
/*
* Filter messages based on message type. Since it is likely that GCM will be
* extended in the future with new message types, just ignore any message types you're
* not interested in, or that you don't recognize.
*/
if (GoogleCloudMessaging.MESSAGE_TYPE_SEND_ERROR.equals(messageType)) {
sendNotification("Send error: " + extras.toString());
} else if (GoogleCloudMessaging.MESSAGE_TYPE_DELETED.equals(messageType)) {
sendNotification("Deleted messages on server: " + extras.toString());
// If it's a regular GCM message, do some work.
} else if (GoogleCloudMessaging.MESSAGE_TYPE_MESSAGE.equals(messageType)) {
// This loop represents the service doing some work.
for (int i = 0; i < 5; i++) {
Log.i(TAG, "Working... " + (i + 1)
+ "/5 @ " + SystemClock.elapsedRealtime());
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
}
}
Log.i(TAG, "Completed work @ " + SystemClock.elapsedRealtime());
// Post notification of received message.
sendNotification("Received: " + extras.toString());
Log.i(TAG, "Received: " + extras.toString());
}
}
// Release the wake lock provided by the WakefulBroadcastReceiver.
GcmBroadcastReceiver.completeWakefulIntent(intent);
}
// Put the message into a notification and post it.
// This is just one simple example of what you might choose to do with
// a GCM message.
private void sendNotification(String msg) {
mNotificationManager = (NotificationManager)
this.getSystemService(Context.NOTIFICATION_SERVICE);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
new Intent(this, DemoActivity.class), 0);
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_stat_gcm)
.setContentTitle("GCM Notification")
.setStyle(new NotificationCompat.BigTextStyle()
.bigText(msg))
.setContentText(msg);
mBuilder.setContentIntent(contentIntent);
mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());
}
}
| Java |
/*
* Copyright 2012 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.gcm.server;
import java.io.IOException;
/**
* Exception thrown when GCM returned an error due to an invalid request.
* <p>
* This is equivalent to GCM posts that return an HTTP error different of 200.
*/
public final class InvalidRequestException extends IOException {
private final int status;
private final String description;
public InvalidRequestException(int status) {
this(status, null);
}
public InvalidRequestException(int status, String description) {
super(getMessage(status, description));
this.status = status;
this.description = description;
}
private static String getMessage(int status, String description) {
StringBuilder base = new StringBuilder("HTTP Status Code: ").append(status);
if (description != null) {
base.append("(").append(description).append(")");
}
return base.toString();
}
/**
* Gets the HTTP Status Code.
*/
public int getHttpStatusCode() {
return status;
}
/**
* Gets the error description.
*/
public String getDescription() {
return description;
}
}
| Java |
/*
* Copyright 2012 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.gcm.server;
import java.io.Serializable;
/**
* Result of a GCM message request that returned HTTP status code 200.
*
* <p>
* If the message is successfully created, the {@link #getMessageId()} returns
* the message id and {@link #getErrorCodeName()} returns {@literal null};
* otherwise, {@link #getMessageId()} returns {@literal null} and
* {@link #getErrorCodeName()} returns the code of the error.
*
* <p>
* There are cases when a request is accept and the message successfully
* created, but GCM has a canonical registration id for that device. In this
* case, the server should update the registration id to avoid rejected requests
* in the future.
*
* <p>
* In a nutshell, the workflow to handle a result is:
* <pre>
* - Call {@link #getMessageId()}:
* - {@literal null} means error, call {@link #getErrorCodeName()}
* - non-{@literal null} means the message was created:
* - Call {@link #getCanonicalRegistrationId()}
* - if it returns {@literal null}, do nothing.
* - otherwise, update the server datastore with the new id.
* </pre>
*/
public final class Result implements Serializable {
private final String messageId;
private final String canonicalRegistrationId;
private final String errorCode;
public static final class Builder {
// optional parameters
private String messageId;
private String canonicalRegistrationId;
private String errorCode;
public Builder canonicalRegistrationId(String value) {
canonicalRegistrationId = value;
return this;
}
public Builder messageId(String value) {
messageId = value;
return this;
}
public Builder errorCode(String value) {
errorCode = value;
return this;
}
public Result build() {
return new Result(this);
}
}
private Result(Builder builder) {
canonicalRegistrationId = builder.canonicalRegistrationId;
messageId = builder.messageId;
errorCode = builder.errorCode;
}
/**
* Gets the message id, if any.
*/
public String getMessageId() {
return messageId;
}
/**
* Gets the canonical registration id, if any.
*/
public String getCanonicalRegistrationId() {
return canonicalRegistrationId;
}
/**
* Gets the error code, if any.
*/
public String getErrorCodeName() {
return errorCode;
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder("[");
if (messageId != null) {
builder.append(" messageId=").append(messageId);
}
if (canonicalRegistrationId != null) {
builder.append(" canonicalRegistrationId=")
.append(canonicalRegistrationId);
}
if (errorCode != null) {
builder.append(" errorCode=").append(errorCode);
}
return builder.append(" ]").toString();
}
}
| Java |
/*
* Copyright 2012 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.gcm.server;
import static com.google.android.gcm.server.Constants.GCM_SEND_ENDPOINT;
import static com.google.android.gcm.server.Constants.JSON_CANONICAL_IDS;
import static com.google.android.gcm.server.Constants.JSON_ERROR;
import static com.google.android.gcm.server.Constants.JSON_FAILURE;
import static com.google.android.gcm.server.Constants.JSON_MESSAGE_ID;
import static com.google.android.gcm.server.Constants.JSON_MULTICAST_ID;
import static com.google.android.gcm.server.Constants.JSON_PAYLOAD;
import static com.google.android.gcm.server.Constants.JSON_REGISTRATION_IDS;
import static com.google.android.gcm.server.Constants.JSON_RESULTS;
import static com.google.android.gcm.server.Constants.JSON_SUCCESS;
import static com.google.android.gcm.server.Constants.PARAM_COLLAPSE_KEY;
import static com.google.android.gcm.server.Constants.PARAM_DELAY_WHILE_IDLE;
import static com.google.android.gcm.server.Constants.PARAM_DRY_RUN;
import static com.google.android.gcm.server.Constants.PARAM_PAYLOAD_PREFIX;
import static com.google.android.gcm.server.Constants.PARAM_REGISTRATION_ID;
import static com.google.android.gcm.server.Constants.PARAM_RESTRICTED_PACKAGE_NAME;
import static com.google.android.gcm.server.Constants.PARAM_TIME_TO_LIVE;
import static com.google.android.gcm.server.Constants.TOKEN_CANONICAL_REG_ID;
import static com.google.android.gcm.server.Constants.TOKEN_ERROR;
import static com.google.android.gcm.server.Constants.TOKEN_MESSAGE_ID;
import com.google.android.gcm.server.Result.Builder;
import org.json.simple.JSONObject;
import org.json.simple.JSONValue;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import java.io.BufferedReader;
import java.io.Closeable;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Random;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* Helper class to send messages to the GCM service using an API Key.
*/
public class Sender {
protected static final String UTF8 = "UTF-8";
/**
* Initial delay before first retry, without jitter.
*/
protected static final int BACKOFF_INITIAL_DELAY = 1000;
/**
* Maximum delay before a retry.
*/
protected static final int MAX_BACKOFF_DELAY = 1024000;
protected final Random random = new Random();
protected static final Logger logger =
Logger.getLogger(Sender.class.getName());
private final String key;
/**
* Default constructor.
*
* @param key API key obtained through the Google API Console.
*/
public Sender(String key) {
this.key = nonNull(key);
}
/**
* Sends a message to one device, retrying in case of unavailability.
*
* <p>
* <strong>Note: </strong> this method uses exponential back-off to retry in
* case of service unavailability and hence could block the calling thread
* for many seconds.
*
* @param message message to be sent, including the device's registration id.
* @param registrationId device where the message will be sent.
* @param retries number of retries in case of service unavailability errors.
*
* @return result of the request (see its javadoc for more details).
*
* @throws IllegalArgumentException if registrationId is {@literal null}.
* @throws InvalidRequestException if GCM didn't returned a 200 or 5xx status.
* @throws IOException if message could not be sent.
*/
public Result send(Message message, String registrationId, int retries)
throws IOException {
int attempt = 0;
Result result = null;
int backoff = BACKOFF_INITIAL_DELAY;
boolean tryAgain;
do {
attempt++;
if (logger.isLoggable(Level.FINE)) {
logger.fine("Attempt #" + attempt + " to send message " +
message + " to regIds " + registrationId);
}
result = sendNoRetry(message, registrationId);
tryAgain = result == null && attempt <= retries;
if (tryAgain) {
int sleepTime = backoff / 2 + random.nextInt(backoff);
sleep(sleepTime);
if (2 * backoff < MAX_BACKOFF_DELAY) {
backoff *= 2;
}
}
} while (tryAgain);
if (result == null) {
throw new IOException("Could not send message after " + attempt +
" attempts");
}
return result;
}
/**
* Sends a message without retrying in case of service unavailability. See
* {@link #send(Message, String, int)} for more info.
*
* @return result of the post, or {@literal null} if the GCM service was
* unavailable or any network exception caused the request to fail.
*
* @throws InvalidRequestException if GCM didn't returned a 200 or 5xx status.
* @throws IllegalArgumentException if registrationId is {@literal null}.
*/
public Result sendNoRetry(Message message, String registrationId)
throws IOException {
StringBuilder body = newBody(PARAM_REGISTRATION_ID, registrationId);
Boolean delayWhileIdle = message.isDelayWhileIdle();
if (delayWhileIdle != null) {
addParameter(body, PARAM_DELAY_WHILE_IDLE, delayWhileIdle ? "1" : "0");
}
Boolean dryRun = message.isDryRun();
if (dryRun != null) {
addParameter(body, PARAM_DRY_RUN, dryRun ? "1" : "0");
}
String collapseKey = message.getCollapseKey();
if (collapseKey != null) {
addParameter(body, PARAM_COLLAPSE_KEY, collapseKey);
}
String restrictedPackageName = message.getRestrictedPackageName();
if (restrictedPackageName != null) {
addParameter(body, PARAM_RESTRICTED_PACKAGE_NAME, restrictedPackageName);
}
Integer timeToLive = message.getTimeToLive();
if (timeToLive != null) {
addParameter(body, PARAM_TIME_TO_LIVE, Integer.toString(timeToLive));
}
for (Entry<String, String> entry : message.getData().entrySet()) {
String key = entry.getKey();
String value = entry.getValue();
if (key == null || value == null) {
logger.warning("Ignoring payload entry thas has null: " + entry);
} else {
key = PARAM_PAYLOAD_PREFIX + key;
addParameter(body, key, URLEncoder.encode(value, UTF8));
}
}
String requestBody = body.toString();
logger.finest("Request body: " + requestBody);
HttpURLConnection conn;
int status;
try {
conn = post(GCM_SEND_ENDPOINT, requestBody);
status = conn.getResponseCode();
} catch (IOException e) {
logger.log(Level.FINE, "IOException posting to GCM", e);
return null;
}
if (status / 100 == 5) {
logger.fine("GCM service is unavailable (status " + status + ")");
return null;
}
String responseBody;
if (status != 200) {
try {
responseBody = getAndClose(conn.getErrorStream());
logger.finest("Plain post error response: " + responseBody);
} catch (IOException e) {
// ignore the exception since it will thrown an InvalidRequestException
// anyways
responseBody = "N/A";
logger.log(Level.FINE, "Exception reading response: ", e);
}
throw new InvalidRequestException(status, responseBody);
} else {
try {
responseBody = getAndClose(conn.getInputStream());
} catch (IOException e) {
logger.log(Level.WARNING, "Exception reading response: ", e);
// return null so it can retry
return null;
}
}
String[] lines = responseBody.split("\n");
if (lines.length == 0 || lines[0].equals("")) {
throw new IOException("Received empty response from GCM service.");
}
String firstLine = lines[0];
String[] responseParts = split(firstLine);
String token = responseParts[0];
String value = responseParts[1];
if (token.equals(TOKEN_MESSAGE_ID)) {
Builder builder = new Result.Builder().messageId(value);
// check for canonical registration id
if (lines.length > 1) {
String secondLine = lines[1];
responseParts = split(secondLine);
token = responseParts[0];
value = responseParts[1];
if (token.equals(TOKEN_CANONICAL_REG_ID)) {
builder.canonicalRegistrationId(value);
} else {
logger.warning("Invalid response from GCM: " + responseBody);
}
}
Result result = builder.build();
if (logger.isLoggable(Level.FINE)) {
logger.fine("Message created succesfully (" + result + ")");
}
return result;
} else if (token.equals(TOKEN_ERROR)) {
return new Result.Builder().errorCode(value).build();
} else {
throw new IOException("Invalid response from GCM: " + responseBody);
}
}
/**
* Sends a message to many devices, retrying in case of unavailability.
*
* <p>
* <strong>Note: </strong> this method uses exponential back-off to retry in
* case of service unavailability and hence could block the calling thread
* for many seconds.
*
* @param message message to be sent.
* @param regIds registration id of the devices that will receive
* the message.
* @param retries number of retries in case of service unavailability errors.
*
* @return combined result of all requests made.
*
* @throws IllegalArgumentException if registrationIds is {@literal null} or
* empty.
* @throws InvalidRequestException if GCM didn't returned a 200 or 503 status.
* @throws IOException if message could not be sent.
*/
public MulticastResult send(Message message, List<String> regIds, int retries)
throws IOException {
int attempt = 0;
MulticastResult multicastResult;
int backoff = BACKOFF_INITIAL_DELAY;
// Map of results by registration id, it will be updated after each attempt
// to send the messages
Map<String, Result> results = new HashMap<String, Result>();
List<String> unsentRegIds = new ArrayList<String>(regIds);
boolean tryAgain;
List<Long> multicastIds = new ArrayList<Long>();
do {
multicastResult = null;
attempt++;
if (logger.isLoggable(Level.FINE)) {
logger.fine("Attempt #" + attempt + " to send message " +
message + " to regIds " + unsentRegIds);
}
try {
multicastResult = sendNoRetry(message, unsentRegIds);
} catch(IOException e) {
// no need for WARNING since exception might be already logged
logger.log(Level.FINEST, "IOException on attempt " + attempt, e);
}
if (multicastResult != null) {
long multicastId = multicastResult.getMulticastId();
logger.fine("multicast_id on attempt # " + attempt + ": " +
multicastId);
multicastIds.add(multicastId);
unsentRegIds = updateStatus(unsentRegIds, results, multicastResult);
tryAgain = !unsentRegIds.isEmpty() && attempt <= retries;
} else {
tryAgain = attempt <= retries;
}
if (tryAgain) {
int sleepTime = backoff / 2 + random.nextInt(backoff);
sleep(sleepTime);
if (2 * backoff < MAX_BACKOFF_DELAY) {
backoff *= 2;
}
}
} while (tryAgain);
if (multicastIds.isEmpty()) {
// all JSON posts failed due to GCM unavailability
throw new IOException("Could not post JSON requests to GCM after "
+ attempt + " attempts");
}
// calculate summary
int success = 0, failure = 0 , canonicalIds = 0;
for (Result result : results.values()) {
if (result.getMessageId() != null) {
success++;
if (result.getCanonicalRegistrationId() != null) {
canonicalIds++;
}
} else {
failure++;
}
}
// build a new object with the overall result
long multicastId = multicastIds.remove(0);
MulticastResult.Builder builder = new MulticastResult.Builder(success,
failure, canonicalIds, multicastId).retryMulticastIds(multicastIds);
// add results, in the same order as the input
for (String regId : regIds) {
Result result = results.get(regId);
builder.addResult(result);
}
return builder.build();
}
/**
* Updates the status of the messages sent to devices and the list of devices
* that should be retried.
*
* @param unsentRegIds list of devices that are still pending an update.
* @param allResults map of status that will be updated.
* @param multicastResult result of the last multicast sent.
*
* @return updated version of devices that should be retried.
*/
private List<String> updateStatus(List<String> unsentRegIds,
Map<String, Result> allResults, MulticastResult multicastResult) {
List<Result> results = multicastResult.getResults();
if (results.size() != unsentRegIds.size()) {
// should never happen, unless there is a flaw in the algorithm
throw new RuntimeException("Internal error: sizes do not match. " +
"currentResults: " + results + "; unsentRegIds: " + unsentRegIds);
}
List<String> newUnsentRegIds = new ArrayList<String>();
for (int i = 0; i < unsentRegIds.size(); i++) {
String regId = unsentRegIds.get(i);
Result result = results.get(i);
allResults.put(regId, result);
String error = result.getErrorCodeName();
if (error != null && (error.equals(Constants.ERROR_UNAVAILABLE)
|| error.equals(Constants.ERROR_INTERNAL_SERVER_ERROR))) {
newUnsentRegIds.add(regId);
}
}
return newUnsentRegIds;
}
/**
* Sends a message without retrying in case of service unavailability. See
* {@link #send(Message, List, int)} for more info.
*
* @return multicast results if the message was sent successfully,
* {@literal null} if it failed but could be retried.
*
* @throws IllegalArgumentException if registrationIds is {@literal null} or
* empty.
* @throws InvalidRequestException if GCM didn't returned a 200 status.
* @throws IOException if there was a JSON parsing error
*/
public MulticastResult sendNoRetry(Message message,
List<String> registrationIds) throws IOException {
if (nonNull(registrationIds).isEmpty()) {
throw new IllegalArgumentException("registrationIds cannot be empty");
}
Map<Object, Object> jsonRequest = new HashMap<Object, Object>();
setJsonField(jsonRequest, PARAM_TIME_TO_LIVE, message.getTimeToLive());
setJsonField(jsonRequest, PARAM_COLLAPSE_KEY, message.getCollapseKey());
setJsonField(jsonRequest, PARAM_RESTRICTED_PACKAGE_NAME, message.getRestrictedPackageName());
setJsonField(jsonRequest, PARAM_DELAY_WHILE_IDLE,
message.isDelayWhileIdle());
setJsonField(jsonRequest, PARAM_DRY_RUN, message.isDryRun());
jsonRequest.put(JSON_REGISTRATION_IDS, registrationIds);
Map<String, String> payload = message.getData();
if (!payload.isEmpty()) {
jsonRequest.put(JSON_PAYLOAD, payload);
}
String requestBody = JSONValue.toJSONString(jsonRequest);
logger.finest("JSON request: " + requestBody);
HttpURLConnection conn;
int status;
try {
conn = post(GCM_SEND_ENDPOINT, "application/json", requestBody);
status = conn.getResponseCode();
} catch (IOException e) {
logger.log(Level.FINE, "IOException posting to GCM", e);
return null;
}
String responseBody;
if (status != 200) {
try {
responseBody = getAndClose(conn.getErrorStream());
logger.finest("JSON error response: " + responseBody);
} catch (IOException e) {
// ignore the exception since it will thrown an InvalidRequestException
// anyways
responseBody = "N/A";
logger.log(Level.FINE, "Exception reading response: ", e);
}
throw new InvalidRequestException(status, responseBody);
}
try {
responseBody = getAndClose(conn.getInputStream());
} catch(IOException e) {
logger.log(Level.WARNING, "IOException reading response", e);
return null;
}
logger.finest("JSON response: " + responseBody);
JSONParser parser = new JSONParser();
JSONObject jsonResponse;
try {
jsonResponse = (JSONObject) parser.parse(responseBody);
int success = getNumber(jsonResponse, JSON_SUCCESS).intValue();
int failure = getNumber(jsonResponse, JSON_FAILURE).intValue();
int canonicalIds = getNumber(jsonResponse, JSON_CANONICAL_IDS).intValue();
long multicastId = getNumber(jsonResponse, JSON_MULTICAST_ID).longValue();
MulticastResult.Builder builder = new MulticastResult.Builder(success,
failure, canonicalIds, multicastId);
@SuppressWarnings("unchecked")
List<Map<String, Object>> results =
(List<Map<String, Object>>) jsonResponse.get(JSON_RESULTS);
if (results != null) {
for (Map<String, Object> jsonResult : results) {
String messageId = (String) jsonResult.get(JSON_MESSAGE_ID);
String canonicalRegId =
(String) jsonResult.get(TOKEN_CANONICAL_REG_ID);
String error = (String) jsonResult.get(JSON_ERROR);
Result result = new Result.Builder()
.messageId(messageId)
.canonicalRegistrationId(canonicalRegId)
.errorCode(error)
.build();
builder.addResult(result);
}
}
MulticastResult multicastResult = builder.build();
return multicastResult;
} catch (ParseException e) {
throw newIoException(responseBody, e);
} catch (CustomParserException e) {
throw newIoException(responseBody, e);
}
}
private IOException newIoException(String responseBody, Exception e) {
// log exception, as IOException constructor that takes a message and cause
// is only available on Java 6
String msg = "Error parsing JSON response (" + responseBody + ")";
logger.log(Level.WARNING, msg, e);
return new IOException(msg + ":" + e);
}
private static void close(Closeable closeable) {
if (closeable != null) {
try {
closeable.close();
} catch (IOException e) {
// ignore error
logger.log(Level.FINEST, "IOException closing stream", e);
}
}
}
/**
* Sets a JSON field, but only if the value is not {@literal null}.
*/
private void setJsonField(Map<Object, Object> json, String field,
Object value) {
if (value != null) {
json.put(field, value);
}
}
private Number getNumber(Map<?, ?> json, String field) {
Object value = json.get(field);
if (value == null) {
throw new CustomParserException("Missing field: " + field);
}
if (!(value instanceof Number)) {
throw new CustomParserException("Field " + field +
" does not contain a number: " + value);
}
return (Number) value;
}
class CustomParserException extends RuntimeException {
CustomParserException(String message) {
super(message);
}
}
private String[] split(String line) throws IOException {
String[] split = line.split("=", 2);
if (split.length != 2) {
throw new IOException("Received invalid response line from GCM: " + line);
}
return split;
}
/**
* Make an HTTP post to a given URL.
*
* @return HTTP response.
*/
protected HttpURLConnection post(String url, String body)
throws IOException {
return post(url, "application/x-www-form-urlencoded;charset=UTF-8", body);
}
/**
* Makes an HTTP POST request to a given endpoint.
*
* <p>
* <strong>Note: </strong> the returned connected should not be disconnected,
* otherwise it would kill persistent connections made using Keep-Alive.
*
* @param url endpoint to post the request.
* @param contentType type of request.
* @param body body of the request.
*
* @return the underlying connection.
*
* @throws IOException propagated from underlying methods.
*/
protected HttpURLConnection post(String url, String contentType, String body)
throws IOException {
if (url == null || body == null) {
throw new IllegalArgumentException("arguments cannot be null");
}
if (!url.startsWith("https://")) {
logger.warning("URL does not use https: " + url);
}
logger.fine("Sending POST to " + url);
logger.finest("POST body: " + body);
byte[] bytes = body.getBytes();
HttpURLConnection conn = getConnection(url);
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setFixedLengthStreamingMode(bytes.length);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", contentType);
conn.setRequestProperty("Authorization", "key=" + key);
OutputStream out = conn.getOutputStream();
try {
out.write(bytes);
} finally {
close(out);
}
return conn;
}
/**
* Creates a map with just one key-value pair.
*/
protected static final Map<String, String> newKeyValues(String key,
String value) {
Map<String, String> keyValues = new HashMap<String, String>(1);
keyValues.put(nonNull(key), nonNull(value));
return keyValues;
}
/**
* Creates a {@link StringBuilder} to be used as the body of an HTTP POST.
*
* @param name initial parameter for the POST.
* @param value initial value for that parameter.
* @return StringBuilder to be used an HTTP POST body.
*/
protected static StringBuilder newBody(String name, String value) {
return new StringBuilder(nonNull(name)).append('=').append(nonNull(value));
}
/**
* Adds a new parameter to the HTTP POST body.
*
* @param body HTTP POST body.
* @param name parameter's name.
* @param value parameter's value.
*/
protected static void addParameter(StringBuilder body, String name,
String value) {
nonNull(body).append('&')
.append(nonNull(name)).append('=').append(nonNull(value));
}
/**
* Gets an {@link HttpURLConnection} given an URL.
*/
protected HttpURLConnection getConnection(String url) throws IOException {
HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
return conn;
}
/**
* Convenience method to convert an InputStream to a String.
* <p>
* If the stream ends in a newline character, it will be stripped.
* <p>
* If the stream is {@literal null}, returns an empty string.
*/
protected static String getString(InputStream stream) throws IOException {
if (stream == null) {
return "";
}
BufferedReader reader =
new BufferedReader(new InputStreamReader(stream));
StringBuilder content = new StringBuilder();
String newLine;
do {
newLine = reader.readLine();
if (newLine != null) {
content.append(newLine).append('\n');
}
} while (newLine != null);
if (content.length() > 0) {
// strip last newline
content.setLength(content.length() - 1);
}
return content.toString();
}
private static String getAndClose(InputStream stream) throws IOException {
try {
return getString(stream);
} finally {
if (stream != null) {
close(stream);
}
}
}
static <T> T nonNull(T argument) {
if (argument == null) {
throw new IllegalArgumentException("argument cannot be null");
}
return argument;
}
void sleep(long millis) {
try {
Thread.sleep(millis);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
| Java |
/*
* Copyright 2012 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.gcm.server;
/**
* Constants used on GCM service communication.
*/
public final class Constants {
/**
* Endpoint for sending messages.
*/
public static final String GCM_SEND_ENDPOINT =
"https://android.googleapis.com/gcm/send";
/**
* HTTP parameter for registration id.
*/
public static final String PARAM_REGISTRATION_ID = "registration_id";
/**
* HTTP parameter for collapse key.
*/
public static final String PARAM_COLLAPSE_KEY = "collapse_key";
/**
* HTTP parameter for delaying the message delivery if the device is idle.
*/
public static final String PARAM_DELAY_WHILE_IDLE = "delay_while_idle";
/**
* HTTP parameter for telling gcm to validate the message without actually sending it.
*/
public static final String PARAM_DRY_RUN = "dry_run";
/**
* HTTP parameter for package name that can be used to restrict message delivery by matching
* against the package name used to generate the registration id.
*/
public static final String PARAM_RESTRICTED_PACKAGE_NAME = "restricted_package_name";
/**
* Prefix to HTTP parameter used to pass key-values in the message payload.
*/
public static final String PARAM_PAYLOAD_PREFIX = "data.";
/**
* Prefix to HTTP parameter used to set the message time-to-live.
*/
public static final String PARAM_TIME_TO_LIVE = "time_to_live";
/**
* Too many messages sent by the sender. Retry after a while.
*/
public static final String ERROR_QUOTA_EXCEEDED = "QuotaExceeded";
/**
* Too many messages sent by the sender to a specific device.
* Retry after a while.
*/
public static final String ERROR_DEVICE_QUOTA_EXCEEDED =
"DeviceQuotaExceeded";
/**
* Missing registration_id.
* Sender should always add the registration_id to the request.
*/
public static final String ERROR_MISSING_REGISTRATION = "MissingRegistration";
/**
* Bad registration_id. Sender should remove this registration_id.
*/
public static final String ERROR_INVALID_REGISTRATION = "InvalidRegistration";
/**
* The sender_id contained in the registration_id does not match the
* sender_id used to register with the GCM servers.
*/
public static final String ERROR_MISMATCH_SENDER_ID = "MismatchSenderId";
/**
* The user has uninstalled the application or turned off notifications.
* Sender should stop sending messages to this device and delete the
* registration_id. The client needs to re-register with the GCM servers to
* receive notifications again.
*/
public static final String ERROR_NOT_REGISTERED = "NotRegistered";
/**
* The payload of the message is too big, see the limitations.
* Reduce the size of the message.
*/
public static final String ERROR_MESSAGE_TOO_BIG = "MessageTooBig";
/**
* Collapse key is required. Include collapse key in the request.
*/
public static final String ERROR_MISSING_COLLAPSE_KEY = "MissingCollapseKey";
/**
* A particular message could not be sent because the GCM servers were not
* available. Used only on JSON requests, as in plain text requests
* unavailability is indicated by a 503 response.
*/
public static final String ERROR_UNAVAILABLE = "Unavailable";
/**
* A particular message could not be sent because the GCM servers encountered
* an error. Used only on JSON requests, as in plain text requests internal
* errors are indicated by a 500 response.
*/
public static final String ERROR_INTERNAL_SERVER_ERROR =
"InternalServerError";
/**
* Time to Live value passed is less than zero or more than maximum.
*/
public static final String ERROR_INVALID_TTL= "InvalidTtl";
/**
* Token returned by GCM when a message was successfully sent.
*/
public static final String TOKEN_MESSAGE_ID = "id";
/**
* Token returned by GCM when the requested registration id has a canonical
* value.
*/
public static final String TOKEN_CANONICAL_REG_ID = "registration_id";
/**
* Token returned by GCM when there was an error sending a message.
*/
public static final String TOKEN_ERROR = "Error";
/**
* JSON-only field representing the registration ids.
*/
public static final String JSON_REGISTRATION_IDS = "registration_ids";
/**
* JSON-only field representing the payload data.
*/
public static final String JSON_PAYLOAD = "data";
/**
* JSON-only field representing the number of successful messages.
*/
public static final String JSON_SUCCESS = "success";
/**
* JSON-only field representing the number of failed messages.
*/
public static final String JSON_FAILURE = "failure";
/**
* JSON-only field representing the number of messages with a canonical
* registration id.
*/
public static final String JSON_CANONICAL_IDS = "canonical_ids";
/**
* JSON-only field representing the id of the multicast request.
*/
public static final String JSON_MULTICAST_ID = "multicast_id";
/**
* JSON-only field representing the result of each individual request.
*/
public static final String JSON_RESULTS = "results";
/**
* JSON-only field representing the error field of an individual request.
*/
public static final String JSON_ERROR = "error";
/**
* JSON-only field sent by GCM when a message was successfully sent.
*/
public static final String JSON_MESSAGE_ID = "message_id";
private Constants() {
throw new UnsupportedOperationException();
}
}
| Java |
/*
* Copyright 2012 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.gcm.server;
import java.io.Serializable;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.Map;
/**
* GCM message.
*
* <p>
* Instances of this class are immutable and should be created using a
* {@link Builder}. Examples:
*
* <strong>Simplest message:</strong>
* <pre><code>
* Message message = new Message.Builder().build();
* </pre></code>
*
* <strong>Message with optional attributes:</strong>
* <pre><code>
* Message message = new Message.Builder()
* .collapseKey(collapseKey)
* .timeToLive(3)
* .delayWhileIdle(true)
* .dryRun(true)
* .restrictedPackageName(restrictedPackageName)
* .build();
* </pre></code>
*
* <strong>Message with optional attributes and payload data:</strong>
* <pre><code>
* Message message = new Message.Builder()
* .collapseKey(collapseKey)
* .timeToLive(3)
* .delayWhileIdle(true)
* .dryRun(true)
* .restrictedPackageName(restrictedPackageName)
* .addData("key1", "value1")
* .addData("key2", "value2")
* .build();
* </pre></code>
*/
public final class Message implements Serializable {
private final String collapseKey;
private final Boolean delayWhileIdle;
private final Integer timeToLive;
private final Map<String, String> data;
private final Boolean dryRun;
private final String restrictedPackageName;
public static final class Builder {
private final Map<String, String> data;
// optional parameters
private String collapseKey;
private Boolean delayWhileIdle;
private Integer timeToLive;
private Boolean dryRun;
private String restrictedPackageName;
public Builder() {
this.data = new LinkedHashMap<String, String>();
}
/**
* Sets the collapseKey property.
*/
public Builder collapseKey(String value) {
collapseKey = value;
return this;
}
/**
* Sets the delayWhileIdle property (default value is {@literal false}).
*/
public Builder delayWhileIdle(boolean value) {
delayWhileIdle = value;
return this;
}
/**
* Sets the time to live, in seconds.
*/
public Builder timeToLive(int value) {
timeToLive = value;
return this;
}
/**
* Adds a key/value pair to the payload data.
*/
public Builder addData(String key, String value) {
data.put(key, value);
return this;
}
/**
* Sets the dryRun property (default value is {@literal false}).
*/
public Builder dryRun(boolean value) {
dryRun = value;
return this;
}
/**
* Sets the restrictedPackageName property.
*/
public Builder restrictedPackageName(String value) {
restrictedPackageName = value;
return this;
}
public Message build() {
return new Message(this);
}
}
private Message(Builder builder) {
collapseKey = builder.collapseKey;
delayWhileIdle = builder.delayWhileIdle;
data = Collections.unmodifiableMap(builder.data);
timeToLive = builder.timeToLive;
dryRun = builder.dryRun;
restrictedPackageName = builder.restrictedPackageName;
}
/**
* Gets the collapse key.
*/
public String getCollapseKey() {
return collapseKey;
}
/**
* Gets the delayWhileIdle flag.
*/
public Boolean isDelayWhileIdle() {
return delayWhileIdle;
}
/**
* Gets the time to live (in seconds).
*/
public Integer getTimeToLive() {
return timeToLive;
}
/**
* Gets the dryRun flag.
*/
public Boolean isDryRun() {
return dryRun;
}
/**
* Gets the restricted package name.
*/
public String getRestrictedPackageName() {
return restrictedPackageName;
}
/**
* Gets the payload data, which is immutable.
*/
public Map<String, String> getData() {
return data;
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder("Message(");
if (collapseKey != null) {
builder.append("collapseKey=").append(collapseKey).append(", ");
}
if (timeToLive != null) {
builder.append("timeToLive=").append(timeToLive).append(", ");
}
if (delayWhileIdle != null) {
builder.append("delayWhileIdle=").append(delayWhileIdle).append(", ");
}
if (dryRun != null) {
builder.append("dryRun=").append(dryRun).append(", ");
}
if (restrictedPackageName != null) {
builder.append("restrictedPackageName=").append(restrictedPackageName).append(", ");
}
if (!data.isEmpty()) {
builder.append("data: {");
for (Map.Entry<String, String> entry : data.entrySet()) {
builder.append(entry.getKey()).append("=").append(entry.getValue())
.append(",");
}
builder.delete(builder.length() - 1, builder.length());
builder.append("}");
}
if (builder.charAt(builder.length() - 1) == ' ') {
builder.delete(builder.length() - 2, builder.length());
}
builder.append(")");
return builder.toString();
}
}
| Java |
/*
* Copyright 2012 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.gcm.server;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
* Result of a GCM multicast message request .
*/
public final class MulticastResult implements Serializable {
private final int success;
private final int failure;
private final int canonicalIds;
private final long multicastId;
private final List<Result> results;
private final List<Long> retryMulticastIds;
public static final class Builder {
private final List<Result> results = new ArrayList<Result>();
// required parameters
private final int success;
private final int failure;
private final int canonicalIds;
private final long multicastId;
// optional parameters
private List<Long> retryMulticastIds;
public Builder(int success, int failure, int canonicalIds,
long multicastId) {
this.success = success;
this.failure = failure;
this.canonicalIds = canonicalIds;
this.multicastId = multicastId;
}
public Builder addResult(Result result) {
results.add(result);
return this;
}
public Builder retryMulticastIds(List<Long> retryMulticastIds) {
this.retryMulticastIds = retryMulticastIds;
return this;
}
public MulticastResult build() {
return new MulticastResult(this);
}
}
private MulticastResult(Builder builder) {
success = builder.success;
failure = builder.failure;
canonicalIds = builder.canonicalIds;
multicastId = builder.multicastId;
results = Collections.unmodifiableList(builder.results);
List<Long> tmpList = builder.retryMulticastIds;
if (tmpList == null) {
tmpList = Collections.emptyList();
}
retryMulticastIds = Collections.unmodifiableList(tmpList);
}
/**
* Gets the multicast id.
*/
public long getMulticastId() {
return multicastId;
}
/**
* Gets the number of successful messages.
*/
public int getSuccess() {
return success;
}
/**
* Gets the total number of messages sent, regardless of the status.
*/
public int getTotal() {
return success + failure;
}
/**
* Gets the number of failed messages.
*/
public int getFailure() {
return failure;
}
/**
* Gets the number of successful messages that also returned a canonical
* registration id.
*/
public int getCanonicalIds() {
return canonicalIds;
}
/**
* Gets the results of each individual message, which is immutable.
*/
public List<Result> getResults() {
return results;
}
/**
* Gets additional ids if more than one multicast message was sent.
*/
public List<Long> getRetryMulticastIds() {
return retryMulticastIds;
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder("MulticastResult(")
.append("multicast_id=").append(multicastId).append(",")
.append("total=").append(getTotal()).append(",")
.append("success=").append(success).append(",")
.append("failure=").append(failure).append(",")
.append("canonical_ids=").append(canonicalIds).append(",");
if (!results.isEmpty()) {
builder.append("results: " + results);
}
return builder.toString();
}
}
| Java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.