1
0
mirror of https://github.com/SquidDev-CC/CC-Tweaked synced 2024-06-30 17:13:20 +00:00

Java 8. Java 8. Does whatever Java 8 can.

Default methods, everywhere.
Arrow types, switch on strings.
Lambdas!
Here comes Java 8.
This commit is contained in:
SquidDev 2017-06-12 21:08:35 +01:00
parent 08099f08f2
commit d29ffed383
76 changed files with 747 additions and 665 deletions

View File

@ -239,11 +239,11 @@ public static class Config {
public static Logger log; public static Logger log;
// API users // API users
private static List<IPeripheralProvider> peripheralProviders = new ArrayList<IPeripheralProvider>(); private static List<IPeripheralProvider> peripheralProviders = new ArrayList<>();
private static List<IBundledRedstoneProvider> bundledRedstoneProviders = new ArrayList<IBundledRedstoneProvider>(); private static List<IBundledRedstoneProvider> bundledRedstoneProviders = new ArrayList<>();
private static List<IMediaProvider> mediaProviders = new ArrayList<IMediaProvider>(); private static List<IMediaProvider> mediaProviders = new ArrayList<>();
private static List<ITurtlePermissionProvider> permissionProviders = new ArrayList<ITurtlePermissionProvider>(); private static List<ITurtlePermissionProvider> permissionProviders = new ArrayList<>();
private static final Map<String, IPocketUpgrade> pocketUpgrades = new HashMap<String, IPocketUpgrade>(); private static final Map<String, IPocketUpgrade> pocketUpgrades = new HashMap<>();
// Implementation // Implementation
@Mod.Instance( value = ComputerCraft.MOD_ID ) @Mod.Instance( value = ComputerCraft.MOD_ID )
@ -755,7 +755,7 @@ public static IPocketUpgrade getPocketUpgrade( @Nonnull ItemStack stack )
} }
public static Iterable<IPocketUpgrade> getVanillaPocketUpgrades() { public static Iterable<IPocketUpgrade> getVanillaPocketUpgrades() {
List<IPocketUpgrade> upgrades = new ArrayList<IPocketUpgrade>(); List<IPocketUpgrade> upgrades = new ArrayList<>();
for(IPocketUpgrade upgrade : pocketUpgrades.values()) { for(IPocketUpgrade upgrade : pocketUpgrades.values()) {
if(upgrade instanceof PocketModem || upgrade instanceof PocketSpeaker) { if(upgrade instanceof PocketModem || upgrade instanceof PocketSpeaker) {
upgrades.add( upgrade ); upgrades.add( upgrade );
@ -790,7 +790,7 @@ public static IWritableMount createSaveDirMount( World world, String subPath, lo
public static IMount createResourceMount( Class<?> modClass, String domain, String subPath ) public static IMount createResourceMount( Class<?> modClass, String domain, String subPath )
{ {
// Start building list of mounts // Start building list of mounts
List<IMount> mounts = new ArrayList<IMount>(); List<IMount> mounts = new ArrayList<>();
subPath = "assets/" + domain + "/" + subPath; subPath = "assets/" + domain + "/" + subPath;
// Mount from debug dir // Mount from debug dir

View File

@ -16,6 +16,7 @@
* @see ILuaContext#executeMainThreadTask(ILuaTask) * @see ILuaContext#executeMainThreadTask(ILuaTask)
* @see ILuaContext#issueMainThreadTask(ILuaTask) * @see ILuaContext#issueMainThreadTask(ILuaTask)
*/ */
@FunctionalInterface
public interface ILuaTask public interface ILuaTask
{ {
/** /**

View File

@ -16,6 +16,7 @@
* *
* @see dan200.computercraft.api.ComputerCraftAPI#registerMediaProvider(IMediaProvider) * @see dan200.computercraft.api.ComputerCraftAPI#registerMediaProvider(IMediaProvider)
*/ */
@FunctionalInterface
public interface IMediaProvider public interface IMediaProvider
{ {
/** /**

View File

@ -91,7 +91,9 @@ public interface IPeripheral
* computers can be attached to a peripheral at once. * computers can be attached to a peripheral at once.
* @see #detach * @see #detach
*/ */
void attach( @Nonnull IComputerAccess computer ); default void attach( @Nonnull IComputerAccess computer )
{
}
/** /**
* Is called when a computer is detaching from the peripheral. * Is called when a computer is detaching from the peripheral.
@ -108,7 +110,9 @@ public interface IPeripheral
* computers can be attached to a peripheral at once. * computers can be attached to a peripheral at once.
* @see #detach * @see #detach
*/ */
void detach( @Nonnull IComputerAccess computer ); default void detach( @Nonnull IComputerAccess computer )
{
}
/** /**
* Determine whether this peripheral is equivalent to another one. * Determine whether this peripheral is equivalent to another one.

View File

@ -18,6 +18,7 @@
* *
* @see dan200.computercraft.api.ComputerCraftAPI#registerPeripheralProvider(IPeripheralProvider) * @see dan200.computercraft.api.ComputerCraftAPI#registerPeripheralProvider(IPeripheralProvider)
*/ */
@FunctionalInterface
public interface IPeripheralProvider public interface IPeripheralProvider
{ {
/** /**

View File

@ -74,7 +74,9 @@ public interface IPocketUpgrade
* @param peripheral The peripheral for this upgrade. * @param peripheral The peripheral for this upgrade.
* @see #createPeripheral(IPocketAccess) * @see #createPeripheral(IPocketAccess)
*/ */
void update( @Nonnull IPocketAccess access, @Nullable IPeripheral peripheral ); default void update( @Nonnull IPocketAccess access, @Nullable IPeripheral peripheral )
{
}
/** /**
* Called when the pocket computer is right clicked. * Called when the pocket computer is right clicked.
@ -87,5 +89,8 @@ public interface IPocketUpgrade
* access the GUI. * access the GUI.
* @see #createPeripheral(IPocketAccess) * @see #createPeripheral(IPocketAccess)
*/ */
boolean onRightClick( @Nonnull World world, @Nonnull IPocketAccess access, @Nullable IPeripheral peripheral ); default boolean onRightClick( @Nonnull World world, @Nonnull IPocketAccess access, @Nullable IPeripheral peripheral )
{
return false;
}
} }

View File

@ -17,6 +17,7 @@
* *
* @see dan200.computercraft.api.ComputerCraftAPI#registerBundledRedstoneProvider(IBundledRedstoneProvider) * @see dan200.computercraft.api.ComputerCraftAPI#registerBundledRedstoneProvider(IBundledRedstoneProvider)
*/ */
@FunctionalInterface
public interface IBundledRedstoneProvider public interface IBundledRedstoneProvider
{ {
/** /**

View File

@ -15,6 +15,7 @@
* *
* @see ITurtleAccess#executeCommand(ILuaContext, ITurtleCommand) * @see ITurtleAccess#executeCommand(ILuaContext, ITurtleCommand)
*/ */
@FunctionalInterface
public interface ITurtleCommand public interface ITurtleCommand
{ {
/** /**

View File

@ -136,5 +136,7 @@ public interface ITurtleUpgrade
* @param turtle Access to the turtle that the upgrade resides on. * @param turtle Access to the turtle that the upgrade resides on.
* @param side Which side of the turtle (left or right) the upgrade resides on. * @param side Which side of the turtle (left or right) the upgrade resides on.
*/ */
void update( @Nonnull ITurtleAccess turtle, @Nonnull TurtleSide side ); default void update( @Nonnull ITurtleAccess turtle, @Nonnull TurtleSide side )
{
}
} }

View File

@ -11,7 +11,6 @@
import dan200.computercraft.shared.computer.blocks.TileComputer; import dan200.computercraft.shared.computer.blocks.TileComputer;
import dan200.computercraft.shared.computer.core.ComputerFamily; import dan200.computercraft.shared.computer.core.ComputerFamily;
import dan200.computercraft.shared.computer.core.IComputer; import dan200.computercraft.shared.computer.core.IComputer;
import dan200.computercraft.shared.computer.core.IComputerContainer;
import dan200.computercraft.shared.computer.inventory.ContainerComputer; import dan200.computercraft.shared.computer.inventory.ContainerComputer;
import net.minecraft.client.gui.inventory.GuiContainer; import net.minecraft.client.gui.inventory.GuiContainer;
import net.minecraft.client.renderer.GlStateManager; import net.minecraft.client.renderer.GlStateManager;
@ -61,14 +60,7 @@ public void initGui()
super.initGui(); super.initGui();
Keyboard.enableRepeatEvents( true ); Keyboard.enableRepeatEvents( true );
m_terminal = new WidgetTerminal( 0, 0, m_termWidth, m_termHeight, new IComputerContainer() m_terminal = new WidgetTerminal( 0, 0, m_termWidth, m_termHeight, () -> m_computer, 2, 2, 2, 2 );
{
@Override
public IComputer getComputer()
{
return m_computer;
}
}, 2, 2, 2, 2 );
m_terminal.setAllowFocusLoss( false ); m_terminal.setAllowFocusLoss( false );
xSize = m_terminal.getWidth() + 24; xSize = m_terminal.getWidth() + 24;
ySize = m_terminal.getHeight() + 24; ySize = m_terminal.getHeight() + 24;

View File

@ -23,7 +23,7 @@ public GuiConfigCC( GuiScreen parentScreen )
private static List<IConfigElement> getConfigElements() private static List<IConfigElement> getConfigElements()
{ {
ArrayList<IConfigElement> elements = new ArrayList<IConfigElement>(); ArrayList<IConfigElement> elements = new ArrayList<>();
for (Property property : ComputerCraft.Config.config.getCategory( Configuration.CATEGORY_GENERAL ).getOrderedValues()) for (Property property : ComputerCraft.Config.config.getCategory( Configuration.CATEGORY_GENERAL ).getOrderedValues())
{ {
elements.add( new ConfigElement( property ) ); elements.add( new ConfigElement( property ) );

View File

@ -11,7 +11,6 @@
import dan200.computercraft.client.gui.widgets.WidgetTerminal; import dan200.computercraft.client.gui.widgets.WidgetTerminal;
import dan200.computercraft.shared.computer.core.ComputerFamily; import dan200.computercraft.shared.computer.core.ComputerFamily;
import dan200.computercraft.shared.computer.core.IComputer; import dan200.computercraft.shared.computer.core.IComputer;
import dan200.computercraft.shared.computer.core.IComputerContainer;
import dan200.computercraft.shared.turtle.blocks.TileTurtle; import dan200.computercraft.shared.turtle.blocks.TileTurtle;
import dan200.computercraft.shared.turtle.inventory.ContainerTurtle; import dan200.computercraft.shared.turtle.inventory.ContainerTurtle;
import net.minecraft.client.Minecraft; import net.minecraft.client.Minecraft;
@ -67,14 +66,7 @@ public void initGui()
( height - ySize ) / 2 + 8, ( height - ySize ) / 2 + 8,
ComputerCraft.terminalWidth_turtle, ComputerCraft.terminalWidth_turtle,
ComputerCraft.terminalHeight_turtle, ComputerCraft.terminalHeight_turtle,
new IComputerContainer() () -> m_computer,
{
@Override
public IComputer getComputer()
{
return m_computer;
}
},
2, 2, 2, 2 2, 2, 2, 2
); );
m_terminalGui.setAllowFocusLoss( false ); m_terminalGui.setAllowFocusLoss( false );

View File

@ -21,7 +21,7 @@ public class WidgetContainer extends Widget
public WidgetContainer( int x, int y, int w, int h ) public WidgetContainer( int x, int y, int w, int h )
{ {
super( x, y, w, h ); super( x, y, w, h );
m_widgets = new ArrayList<Widget>(); m_widgets = new ArrayList<>();
m_modalWidget = null; m_modalWidget = null;
} }
@ -203,6 +203,7 @@ public boolean suppressItemTooltips( Minecraft mc, int xOrigin, int yOrigin, int
return false; return false;
} }
@Override
public boolean suppressKeyPress( char c, int k ) public boolean suppressKeyPress( char c, int k )
{ {
if( m_modalWidget == null ) if( m_modalWidget == null )

View File

@ -76,7 +76,7 @@ public WidgetTerminal( int x, int y, int termWidth, int termHeight, IComputerCon
m_topMargin = topMargin; m_topMargin = topMargin;
m_bottomMargin = bottomMargin; m_bottomMargin = bottomMargin;
m_keysDown = new ArrayList<Integer>(); m_keysDown = new ArrayList<>();
} }
public void setAllowFocusLoss( boolean allowFocusLoss ) public void setAllowFocusLoss( boolean allowFocusLoss )

View File

@ -6,7 +6,6 @@
package dan200.computercraft.client.proxy; package dan200.computercraft.client.proxy;
import com.google.common.base.Function;
import dan200.computercraft.ComputerCraft; import dan200.computercraft.ComputerCraft;
import dan200.computercraft.client.render.TileEntityTurtleRenderer; import dan200.computercraft.client.render.TileEntityTurtleRenderer;
import dan200.computercraft.client.render.TurtleSmartItemModel; import dan200.computercraft.client.render.TurtleSmartItemModel;
@ -21,7 +20,6 @@
import net.minecraft.client.renderer.block.model.ModelBakery; import net.minecraft.client.renderer.block.model.ModelBakery;
import net.minecraft.client.renderer.block.model.ModelResourceLocation; import net.minecraft.client.renderer.block.model.ModelResourceLocation;
import net.minecraft.client.renderer.color.IItemColor; import net.minecraft.client.renderer.color.IItemColor;
import net.minecraft.client.renderer.texture.TextureAtlasSprite;
import net.minecraft.client.renderer.vertex.DefaultVertexFormats; import net.minecraft.client.renderer.vertex.DefaultVertexFormats;
import net.minecraft.client.resources.IResourceManager; import net.minecraft.client.resources.IResourceManager;
import net.minecraft.client.resources.SimpleReloadableResourceManager; import net.minecraft.client.resources.SimpleReloadableResourceManager;
@ -173,14 +171,7 @@ private void loadModel( ModelBakeEvent event, String name )
IBakedModel bakedModel = model.bake( IBakedModel bakedModel = model.bake(
model.getDefaultState(), model.getDefaultState(),
DefaultVertexFormats.ITEM, DefaultVertexFormats.ITEM,
new Function<ResourceLocation, TextureAtlasSprite>() location -> Minecraft.getMinecraft().getTextureMapBlocks().getAtlasSprite( location.toString() )
{
@Override
public TextureAtlasSprite apply( ResourceLocation location )
{
return Minecraft.getMinecraft().getTextureMapBlocks().getAtlasSprite( location.toString() );
}
}
); );
event.getModelRegistry().putObject( event.getModelRegistry().putObject(
new ModelResourceLocation( "computercraft:" + name, "inventory" ), new ModelResourceLocation( "computercraft:" + name, "inventory" ),

View File

@ -198,10 +198,7 @@ public void init()
mc.getItemColors().registerItemColorHandler( new DiskColorHandler( ComputerCraft.Items.disk ), ComputerCraft.Items.disk ); mc.getItemColors().registerItemColorHandler( new DiskColorHandler( ComputerCraft.Items.disk ), ComputerCraft.Items.disk );
mc.getItemColors().registerItemColorHandler( new DiskColorHandler( ComputerCraft.Items.diskExpanded ), ComputerCraft.Items.diskExpanded ); mc.getItemColors().registerItemColorHandler( new DiskColorHandler( ComputerCraft.Items.diskExpanded ), ComputerCraft.Items.diskExpanded );
mc.getItemColors().registerItemColorHandler( new IItemColor() mc.getItemColors().registerItemColorHandler( ( stack, layer ) ->
{
@Override
public int getColorFromItemstack( @Nonnull ItemStack stack, int layer )
{ {
switch( layer ) switch( layer )
{ {
@ -221,7 +218,6 @@ public int getColorFromItemstack( @Nonnull ItemStack stack, int layer )
return colour == -1 ? Colour.Black.getHex() : colour; return colour == -1 ? Colour.Black.getHex() : colour;
} }
} }
}
}, ComputerCraft.Items.pocketComputer ); }, ComputerCraft.Items.pocketComputer );
// Setup renderers // Setup renderers
@ -309,7 +305,7 @@ public Object getFixedWidthFontRenderer()
@Override @Override
public String getRecordInfo( @Nonnull ItemStack recordStack ) public String getRecordInfo( @Nonnull ItemStack recordStack )
{ {
List<String> info = new ArrayList<String>( 1 ); List<String> info = new ArrayList<>( 1 );
recordStack.getItem().addInformation( recordStack, null, info, ITooltipFlag.TooltipFlags.NORMAL ); recordStack.getItem().addInformation( recordStack, null, info, ITooltipFlag.TooltipFlags.NORMAL );
if( info.size() > 0 ) { if( info.size() > 0 ) {
return info.get( 0 ); return info.get( 0 );
@ -399,14 +395,7 @@ public void handlePacket( final ComputerCraftPacket packet, final EntityPlayer p
} }
else else
{ {
listener.addScheduledTask( new Runnable() listener.addScheduledTask( () -> processPacket( packet, player ) );
{
@Override
public void run()
{
processPacket( packet, player );
}
} );
} }
} }
break; break;

View File

@ -39,7 +39,7 @@ public TurtleMultiModel( IBakedModel baseModel, IBakedModel overlayModel, IBaked
m_rightUpgradeModel = rightUpgradeModel; m_rightUpgradeModel = rightUpgradeModel;
m_rightUpgradeTransform = rightUpgradeTransform; m_rightUpgradeTransform = rightUpgradeTransform;
m_generalQuads = null; m_generalQuads = null;
m_faceQuads = new HashMap<EnumFacing, List<BakedQuad>>(); m_faceQuads = new HashMap<>();
} }
@Nonnull @Nonnull
@ -50,7 +50,7 @@ public List<BakedQuad> getQuads( IBlockState state, EnumFacing side, long rand )
{ {
if( !m_faceQuads.containsKey( side ) ) if( !m_faceQuads.containsKey( side ) )
{ {
ArrayList<BakedQuad> quads = new ArrayList<BakedQuad>(); ArrayList<BakedQuad> quads = new ArrayList<>();
if( m_overlayModel != null ) if( m_overlayModel != null )
{ {
quads.addAll( m_overlayModel.getQuads( state, side, rand ) ); quads.addAll( m_overlayModel.getQuads( state, side, rand ) );
@ -72,7 +72,7 @@ public List<BakedQuad> getQuads( IBlockState state, EnumFacing side, long rand )
{ {
if( m_generalQuads == null ) if( m_generalQuads == null )
{ {
ArrayList<BakedQuad> quads = new ArrayList<BakedQuad>(); ArrayList<BakedQuad> quads = new ArrayList<>();
quads.addAll( m_baseModel.getQuads( state, side, rand ) ); quads.addAll( m_baseModel.getQuads( state, side, rand ) );
if( m_overlayModel != null ) if( m_overlayModel != null )
{ {
@ -141,7 +141,7 @@ private List<BakedQuad> transformQuads( List<BakedQuad> input, Matrix4f transfor
} }
else else
{ {
List<BakedQuad> output = new ArrayList<BakedQuad>( input.size() ); List<BakedQuad> output = new ArrayList<>( input.size() );
for( BakedQuad quad : input ) for( BakedQuad quad : input )
{ {
output.add( transformQuad( quad, transform ) ); output.add( transformQuad( quad, transform ) );

View File

@ -96,9 +96,9 @@ public int hashCode()
public TurtleSmartItemModel() public TurtleSmartItemModel()
{ {
m_cachedModels = new HashMap<TurtleModelCombination, IBakedModel>(); m_cachedModels = new HashMap<>();
m_defaultCombination = new TurtleModelCombination( ComputerFamily.Normal, false, null, null, null, false ); m_defaultCombination = new TurtleModelCombination( ComputerFamily.Normal, false, null, null, null, false );
m_overrides = new ItemOverrideList( new ArrayList<ItemOverride>() ) m_overrides = new ItemOverrideList( new ArrayList<>() )
{ {
@Nonnull @Nonnull
@Override @Override

View File

@ -94,7 +94,7 @@ public Object[] callMethod( @Nonnull ILuaContext context, int method, @Nonnull O
String path = getString( args, 0 ); String path = getString( args, 0 );
try { try {
String[] results = m_fileSystem.list( path ); String[] results = m_fileSystem.list( path );
Map<Object,Object> table = new HashMap<Object,Object>(); Map<Object,Object> table = new HashMap<>();
for(int i=0; i<results.length; ++i ) { for(int i=0; i<results.length; ++i ) {
table.put( i+1, results[i] ); table.put( i+1, results[i] );
} }
@ -213,39 +213,46 @@ public Object[] callMethod( @Nonnull ILuaContext context, int method, @Nonnull O
String path = getString( args, 0 ); String path = getString( args, 0 );
String mode = getString( args, 1 ); String mode = getString( args, 1 );
try { try {
if( mode.equals( "r" ) ) { switch( mode )
{
case "r":
{
// Open the file for reading, then create a wrapper around the reader // Open the file for reading, then create a wrapper around the reader
InputStream reader = m_fileSystem.openForRead( path ); InputStream reader = m_fileSystem.openForRead( path );
return new Object[] { new EncodedInputHandle( reader ) }; return new Object[] { new EncodedInputHandle( reader ) };
}
} else if( mode.equals( "w" ) ) { case "w":
{
// Open the file for writing, then create a wrapper around the writer // Open the file for writing, then create a wrapper around the writer
OutputStream writer = m_fileSystem.openForWrite( path, false ); OutputStream writer = m_fileSystem.openForWrite( path, false );
return new Object[] { new EncodedOutputHandle( writer ) }; return new Object[] { new EncodedOutputHandle( writer ) };
}
} else if( mode.equals( "a" ) ) { case "a":
{
// Open the file for appending, then create a wrapper around the writer // Open the file for appending, then create a wrapper around the writer
OutputStream writer = m_fileSystem.openForWrite( path, true ); OutputStream writer = m_fileSystem.openForWrite( path, true );
return new Object[] { new EncodedOutputHandle( writer ) }; return new Object[] { new EncodedOutputHandle( writer ) };
}
} else if( mode.equals( "rb" ) ) { case "rb":
{
// Open the file for binary reading, then create a wrapper around the reader // Open the file for binary reading, then create a wrapper around the reader
InputStream reader = m_fileSystem.openForRead( path ); InputStream reader = m_fileSystem.openForRead( path );
return new Object[] { new BinaryInputHandle( reader ) }; return new Object[] { new BinaryInputHandle( reader ) };
}
} else if( mode.equals( "wb" ) ) { case "wb":
{
// Open the file for binary writing, then create a wrapper around the writer // Open the file for binary writing, then create a wrapper around the writer
OutputStream writer = m_fileSystem.openForWrite( path, false ); OutputStream writer = m_fileSystem.openForWrite( path, false );
return new Object[] { new BinaryOutputHandle( writer ) }; return new Object[] { new BinaryOutputHandle( writer ) };
}
} else if( mode.equals( "ab" ) ) { case "ab":
{
// Open the file for binary appending, then create a wrapper around the reader // Open the file for binary appending, then create a wrapper around the reader
OutputStream writer = m_fileSystem.openForWrite( path, true ); OutputStream writer = m_fileSystem.openForWrite( path, true );
return new Object[] { new BinaryOutputHandle( writer ) }; return new Object[] { new BinaryOutputHandle( writer ) };
}
} else { default:
throw new LuaException( "Unsupported mode" ); throw new LuaException( "Unsupported mode" );
} }
} catch( FileSystemException e ) { } catch( FileSystemException e ) {
return new Object[] { null, e.getMessage() }; return new Object[] { null, e.getMessage() };
@ -286,7 +293,7 @@ public Object[] callMethod( @Nonnull ILuaContext context, int method, @Nonnull O
String path = getString( args, 0 ); String path = getString( args, 0 );
try { try {
String[] results = m_fileSystem.find( path ); String[] results = m_fileSystem.find( path );
Map<Object,Object> table = new HashMap<Object,Object>(); Map<Object,Object> table = new HashMap<>();
for(int i=0; i<results.length; ++i ) { for(int i=0; i<results.length; ++i ) {
table.put( i+1, results[i] ); table.put( i+1, results[i] );
} }

View File

@ -26,7 +26,7 @@ public class HTTPAPI implements ILuaAPI
public HTTPAPI( IAPIEnvironment environment ) public HTTPAPI( IAPIEnvironment environment )
{ {
m_apiEnvironment = environment; m_apiEnvironment = environment;
m_httpTasks = new ArrayList<HTTPTask>(); m_httpTasks = new ArrayList<>();
} }
@Override @Override
@ -103,7 +103,7 @@ public Object[] callMethod( @Nonnull ILuaContext context, int method, @Nonnull O
Map<Object, Object> table = optTable( args, 2, null ); Map<Object, Object> table = optTable( args, 2, null );
if( table != null ) if( table != null )
{ {
headers = new HashMap<String, String>( table.size() ); headers = new HashMap<>( table.size() );
for( Object key : table.keySet() ) for( Object key : table.keySet() )
{ {
Object value = table.get( key ); Object value = table.get( key );

View File

@ -0,0 +1,245 @@
/*
* This file is part of ComputerCraft - http://www.computercraft.info
* Copyright Daniel Ratcliffe, 2011-2017. Do not distribute without permission.
* Send enquiries to dratcliffe@gmail.com
*/
package dan200.computercraft.core.apis;
import com.google.common.base.Joiner;
import com.google.common.io.ByteStreams;
import dan200.computercraft.ComputerCraft;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class HTTPRequest
{
public static URL checkURL( String urlString ) throws HTTPRequestException
{
URL url;
try
{
url = new URL( urlString );
}
catch( MalformedURLException e )
{
throw new HTTPRequestException( "URL malformed" );
}
// Validate the URL
String protocol = url.getProtocol().toLowerCase();
if( !protocol.equals("http") && !protocol.equals("https") )
{
throw new HTTPRequestException( "URL not http" );
}
// Compare the URL to the whitelist
if( !ComputerCraft.http_whitelist.matches( url.getHost() ) || ComputerCraft.http_blacklist.matches( url.getHost() ) )
{
throw new HTTPRequestException( "Domain not permitted" );
}
return url;
}
public HTTPRequest( String url, final String postText, final Map<String, String> headers, boolean binary ) throws HTTPRequestException
{
// Parse the URL
m_urlString = url;
m_url = checkURL( m_urlString );
m_binary = binary;
// Start the thread
m_cancelled = false;
m_complete = false;
m_success = false;
m_result = null;
m_responseCode = -1;
Thread thread = new Thread( () ->
{
try
{
// Connect to the URL
HttpURLConnection connection = (HttpURLConnection)m_url.openConnection();
if( postText != null )
{
connection.setRequestMethod( "POST" );
connection.setDoOutput( true );
}
else
{
connection.setRequestMethod( "GET" );
}
// Set headers
connection.setRequestProperty( "accept-charset", "UTF-8" );
if( postText != null )
{
connection.setRequestProperty( "content-type", "application/x-www-form-urlencoded; charset=utf-8" );
connection.setRequestProperty( "content-encoding", "UTF-8" );
}
if( headers != null )
{
for( Map.Entry<String, String> header : headers.entrySet() )
{
connection.setRequestProperty( header.getKey(), header.getValue() );
}
}
// Send POST text
if( postText != null )
{
OutputStream os = connection.getOutputStream();
OutputStreamWriter osw;
try
{
osw = new OutputStreamWriter( os, "UTF-8" );
}
catch( UnsupportedEncodingException e )
{
osw = new OutputStreamWriter( os );
}
BufferedWriter writer = new BufferedWriter( osw );
writer.write( postText, 0, postText.length() );
writer.close();
}
// Read response
InputStream is;
int code = connection.getResponseCode();
boolean responseSuccess;
if (code >= 200 && code < 400) {
is = connection.getInputStream();
responseSuccess = true;
} else {
is = connection.getErrorStream();
responseSuccess = false;
}
byte[] result = ByteStreams.toByteArray( is );
is.close();
synchronized( m_lock )
{
if( m_cancelled )
{
// We cancelled
m_complete = true;
m_success = false;
m_result = null;
}
else
{
// We completed
m_complete = true;
m_success = responseSuccess;
m_result = result;
m_responseCode = connection.getResponseCode();
m_encoding = connection.getContentEncoding();
Joiner joiner = Joiner.on( ',' );
Map<String, String> headers1 = m_responseHeaders = new HashMap<>();
for (Map.Entry<String, List<String>> header : connection.getHeaderFields().entrySet()) {
headers1.put(header.getKey(), joiner.join( header.getValue() ));
}
}
}
connection.disconnect(); // disconnect
}
catch( IOException e )
{
synchronized( m_lock )
{
// There was an error
m_complete = true;
m_success = false;
m_result = null;
}
}
} );
thread.setDaemon(true);
thread.start();
}
public String getURL() {
return m_urlString;
}
public void cancel()
{
synchronized(m_lock) {
m_cancelled = true;
}
}
public boolean isComplete()
{
synchronized(m_lock) {
return m_complete;
}
}
public int getResponseCode() {
synchronized(m_lock) {
return m_responseCode;
}
}
public Map<String, String> getResponseHeaders() {
synchronized (m_lock) {
return m_responseHeaders;
}
}
public boolean wasSuccessful()
{
synchronized(m_lock) {
return m_success;
}
}
public boolean isBinary()
{
return m_binary;
}
public InputStream getContents()
{
byte[] result;
synchronized(m_lock) {
result = m_result;
}
if( result != null ) {
return new ByteArrayInputStream( result );
}
return null;
}
public String getEncoding() {
return m_encoding;
}
private final Object m_lock = new Object();
private final URL m_url;
private final String m_urlString;
private boolean m_complete;
private boolean m_cancelled;
private boolean m_success;
private String m_encoding;
private byte[] m_result;
private boolean m_binary;
private int m_responseCode;
private Map<String, String> m_responseHeaders;
}

View File

@ -69,8 +69,8 @@ public OSAPI( IAPIEnvironment environment )
m_apiEnvironment = environment; m_apiEnvironment = environment;
m_nextTimerToken = 0; m_nextTimerToken = 0;
m_nextAlarmToken = 0; m_nextAlarmToken = 0;
m_timers = new HashMap<Integer, Timer>(); m_timers = new HashMap<>();
m_alarms = new HashMap<Integer, Alarm>(); m_alarms = new HashMap<>();
} }
// ILuaAPI implementation // ILuaAPI implementation
@ -303,24 +303,27 @@ public Object[] callMethod( @Nonnull ILuaContext context, int method, @Nonnull O
{ {
// time // time
String param = optString( args, 0, "ingame" ); String param = optString( args, 0, "ingame" );
switch( param )
if (param.equals("utc")) { {
case "utc":
{
// Get Hour of day (UTC) // Get Hour of day (UTC)
Calendar c = Calendar.getInstance( TimeZone.getTimeZone( "UTC" ) ); Calendar c = Calendar.getInstance( TimeZone.getTimeZone( "UTC" ) );
return new Object[] { getTimeForCalendar( c ) }; return new Object[] { getTimeForCalendar( c ) };
}
} else if (param.equals("local")) { case "local":
{
// Get Hour of day (local time) // Get Hour of day (local time)
Calendar c = Calendar.getInstance(); Calendar c = Calendar.getInstance();
return new Object[] { getTimeForCalendar( c ) }; return new Object[] { getTimeForCalendar( c ) };
}
} else if (param.equals("ingame")) { case "ingame":
// Get ingame hour // Get ingame hour
synchronized (m_alarms) { synchronized( m_alarms )
{
return new Object[] { m_time }; return new Object[] { m_time };
} }
default:
} else {
throw new LuaException( "Unsupported operation" ); throw new LuaException( "Unsupported operation" );
} }
} }
@ -328,23 +331,27 @@ public Object[] callMethod( @Nonnull ILuaContext context, int method, @Nonnull O
{ {
// day // day
String param = optString( args, 0, "ingame" ); String param = optString( args, 0, "ingame" );
if (param.equals("utc")) { switch( param )
{
case "utc":
{
// Get numbers of days since 1970-01-01 (utc) // Get numbers of days since 1970-01-01 (utc)
Calendar c = Calendar.getInstance( TimeZone.getTimeZone( "UTC" ) ); Calendar c = Calendar.getInstance( TimeZone.getTimeZone( "UTC" ) );
return new Object[] { getDayForCalendar( c ) }; return new Object[] { getDayForCalendar( c ) };
}
} else if (param.equals("local")) { case "local":
{
// Get numbers of days since 1970-01-01 (local time) // Get numbers of days since 1970-01-01 (local time)
Calendar c = Calendar.getInstance(); Calendar c = Calendar.getInstance();
return new Object[] { getDayForCalendar( c ) }; return new Object[] { getDayForCalendar( c ) };
}
} else if (param.equals("ingame")){ case "ingame":
// Get game day // Get game day
synchronized (m_alarms) { synchronized( m_alarms )
{
return new Object[] { m_day }; return new Object[] { m_day };
} }
default:
} else {
throw new LuaException( "Unsupported operation" ); throw new LuaException( "Unsupported operation" );
} }
} }
@ -378,25 +385,29 @@ public Object[] callMethod( @Nonnull ILuaContext context, int method, @Nonnull O
{ {
// epoch // epoch
String param = optString( args, 0, "ingame" ); String param = optString( args, 0, "ingame" );
if (param.equals("utc")) { switch( param )
{
case "utc":
{
// Get utc epoch // Get utc epoch
Calendar c = Calendar.getInstance( TimeZone.getTimeZone( "UTC" ) ); Calendar c = Calendar.getInstance( TimeZone.getTimeZone( "UTC" ) );
return new Object[] { getEpochForCalendar( c ) }; return new Object[] { getEpochForCalendar( c ) };
}
} else if (param.equals("local")) { case "local":
{
// Get local epoch // Get local epoch
Calendar c = Calendar.getInstance(); Calendar c = Calendar.getInstance();
return new Object[] { getEpochForCalendar( c ) }; return new Object[] { getEpochForCalendar( c ) };
}
} else if (param.equals("ingame")){ case "ingame":
// Get in-game epoch // Get in-game epoch
synchronized (m_alarms) { synchronized( m_alarms )
{
return new Object[] { return new Object[] {
m_day * 86400000 + (int) (m_time * 3600000.0f) m_day * 86400000 + (int) (m_time * 3600000.0f)
}; };
} }
default:
} else {
throw new LuaException( "Unsupported operation" ); throw new LuaException( "Unsupported operation" );
} }
} }

View File

@ -48,14 +48,14 @@ public PeripheralWrapper( IPeripheral peripheral, String side )
assert( m_type != null ); assert( m_type != null );
assert( m_methods != null ); assert( m_methods != null );
m_methodMap = new HashMap<String, Integer>(); m_methodMap = new HashMap<>();
for(int i=0; i<m_methods.length; ++i ) { for(int i=0; i<m_methods.length; ++i ) {
if( m_methods[i] != null ) { if( m_methods[i] != null ) {
m_methodMap.put( m_methods[i], i ); m_methodMap.put( m_methods[i], i );
} }
} }
m_mounts = new HashSet<String>(); m_mounts = new HashSet<>();
} }
public IPeripheral getPeripheral() public IPeripheral getPeripheral()
@ -451,7 +451,7 @@ public Object[] callMethod( @Nonnull ILuaContext context, int method, @Nonnull O
} }
if( methods != null ) if( methods != null )
{ {
Map<Object,Object> table = new HashMap<Object,Object>(); Map<Object,Object> table = new HashMap<>();
for(int i=0; i<methods.length; ++i ) { for(int i=0; i<methods.length; ++i ) {
table.put( i+1, methods[i] ); table.put( i+1, methods[i] );
} }

View File

@ -78,7 +78,7 @@ public Object[] callMethod( @Nonnull ILuaContext context, int method, @Nonnull O
case 0: case 0:
{ {
// getSides // getSides
Map<Object,Object> table = new HashMap<Object,Object>(); Map<Object,Object> table = new HashMap<>();
for(int i=0; i< Computer.s_sideNames.length; ++i ) for(int i=0; i< Computer.s_sideNames.length; ++i )
{ {
table.put( i+1, Computer.s_sideNames[i] ); table.put( i+1, Computer.s_sideNames[i] );

View File

@ -224,7 +224,7 @@ public Computer( IComputerEnvironment environment, Terminal terminal, int id )
m_fileSystem = null; m_fileSystem = null;
m_machine = null; m_machine = null;
m_apis = new ArrayList<ILuaAPI>(); m_apis = new ArrayList<>();
m_apiEnvironment = new APIEnvironment( this ); m_apiEnvironment = new APIEnvironment( this );
m_internalOutput = new int[6]; m_internalOutput = new int[6];

View File

@ -31,9 +31,9 @@ public class ComputerThread
{ {
m_lock = new Object(); m_lock = new Object();
m_thread = null; m_thread = null;
m_computerTasks = new WeakHashMap<Object, LinkedBlockingQueue<ITask>>(); m_computerTasks = new WeakHashMap<>();
m_computerTasksPending = new ArrayList<LinkedBlockingQueue<ITask>>(); m_computerTasksPending = new ArrayList<>();
m_computerTasksActive = new ArrayList<LinkedBlockingQueue<ITask>>(); m_computerTasksActive = new ArrayList<>();
m_defaultQueue = new Object(); m_defaultQueue = new Object();
m_monitor = new Object(); m_monitor = new Object();
m_running = false; m_running = false;
@ -50,8 +50,7 @@ public static void start()
return; return;
} }
m_thread = new Thread( new Runnable() { m_thread = new Thread( () ->
public void run()
{ {
while( true ) while( true )
{ {
@ -103,14 +102,13 @@ public void run()
final ITask task = queue.take(); final ITask task = queue.take();
// Create the task // Create the task
Thread worker = new Thread( new Runnable() { Thread worker = new Thread( () ->
public void run() { {
try { try {
task.execute(); task.execute();
} catch( Throwable e ) { } catch( Throwable e ) {
ComputerCraft.log.error( "Error running task", e ); ComputerCraft.log.error( "Error running task", e );
} }
}
} ); } );
// Run the task // Run the task
@ -173,7 +171,6 @@ public void run() {
} }
} }
} }
}
}, "Computer Dispatch Thread" ); }, "Computer Dispatch Thread" );
m_thread.setDaemon(true); m_thread.setDaemon(true);
@ -207,7 +204,7 @@ public static void queueTask( ITask _task, Computer computer )
if (queue == null) if (queue == null)
{ {
m_computerTasks.put(queueObject, queue = new LinkedBlockingQueue<ITask>(256)); m_computerTasks.put(queueObject, queue = new LinkedBlockingQueue<>( 256 ));
} }
synchronized ( m_computerTasksPending ) synchronized ( m_computerTasksPending )

View File

@ -13,7 +13,7 @@ public class MainThread
private static final int MAX_TASKS_PER_TICK = 1000; private static final int MAX_TASKS_PER_TICK = 1000;
private static final int MAX_TASKS_TOTAL = 50000; private static final int MAX_TASKS_TOTAL = 50000;
private static final LinkedList<ITask> m_outstandingTasks = new LinkedList<ITask>(); private static final LinkedList<ITask> m_outstandingTasks = new LinkedList<>();
private static final Object m_nextUnusedTaskIDLock = new Object(); private static final Object m_nextUnusedTaskIDLock = new Object();
private static long m_nextUnusedTaskID = 0; private static long m_nextUnusedTaskID = 0;

View File

@ -68,7 +68,7 @@ public void list( @Nonnull String path, @Nonnull List<String> contents ) throws
{ {
if( foundFiles == null ) if( foundFiles == null )
{ {
foundFiles = new ArrayList<String>(); foundFiles = new ArrayList<>();
} }
part.list( path, foundFiles ); part.list( path, foundFiles );
foundDirs++; foundDirs++;
@ -83,7 +83,7 @@ public void list( @Nonnull String path, @Nonnull List<String> contents ) throws
else if( foundDirs > 1 ) else if( foundDirs > 1 )
{ {
// We found multiple directories, so filter for duplicates // We found multiple directories, so filter for duplicates
Set<String> seen = new HashSet<String>(); Set<String> seen = new HashSet<>();
for(String file : foundFiles) for(String file : foundFiles)
{ {
if( seen.add( file ) ) if( seen.add( file ) )

View File

@ -9,7 +9,6 @@
import dan200.computercraft.ComputerCraft; import dan200.computercraft.ComputerCraft;
import dan200.computercraft.api.filesystem.IMount; import dan200.computercraft.api.filesystem.IMount;
import dan200.computercraft.api.filesystem.IWritableMount; import dan200.computercraft.api.filesystem.IWritableMount;
import net.minecraftforge.fml.common.FMLLog;
import java.io.*; import java.io.*;
import java.util.*; import java.util.*;
@ -291,7 +290,7 @@ private String toLocal( String path )
} }
} }
private final Map<String, MountWrapper> m_mounts = new HashMap<String, MountWrapper>(); private final Map<String, MountWrapper> m_mounts = new HashMap<>();
private final Set<Closeable> m_openFiles = Collections.newSetFromMap( new WeakHashMap<Closeable, Boolean>() ); private final Set<Closeable> m_openFiles = Collections.newSetFromMap( new WeakHashMap<Closeable, Boolean>() );
public FileSystem( String rootLabel, IMount rootMount ) throws FileSystemException public FileSystem( String rootLabel, IMount rootMount ) throws FileSystemException
@ -424,7 +423,7 @@ public synchronized String[] list( String path ) throws FileSystemException
MountWrapper mount = getMount( path ); MountWrapper mount = getMount( path );
// Gets a list of the files in the mount // Gets a list of the files in the mount
List<String> list = new ArrayList<String>(); List<String> list = new ArrayList<>();
mount.list( path, list ); mount.list( path, list );
// Add any mounts that are mounted at this location // Add any mounts that are mounted at this location
@ -481,7 +480,7 @@ public synchronized String[] find( String wildPath ) throws FileSystemException
// Scan as normal, starting from this directory // Scan as normal, starting from this directory
Pattern wildPattern = Pattern.compile( "^\\Q" + wildPath.replaceAll( "\\*", "\\\\E[^\\\\/]*\\\\Q" ) + "\\E$" ); Pattern wildPattern = Pattern.compile( "^\\Q" + wildPath.replaceAll( "\\*", "\\\\E[^\\\\/]*\\\\Q" ) + "\\E$" );
List<String> matches = new ArrayList<String>(); List<String> matches = new ArrayList<>();
findIn( startDir, matches, wildPattern ); findIn( startDir, matches, wildPattern );
// Return matches // Return matches
@ -585,7 +584,7 @@ private synchronized void copyRecursive( String sourcePath, MountWrapper sourceM
destinationMount.makeDirectory( destinationPath ); destinationMount.makeDirectory( destinationPath );
// Copy the source contents into it // Copy the source contents into it
List<String> sourceChildren = new ArrayList<String>(); List<String> sourceChildren = new ArrayList<>();
sourceMount.list( sourcePath, sourceChildren ); sourceMount.list( sourcePath, sourceChildren );
for( String child : sourceChildren ) for( String child : sourceChildren )
{ {
@ -762,7 +761,7 @@ private static String sanitizePath( String path, boolean allowWildcards )
// Collapse the string into its component parts, removing ..'s // Collapse the string into its component parts, removing ..'s
String[] parts = path.split("/"); String[] parts = path.split("/");
Stack<String> outputParts = new Stack<String>(); Stack<String> outputParts = new Stack<>();
for( String part : parts ) for( String part : parts )
{ {
if( part.length() == 0 || part.equals( "." ) ) if( part.length() == 0 || part.equals( "." ) )

View File

@ -34,7 +34,7 @@ public FileInZip( String path, boolean directory, long size )
m_path = path; m_path = path;
m_directory = directory; m_directory = directory;
m_size = m_directory ? 0 : size; m_size = m_directory ? 0 : size;
m_children = new LinkedHashMap<String, FileInZip>(); m_children = new LinkedHashMap<>();
} }
public String getPath() public String getPath()

View File

@ -535,7 +535,7 @@ else if( object instanceof Map )
{ {
if( m_valuesInProgress == null ) if( m_valuesInProgress == null )
{ {
m_valuesInProgress = new IdentityHashMap<Object, LuaValue>(); m_valuesInProgress = new IdentityHashMap<>();
clearWhenDone = true; clearWhenDone = true;
} }
else if( m_valuesInProgress.containsKey( object ) ) else if( m_valuesInProgress.containsKey( object ) )
@ -629,14 +629,14 @@ private Object toObject( LuaValue value )
// Start remembering stuff // Start remembering stuff
if( m_objectsInProgress == null ) if( m_objectsInProgress == null )
{ {
m_objectsInProgress = new IdentityHashMap<LuaValue, Object>(); m_objectsInProgress = new IdentityHashMap<>();
clearWhenDone = true; clearWhenDone = true;
} }
else if( m_objectsInProgress.containsKey( value ) ) else if( m_objectsInProgress.containsKey( value ) )
{ {
return m_objectsInProgress.get( value ); return m_objectsInProgress.get( value );
} }
Map<Object, Object> table = new HashMap<Object, Object>(); Map<Object, Object> table = new HashMap<>();
m_objectsInProgress.put( value, table ); m_objectsInProgress.put( value, table );
// Convert all keys // Convert all keys

View File

@ -234,7 +234,7 @@ public final AxisAlignedBB getCollisionBoundingBox( IBlockState state, @Nonnull
TileGeneric generic = (TileGeneric)tile; TileGeneric generic = (TileGeneric)tile;
// Get collision bounds // Get collision bounds
List<AxisAlignedBB> collision = new ArrayList<AxisAlignedBB>( 1 ); List<AxisAlignedBB> collision = new ArrayList<>( 1 );
generic.getCollisionBounds( collision ); generic.getCollisionBounds( collision );
// Return the union of the collision bounds // Return the union of the collision bounds
@ -262,7 +262,7 @@ public final void addCollisionBoxToList( IBlockState state, @Nonnull World world
TileGeneric generic = (TileGeneric)tile; TileGeneric generic = (TileGeneric)tile;
// Get collision bounds // Get collision bounds
List<AxisAlignedBB> collision = new ArrayList<AxisAlignedBB>( 1 ); List<AxisAlignedBB> collision = new ArrayList<>( 1 );
generic.getCollisionBounds( collision ); generic.getCollisionBounds( collision );
// Add collision bounds to list // Add collision bounds to list

View File

@ -9,7 +9,6 @@
import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableMap;
import dan200.computercraft.ComputerCraft; import dan200.computercraft.ComputerCraft;
import dan200.computercraft.api.lua.ILuaContext; import dan200.computercraft.api.lua.ILuaContext;
import dan200.computercraft.api.lua.ILuaTask;
import dan200.computercraft.api.lua.LuaException; import dan200.computercraft.api.lua.LuaException;
import dan200.computercraft.core.apis.ILuaAPI; import dan200.computercraft.core.apis.ILuaAPI;
import dan200.computercraft.shared.computer.blocks.TileCommandComputer; import dan200.computercraft.shared.computer.blocks.TileCommandComputer;
@ -81,7 +80,7 @@ public String[] getMethodNames()
private Map<Object, Object> createOutput( String output ) private Map<Object, Object> createOutput( String output )
{ {
Map<Object, Object> result = new HashMap<Object, Object>( 1 ); Map<Object, Object> result = new HashMap<>( 1 );
result.put( 1, output ); result.put( 1, output );
return result; return result;
} }
@ -123,11 +122,11 @@ private Object getBlockInfo( World world, BlockPos pos )
String name = Block.REGISTRY.getNameForObject( block ).toString(); String name = Block.REGISTRY.getNameForObject( block ).toString();
int metadata = block.getMetaFromState( state ); int metadata = block.getMetaFromState( state );
Map<Object, Object> table = new HashMap<Object, Object>(); Map<Object, Object> table = new HashMap<>();
table.put( "name", name ); table.put( "name", name );
table.put( "metadata", metadata ); table.put( "metadata", metadata );
Map<Object, Object> stateTable = new HashMap<Object, Object>(); Map<Object, Object> stateTable = new HashMap<>();
for( ImmutableMap.Entry<IProperty<?>, Comparable<?>> entry : state.getActualState( world, pos ).getProperties().entrySet() ) for( ImmutableMap.Entry<IProperty<?>, Comparable<?>> entry : state.getActualState( world, pos ).getProperties().entrySet() )
{ {
String propertyName = entry.getKey().getName(); String propertyName = entry.getKey().getName();
@ -155,39 +154,22 @@ public Object[] callMethod( @Nonnull ILuaContext context, int method, @Nonnull O
{ {
// exec // exec
final String command = getString( arguments, 0 ); final String command = getString( arguments, 0 );
return context.executeMainThreadTask( new ILuaTask() return context.executeMainThreadTask( () -> doCommand( command ) );
{
@Override
public Object[] execute() throws LuaException
{
return doCommand( command );
}
} );
} }
case 1: case 1:
{ {
// execAsync // execAsync
final String command = getString( arguments, 0 ); final String command = getString( arguments, 0 );
long taskID = context.issueMainThreadTask( new ILuaTask() long taskID = context.issueMainThreadTask( () -> doCommand( command ) );
{
@Override
public Object[] execute() throws LuaException
{
return doCommand( command );
}
} );
return new Object[] { taskID }; return new Object[] { taskID };
} }
case 2: case 2:
{ {
// list // list
return context.executeMainThreadTask( new ILuaTask() return context.executeMainThreadTask( () ->
{
@Override
public Object[] execute() throws LuaException
{ {
int i = 1; int i = 1;
Map<Object, Object> result = new HashMap<Object, Object>(); Map<Object, Object> result = new HashMap<>();
MinecraftServer server = m_computer.getWorld().getMinecraftServer(); MinecraftServer server = m_computer.getWorld().getMinecraftServer();
if( server != null ) if( server != null )
{ {
@ -216,7 +198,6 @@ public Object[] execute() throws LuaException
} }
} }
return new Object[]{ result }; return new Object[]{ result };
}
} ); } );
} }
case 3: case 3:
@ -235,10 +216,7 @@ public Object[] execute() throws LuaException
final int maxx = getInt( arguments, 3 ); final int maxx = getInt( arguments, 3 );
final int maxy = getInt( arguments, 4 ); final int maxy = getInt( arguments, 4 );
final int maxz = getInt( arguments, 5 ); final int maxz = getInt( arguments, 5 );
return context.executeMainThreadTask( new ILuaTask() return context.executeMainThreadTask( () ->
{
@Override
public Object[] execute() throws LuaException
{ {
// Get the details of the block // Get the details of the block
World world = m_computer.getWorld(); World world = m_computer.getWorld();
@ -261,7 +239,7 @@ public Object[] execute() throws LuaException
throw new LuaException( "Too many blocks" ); throw new LuaException( "Too many blocks" );
} }
int i=1; int i=1;
Map<Object, Object> results = new HashMap<Object, Object>(); Map<Object, Object> results = new HashMap<>();
for( int y=min.getY(); y<= max.getY(); ++y ) for( int y=min.getY(); y<= max.getY(); ++y )
{ {
for( int z = min.getZ(); z <= max.getZ(); ++z ) for( int z = min.getZ(); z <= max.getZ(); ++z )
@ -274,7 +252,6 @@ public Object[] execute() throws LuaException
} }
} }
return new Object[]{ results }; return new Object[]{ results };
}
} ); } );
} }
case 5: case 5:
@ -283,10 +260,7 @@ public Object[] execute() throws LuaException
final int x = getInt( arguments, 0 ); final int x = getInt( arguments, 0 );
final int y = getInt( arguments, 1 ); final int y = getInt( arguments, 1 );
final int z = getInt( arguments, 2 ); final int z = getInt( arguments, 2 );
return context.executeMainThreadTask( new ILuaTask() return context.executeMainThreadTask( () ->
{
@Override
public Object[] execute() throws LuaException
{ {
// Get the details of the block // Get the details of the block
World world = m_computer.getWorld(); World world = m_computer.getWorld();
@ -299,7 +273,6 @@ public Object[] execute() throws LuaException
{ {
throw new LuaException( "co-ordinates out or range" ); throw new LuaException( "co-ordinates out or range" );
} }
}
} ); } );
} }
default: default:

View File

@ -94,16 +94,6 @@ public Object[] callMethod( @Nonnull IComputerAccess computer, @Nonnull ILuaCont
} }
} }
@Override
public void attach( @Nonnull IComputerAccess computer )
{
}
@Override
public void detach( @Nonnull IComputerAccess computer )
{
}
@Override @Override
public boolean equals( IPeripheral other ) public boolean equals( IPeripheral other )
{ {

View File

@ -33,7 +33,7 @@ public class CommandSender extends CommandBlockBaseLogic
public CommandSender() public CommandSender()
{ {
m_outputTable = new HashMap<Integer, String>(); m_outputTable = new HashMap<>();
} }
public void clearOutput() public void clearOutput()
@ -48,7 +48,7 @@ public Map<Integer, String> getOutput()
public Map<Integer, String> copyOutput() public Map<Integer, String> copyOutput()
{ {
return new HashMap<Integer, String>( m_outputTable ); return new HashMap<>( m_outputTable );
} }
// ICommandSender // ICommandSender

View File

@ -153,6 +153,7 @@ public void queueEvent( String event, Object[] arguments )
ComputerCraft.sendToServer( packet ); ComputerCraft.sendToServer( packet );
} }
@Override
public void readDescription( NBTTagCompound nbttagcompound ) public void readDescription( NBTTagCompound nbttagcompound )
{ {
super.readDescription( nbttagcompound ); super.readDescription( nbttagcompound );

View File

@ -19,7 +19,7 @@ public class ComputerRegistry<TComputer extends IComputer>
protected ComputerRegistry() protected ComputerRegistry()
{ {
m_computers = new HashMap<Integer, TComputer>(); m_computers = new HashMap<>();
reset(); reset();
} }

View File

@ -337,6 +337,7 @@ public int assignNewID()
// Networking stuff // Networking stuff
@Override
public void writeDescription( NBTTagCompound nbttagcompound ) public void writeDescription( NBTTagCompound nbttagcompound )
{ {
super.writeDescription( nbttagcompound ); super.writeDescription( nbttagcompound );

View File

@ -10,7 +10,6 @@
import dan200.computercraft.shared.computer.core.ComputerFamily; import dan200.computercraft.shared.computer.core.ComputerFamily;
import net.minecraft.block.Block; import net.minecraft.block.Block;
import net.minecraft.creativetab.CreativeTabs; import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack; import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound; import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.util.NonNullList; import net.minecraft.util.NonNullList;
@ -29,6 +28,7 @@ public ItemCommandComputer( Block block )
setCreativeTab( ComputerCraft.mainCreativeTab ); setCreativeTab( ComputerCraft.mainCreativeTab );
} }
@Override
public ItemStack create( int id, String label, ComputerFamily family ) public ItemStack create( int id, String label, ComputerFamily family )
{ {
// Ignore types we can't handle // Ignore types we can't handle

View File

@ -13,7 +13,6 @@
import net.minecraft.block.state.IBlockState; import net.minecraft.block.state.IBlockState;
import net.minecraft.creativetab.CreativeTabs; import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack; import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound; import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.tileentity.TileEntity; import net.minecraft.tileentity.TileEntity;

View File

@ -12,7 +12,6 @@
import dan200.computercraft.shared.computer.core.ComputerFamily; import dan200.computercraft.shared.computer.core.ComputerFamily;
import net.minecraft.block.Block; import net.minecraft.block.Block;
import net.minecraft.client.util.ITooltipFlag; import net.minecraft.client.util.ITooltipFlag;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemBlock; import net.minecraft.item.ItemBlock;
import net.minecraft.item.ItemStack; import net.minecraft.item.ItemStack;
import net.minecraft.util.SoundEvent; import net.minecraft.util.SoundEvent;

View File

@ -24,7 +24,6 @@
import net.minecraft.world.World; import net.minecraft.world.World;
import javax.annotation.Nonnull; import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.io.IOException; import java.io.IOException;
import java.util.List; import java.util.List;

View File

@ -7,7 +7,6 @@
package dan200.computercraft.shared.peripheral.commandblock; package dan200.computercraft.shared.peripheral.commandblock;
import dan200.computercraft.api.lua.ILuaContext; import dan200.computercraft.api.lua.ILuaContext;
import dan200.computercraft.api.lua.ILuaTask;
import dan200.computercraft.api.lua.LuaException; import dan200.computercraft.api.lua.LuaException;
import dan200.computercraft.api.peripheral.IComputerAccess; import dan200.computercraft.api.peripheral.IComputerAccess;
import dan200.computercraft.api.peripheral.IPeripheral; import dan200.computercraft.api.peripheral.IPeripheral;
@ -55,41 +54,27 @@ public Object[] callMethod( @Nonnull IComputerAccess computer, @Nonnull ILuaCont
case 0: case 0:
{ {
// getCommand // getCommand
return context.executeMainThreadTask( new ILuaTask() return context.executeMainThreadTask( () -> new Object[] {
{
@Override
public Object[] execute() throws LuaException
{
return new Object[] {
m_commandBlock.getCommandBlockLogic().getCommand() m_commandBlock.getCommandBlockLogic().getCommand()
};
}
} ); } );
} }
case 1: case 1:
{ {
// setCommand // setCommand
final String command = getString( arguments, 0 ); final String command = getString( arguments, 0 );
context.issueMainThreadTask( new ILuaTask() context.issueMainThreadTask( () ->
{
@Override
public Object[] execute() throws LuaException
{ {
BlockPos pos = m_commandBlock.getPos(); BlockPos pos = m_commandBlock.getPos();
m_commandBlock.getCommandBlockLogic().setCommand( command ); m_commandBlock.getCommandBlockLogic().setCommand( command );
m_commandBlock.getWorld().markBlockRangeForRenderUpdate( pos, pos ); m_commandBlock.getWorld().markBlockRangeForRenderUpdate( pos, pos );
return null; return null;
}
} ); } );
return null; return null;
} }
case 2: case 2:
{ {
// runCommand // runCommand
return context.executeMainThreadTask( new ILuaTask() return context.executeMainThreadTask( () ->
{
@Override
public Object[] execute() throws LuaException
{ {
m_commandBlock.getCommandBlockLogic().trigger( m_commandBlock.getWorld() ); m_commandBlock.getCommandBlockLogic().trigger( m_commandBlock.getWorld() );
int result = m_commandBlock.getCommandBlockLogic().getSuccessCount(); int result = m_commandBlock.getCommandBlockLogic().getSuccessCount();
@ -101,23 +86,12 @@ public Object[] execute() throws LuaException
{ {
return new Object[] { false, "Command failed" }; return new Object[] { false, "Command failed" };
} }
}
} ); } );
} }
} }
return null; return null;
} }
@Override
public void attach( @Nonnull IComputerAccess computer )
{
}
@Override
public void detach( @Nonnull IComputerAccess computer )
{
}
@Override @Override
public boolean equals( IPeripheral other ) public boolean equals( IPeripheral other )
{ {

View File

@ -51,6 +51,7 @@ public BlockPeripheral()
); );
} }
@Override
@Nonnull @Nonnull
@SideOnly( Side.CLIENT) @SideOnly( Side.CLIENT)
public BlockRenderLayer getBlockLayer() public BlockRenderLayer getBlockLayer()

View File

@ -10,7 +10,6 @@
import dan200.computercraft.shared.peripheral.PeripheralType; import dan200.computercraft.shared.peripheral.PeripheralType;
import net.minecraft.block.Block; import net.minecraft.block.Block;
import net.minecraft.creativetab.CreativeTabs; import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack; import net.minecraft.item.ItemStack;
import net.minecraft.util.NonNullList; import net.minecraft.util.NonNullList;

View File

@ -14,7 +14,6 @@
import net.minecraft.block.state.IBlockState; import net.minecraft.block.state.IBlockState;
import net.minecraft.creativetab.CreativeTabs; import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack; import net.minecraft.item.ItemStack;
import net.minecraft.tileentity.TileEntity; import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.*; import net.minecraft.util.*;

View File

@ -10,12 +10,10 @@
import dan200.computercraft.shared.peripheral.PeripheralType; import dan200.computercraft.shared.peripheral.PeripheralType;
import net.minecraft.block.Block; import net.minecraft.block.Block;
import net.minecraft.creativetab.CreativeTabs; import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack; import net.minecraft.item.ItemStack;
import net.minecraft.util.NonNullList; import net.minecraft.util.NonNullList;
import javax.annotation.Nonnull; import javax.annotation.Nonnull;
import javax.annotation.Nullable;
public class ItemPeripheral extends ItemPeripheralBase public class ItemPeripheral extends ItemPeripheralBase
{ {

View File

@ -72,7 +72,7 @@ private static class MountInfo
public TileDiskDrive() public TileDiskDrive()
{ {
m_computers = new HashMap<IComputerAccess, MountInfo>(); m_computers = new HashMap<>();
m_diskStack = ItemStack.EMPTY; m_diskStack = ItemStack.EMPTY;
m_diskMount = null; m_diskMount = null;

View File

@ -131,7 +131,7 @@ public Object[] callMethod( @Nonnull IComputerAccess computer, @Nonnull ILuaCont
synchronized( m_entity.m_peripheralsByName ) synchronized( m_entity.m_peripheralsByName )
{ {
int idx = 1; int idx = 1;
Map<Object,Object> table = new HashMap<Object,Object>(); Map<Object,Object> table = new HashMap<>();
for( String name : m_entity.m_peripheralWrappersByName.keySet() ) for( String name : m_entity.m_peripheralWrappersByName.keySet() )
{ {
table.put( idx++, name ); table.put( idx++, name );
@ -161,7 +161,7 @@ public Object[] callMethod( @Nonnull IComputerAccess computer, @Nonnull ILuaCont
String[] methodNames = m_entity.getMethodNamesRemote( getString( arguments, 0 ) ); String[] methodNames = m_entity.getMethodNamesRemote( getString( arguments, 0 ) );
if( methodNames != null ) if( methodNames != null )
{ {
Map<Object,Object> table = new HashMap<Object,Object>(); Map<Object,Object> table = new HashMap<>();
for(int i=0; i<methodNames.length; ++i ) { for(int i=0; i<methodNames.length; ++i ) {
table.put( i+1, methodNames[i] ); table.put( i+1, methodNames[i] );
} }
@ -247,14 +247,14 @@ public boolean equals( IPeripheral other )
public TileCable() public TileCable()
{ {
m_receivers = new HashSet<IPacketReceiver>(); m_receivers = new HashSet<>();
m_transmitQueue = new LinkedList<PacketWrapper>(); m_transmitQueue = new LinkedList<>();
m_peripheralAccessAllowed = false; m_peripheralAccessAllowed = false;
m_attachedPeripheralID = -1; m_attachedPeripheralID = -1;
m_peripheralsByName = new HashMap<String, IPeripheral>(); m_peripheralsByName = new HashMap<>();
m_peripheralWrappersByName = new HashMap<String, RemotePeripheralWrapper>(); m_peripheralWrappersByName = new HashMap<>();
m_peripheralsKnown = false; m_peripheralsKnown = false;
m_destroyed = false; m_destroyed = false;
@ -685,14 +685,12 @@ public void networkChanged()
if( !m_destroyed ) if( !m_destroyed )
{ {
// If this modem is alive, rebuild the network // If this modem is alive, rebuild the network
searchNetwork( new ICableVisitor() { searchNetwork( ( modem, distance ) ->
public void visit( TileCable modem, int distance )
{ {
synchronized( modem.m_peripheralsByName ) synchronized( modem.m_peripheralsByName )
{ {
modem.m_peripheralsKnown = false; modem.m_peripheralsKnown = false;
} }
}
} ); } );
} }
else else
@ -733,14 +731,12 @@ private PacketWrapper( Packet m_packet, double m_range )
private void dispatchPacket( final PacketWrapper packet ) private void dispatchPacket( final PacketWrapper packet )
{ {
searchNetwork( new ICableVisitor() { searchNetwork( ( modem, distance ) ->
public void visit( TileCable modem, int distance )
{ {
if( distance <= packet.m_range) if( distance <= packet.m_range)
{ {
modem.receivePacket( packet.m_packet, distance ); modem.receivePacket( packet.m_packet, distance );
} }
}
} ); } );
} }
@ -778,7 +774,7 @@ public RemotePeripheralWrapper( IPeripheral peripheral, IComputerAccess computer
assert( m_type != null ); assert( m_type != null );
assert( m_methods != null ); assert( m_methods != null );
m_methodMap = new HashMap<String, Integer>(); m_methodMap = new HashMap<>();
for( int i=0; i<m_methods.length; ++i ) { for( int i=0; i<m_methods.length; ++i ) {
if( m_methods[i] != null ) { if( m_methods[i] != null ) {
m_methodMap.put( m_methods[i], i ); m_methodMap.put( m_methods[i], i );
@ -876,11 +872,10 @@ private void findPeripherals( )
synchronized( m_peripheralsByName ) synchronized( m_peripheralsByName )
{ {
// Collect the peripherals // Collect the peripherals
final Map<String, IPeripheral> newPeripheralsByName = new HashMap<String, IPeripheral>(); final Map<String, IPeripheral> newPeripheralsByName = new HashMap<>();
if( getPeripheralType() == PeripheralType.WiredModemWithCable ) if( getPeripheralType() == PeripheralType.WiredModemWithCable )
{ {
searchNetwork( new ICableVisitor() { searchNetwork( ( modem, distance ) ->
public void visit( TileCable modem, int distance )
{ {
if( modem != origin ) if( modem != origin )
{ {
@ -891,7 +886,6 @@ public void visit( TileCable modem, int distance )
newPeripheralsByName.put( periphName, peripheral ); newPeripheralsByName.put( periphName, peripheral );
} }
} }
}
} ); } );
} }
//System.out.println( newPeripheralsByName.size()+" peripherals discovered" ); //System.out.println( newPeripheralsByName.size()+" peripherals discovered" );
@ -1035,7 +1029,7 @@ private static void visitBlock( Queue<SearchLoc> queue, SearchLoc location, int
private void searchNetwork( ICableVisitor visitor ) private void searchNetwork( ICableVisitor visitor )
{ {
int searchID = ++s_nextUniqueSearchID; int searchID = ++s_nextUniqueSearchID;
Queue<SearchLoc> queue = new LinkedList<SearchLoc>(); Queue<SearchLoc> queue = new LinkedList<>();
enqueue( queue, getWorld(), getPos(), 1 ); enqueue( queue, getWorld(), getPos(), 1 );
int visited = 0; int visited = 0;

View File

@ -38,7 +38,7 @@ public static void resetNetworks()
private WirelessNetwork() private WirelessNetwork()
{ {
m_receivers = new HashSet<IPacketReceiver>(); m_receivers = new HashSet<>();
} }
@Override @Override

View File

@ -65,7 +65,7 @@ public class TileMonitor extends TilePeripheralBase
public TileMonitor() public TileMonitor()
{ {
m_computers = new HashSet<IComputerAccess>(); m_computers = new HashSet<>();
m_destroyed = false; m_destroyed = false;
m_ignoreMe = false; m_ignoreMe = false;

View File

@ -131,16 +131,6 @@ public Object[] callMethod( @Nonnull IComputerAccess computer, @Nonnull ILuaCont
} }
} }
@Override
public void attach( @Nonnull IComputerAccess computer )
{
}
@Override
public void detach( @Nonnull IComputerAccess computer )
{
}
@Override @Override
public boolean equals( IPeripheral other ) public boolean equals( IPeripheral other )
{ {

View File

@ -75,17 +75,6 @@ public boolean equals( IPeripheral other )
} }
} }
@Override
public void attach( @Nonnull IComputerAccess computerAccess )
{
}
@Override
public void detach( @Nonnull IComputerAccess computerAccess )
{
}
@Nonnull @Nonnull
@Override @Override
public String getType() public String getType()

View File

@ -32,6 +32,7 @@ public synchronized void update()
// IPeripheralTile implementation // IPeripheralTile implementation
@Override
public IPeripheral getPeripheral( EnumFacing side ) public IPeripheral getPeripheral( EnumFacing side )
{ {
return m_peripheral; return m_peripheral;

View File

@ -8,7 +8,6 @@
import dan200.computercraft.ComputerCraft; import dan200.computercraft.ComputerCraft;
import dan200.computercraft.api.lua.ILuaContext; import dan200.computercraft.api.lua.ILuaContext;
import dan200.computercraft.api.lua.ILuaTask;
import dan200.computercraft.api.lua.LuaException; import dan200.computercraft.api.lua.LuaException;
import dan200.computercraft.api.pocket.IPocketUpgrade; import dan200.computercraft.api.pocket.IPocketUpgrade;
import dan200.computercraft.core.apis.ILuaAPI; import dan200.computercraft.core.apis.ILuaAPI;
@ -72,10 +71,7 @@ public Object[] callMethod( @Nonnull ILuaContext context, int method, @Nonnull O
{ {
case 0: case 0:
// equipBack // equipBack
return context.executeMainThreadTask( new ILuaTask() return context.executeMainThreadTask( () ->
{
@Override
public Object[] execute() throws LuaException
{ {
if( !(m_computer.getEntity() instanceof EntityPlayer) ) if( !(m_computer.getEntity() instanceof EntityPlayer) )
{ {
@ -114,15 +110,11 @@ public Object[] execute() throws LuaException
m_computer.setUpgrade( newUpgrade ); m_computer.setUpgrade( newUpgrade );
return null; return null;
}
} ); } );
case 1: case 1:
// unequipBack // unequipBack
return context.executeMainThreadTask( new ILuaTask() return context.executeMainThreadTask( () ->
{
@Override
public Object[] execute() throws LuaException
{ {
if( !(m_computer.getEntity() instanceof EntityPlayer) ) if( !(m_computer.getEntity() instanceof EntityPlayer) )
{ {
@ -149,7 +141,6 @@ public Object[] execute() throws LuaException
} }
return null; return null;
}
} ); } );
default: default:
return null; return null;

View File

@ -184,7 +184,7 @@ public ActionResult<ItemStack> onItemRightClick( World world, EntityPlayer playe
if( !stop ) ComputerCraft.openPocketComputerGUI( player, hand ); if( !stop ) ComputerCraft.openPocketComputerGUI( player, hand );
} }
return new ActionResult<ItemStack>( EnumActionResult.SUCCESS, stack ); return new ActionResult<>( EnumActionResult.SUCCESS, stack );
} }
@Nonnull @Nonnull

View File

@ -9,7 +9,6 @@
import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.EntityLivingBase;
import net.minecraft.item.ItemStack; import net.minecraft.item.ItemStack;
import net.minecraft.util.ResourceLocation; import net.minecraft.util.ResourceLocation;
import net.minecraft.world.World;
import javax.annotation.Nonnull; import javax.annotation.Nonnull;
import javax.annotation.Nullable; import javax.annotation.Nullable;
@ -79,10 +78,4 @@ else if( entity != null )
access.setLight( modem.isActive() ? 0xBA0000 : -1 ); access.setLight( modem.isActive() ? 0xBA0000 : -1 );
} }
} }
@Override
public boolean onRightClick( @Nonnull World world, @Nonnull IPocketAccess access, @Nullable IPeripheral peripheral )
{
return false;
}
} }

View File

@ -15,7 +15,6 @@
import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.EntityLivingBase;
import net.minecraft.item.ItemStack; import net.minecraft.item.ItemStack;
import net.minecraft.util.ResourceLocation; import net.minecraft.util.ResourceLocation;
import net.minecraft.world.World;
import javax.annotation.Nonnull; import javax.annotation.Nonnull;
import javax.annotation.Nullable; import javax.annotation.Nullable;
@ -76,12 +75,4 @@ else if ( entity != null )
speaker.update(); speaker.update();
} }
} }
@Override
public boolean onRightClick(@Nonnull World world, @Nonnull IPocketAccess access, @Nullable IPeripheral peripheral )
{
return false;
}
} }

View File

@ -51,9 +51,9 @@ public abstract class CCTurtleProxyCommon implements ICCTurtleProxy
public CCTurtleProxyCommon() public CCTurtleProxyCommon()
{ {
m_legacyTurtleUpgrades = new HashMap<Integer, ITurtleUpgrade>(); m_legacyTurtleUpgrades = new HashMap<>();
m_turtleUpgrades = new HashMap<String, ITurtleUpgrade>(); m_turtleUpgrades = new HashMap<>();
m_dropConsumers = new WeakHashMap<Entity, IEntityDropConsumer>(); m_dropConsumers = new WeakHashMap<>();
} }
// ICCTurtleProxy implementation // ICCTurtleProxy implementation

View File

@ -179,14 +179,7 @@ public void handlePacket( final ComputerCraftPacket packet, final EntityPlayer p
processPacket( packet, player ); processPacket( packet, player );
} else } else
{ {
listener.addScheduledTask( new Runnable() listener.addScheduledTask( () -> processPacket( packet, player ) );
{
@Override
public void run()
{
processPacket( packet, player );
}
} );
} }
} }
} }

View File

@ -6,7 +6,6 @@
package dan200.computercraft.shared.turtle.apis; package dan200.computercraft.shared.turtle.apis;
import com.google.common.base.Optional;
import dan200.computercraft.api.lua.ILuaContext; import dan200.computercraft.api.lua.ILuaContext;
import dan200.computercraft.api.lua.LuaException; import dan200.computercraft.api.lua.LuaException;
import dan200.computercraft.api.turtle.ITurtleAccess; import dan200.computercraft.api.turtle.ITurtleAccess;
@ -21,6 +20,7 @@
import javax.annotation.Nonnull; import javax.annotation.Nonnull;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
import java.util.Optional;
import static dan200.computercraft.core.apis.ArgumentHelper.*; import static dan200.computercraft.core.apis.ArgumentHelper.*;
@ -149,7 +149,7 @@ private Optional<TurtleSide> parseSide( Object[] arguments, int index ) throws L
String side = optString( arguments, index, null ); String side = optString( arguments, index, null );
if( side == null ) if( side == null )
{ {
return Optional.absent(); return Optional.empty();
} }
else if( side.equalsIgnoreCase( "left" ) ) else if( side.equalsIgnoreCase( "left" ) )
{ {
@ -435,7 +435,7 @@ public Object[] callMethod( @Nonnull ILuaContext context, int method, @Nonnull O
int damage = stack.getItemDamage(); int damage = stack.getItemDamage();
int count = stack.getCount(); int count = stack.getCount();
Map<Object, Object> table = new HashMap<Object, Object>(); Map<Object, Object> table = new HashMap<>();
table.put( "name", name ); table.put( "name", name );
table.put( "damage", damage ); table.put( "damage", damage );
table.put( "count", count ); table.put( "count", count );

View File

@ -6,10 +6,11 @@
package dan200.computercraft.shared.turtle.core; package dan200.computercraft.shared.turtle.core;
import com.google.common.base.Optional;
import dan200.computercraft.api.turtle.TurtleSide; import dan200.computercraft.api.turtle.TurtleSide;
import dan200.computercraft.api.turtle.TurtleVerb; import dan200.computercraft.api.turtle.TurtleVerb;
import java.util.Optional;
public class TurtleAttackCommand extends TurtleToolCommand public class TurtleAttackCommand extends TurtleToolCommand
{ {
public TurtleAttackCommand( InteractDirection direction, Optional<TurtleSide> side ) public TurtleAttackCommand( InteractDirection direction, Optional<TurtleSide> side )

View File

@ -41,7 +41,7 @@
public class TurtleBrain implements ITurtleAccess public class TurtleBrain implements ITurtleAccess
{ {
private static int s_nextInstanceID = 0; private static int s_nextInstanceID = 0;
private static Map<Integer, WeakReference<TurtleBrain>> s_allClientBrains = new HashMap<Integer, WeakReference<TurtleBrain>>(); private static Map<Integer, WeakReference<TurtleBrain>> s_allClientBrains = new HashMap<>();
public static int assignInstanceID() public static int assignInstanceID()
{ {
@ -75,7 +75,7 @@ public static void setClientBrain( int instanceID, TurtleBrain brain )
{ {
if( getClientBrain( instanceID ) != brain ) if( getClientBrain( instanceID ) != brain )
{ {
s_allClientBrains.put( instanceID, new WeakReference<TurtleBrain>( brain ) ); s_allClientBrains.put( instanceID, new WeakReference<>( brain ) );
} }
} }
} }
@ -127,12 +127,12 @@ public TurtleBrain( TileTurtle turtle )
{ {
m_owner = turtle; m_owner = turtle;
m_commandQueue = new LinkedList<TurtleCommandQueueEntry>(); m_commandQueue = new LinkedList<>();
m_commandsIssued = 0; m_commandsIssued = 0;
m_upgrades = new HashMap<TurtleSide, ITurtleUpgrade>(); m_upgrades = new HashMap<>();
m_peripherals = new HashMap<TurtleSide, IPeripheral>(); m_peripherals = new HashMap<>();
m_upgradeNBTData = new HashMap<TurtleSide, NBTTagCompound>(); m_upgradeNBTData = new HashMap<>();
m_selectedSlot = 0; m_selectedSlot = 0;
m_fuelLevel = 0; m_fuelLevel = 0;

View File

@ -6,10 +6,11 @@
package dan200.computercraft.shared.turtle.core; package dan200.computercraft.shared.turtle.core;
import com.google.common.base.Optional;
import dan200.computercraft.api.turtle.TurtleSide; import dan200.computercraft.api.turtle.TurtleSide;
import dan200.computercraft.api.turtle.TurtleVerb; import dan200.computercraft.api.turtle.TurtleVerb;
import java.util.Optional;
public class TurtleDigCommand extends TurtleToolCommand public class TurtleDigCommand extends TurtleToolCommand
{ {
public TurtleDigCommand( InteractDirection direction, Optional<TurtleSide> side ) public TurtleDigCommand( InteractDirection direction, Optional<TurtleSide> side )

View File

@ -53,11 +53,11 @@ public TurtleCommandResult execute( @Nonnull ITurtleAccess turtle )
String name = Block.REGISTRY.getNameForObject( block ).toString(); String name = Block.REGISTRY.getNameForObject( block ).toString();
int metadata = block.getMetaFromState( state ); int metadata = block.getMetaFromState( state );
Map<Object, Object> table = new HashMap<Object, Object>(); Map<Object, Object> table = new HashMap<>();
table.put( "name", name ); table.put( "name", name );
table.put( "metadata", metadata ); table.put( "metadata", metadata );
Map<Object, Object> stateTable = new HashMap<Object, Object>(); Map<Object, Object> stateTable = new HashMap<>();
for( ImmutableMap.Entry<IProperty<?>, ?> entry : state.getActualState( world, newPosition ).getProperties().entrySet() ) for( ImmutableMap.Entry<IProperty<?>, ?> entry : state.getActualState( world, newPosition ).getProperties().entrySet() )
{ {
String propertyName = entry.getKey().getName(); String propertyName = entry.getKey().getName();
@ -79,10 +79,10 @@ public TurtleCommandResult execute( @Nonnull ITurtleAccess turtle )
if( !FAIL_ON_AIR ) if( !FAIL_ON_AIR )
{ {
Map<Object, Object> table = new HashMap<Object, Object>(); Map<Object, Object> table = new HashMap<>();
table.put( "name", "minecraft:air" ); table.put( "name", "minecraft:air" );
table.put( "metadata", 0 ); table.put( "metadata", 0 );
table.put( "state", new HashMap<Object, Object>() ); table.put( "state", new HashMap<>() );
return TurtleCommandResult.success( new Object[]{ table } ); return TurtleCommandResult.success( new Object[]{ table } );
} }
return TurtleCommandResult.failure( "No block to inspect" ); return TurtleCommandResult.failure( "No block to inspect" );

View File

@ -12,7 +12,6 @@
import dan200.computercraft.api.turtle.TurtleAnimation; import dan200.computercraft.api.turtle.TurtleAnimation;
import dan200.computercraft.api.turtle.TurtleCommandResult; import dan200.computercraft.api.turtle.TurtleCommandResult;
import dan200.computercraft.shared.util.DirectionUtil; import dan200.computercraft.shared.util.DirectionUtil;
import dan200.computercraft.shared.util.IEntityDropConsumer;
import dan200.computercraft.shared.util.InventoryUtil; import dan200.computercraft.shared.util.InventoryUtil;
import dan200.computercraft.shared.util.WorldUtil; import dan200.computercraft.shared.util.WorldUtil;
import net.minecraft.block.Block; import net.minecraft.block.Block;
@ -225,17 +224,13 @@ private static ItemStack deployOnEntity( @Nonnull ItemStack stack, final ITurtle
// Start claiming entity drops // Start claiming entity drops
Entity hitEntity = hit.getKey(); Entity hitEntity = hit.getKey();
Vec3d hitPos = hit.getValue(); Vec3d hitPos = hit.getValue();
ComputerCraft.setEntityDropConsumer( hitEntity, new IEntityDropConsumer() ComputerCraft.setEntityDropConsumer( hitEntity, ( entity, drop ) ->
{
@Override
public void consumeDrop( Entity entity, @Nonnull ItemStack drop )
{ {
ItemStack remainder = InventoryUtil.storeItems( drop, turtle.getItemHandler(), turtle.getSelectedSlot() ); ItemStack remainder = InventoryUtil.storeItems( drop, turtle.getItemHandler(), turtle.getSelectedSlot() );
if( !remainder.isEmpty() ) if( !remainder.isEmpty() )
{ {
WorldUtil.dropItemStack( remainder, world, position, turtle.getDirection().getOpposite() ); WorldUtil.dropItemStack( remainder, world, position, turtle.getDirection().getOpposite() );
} }
}
} ); } );
// Place on the entity // Place on the entity

View File

@ -6,10 +6,10 @@
package dan200.computercraft.shared.turtle.core; package dan200.computercraft.shared.turtle.core;
import com.google.common.base.Optional;
import dan200.computercraft.api.turtle.*; import dan200.computercraft.api.turtle.*;
import javax.annotation.Nonnull; import javax.annotation.Nonnull;
import java.util.Optional;
public class TurtleToolCommand implements ITurtleCommand public class TurtleToolCommand implements ITurtleCommand
{ {

View File

@ -28,7 +28,7 @@ public TurtleVisionCamera( World world, ITurtleAccess turtle )
{ {
super( world ); super( world );
m_turtle = turtle; m_turtle = turtle;
m_armor = new ArrayList<ItemStack>(); m_armor = new ArrayList<>();
applyPos(); applyPos();
} }

View File

@ -20,5 +20,6 @@ public interface ITurtleItem extends IComputerItem, IColouredItem
ITurtleUpgrade getUpgrade( ItemStack stack, TurtleSide side ); ITurtleUpgrade getUpgrade( ItemStack stack, TurtleSide side );
int getFuelLevel( ItemStack stack ); int getFuelLevel( ItemStack stack );
ResourceLocation getOverlay( ItemStack stack ); ResourceLocation getOverlay( ItemStack stack );
@Override
int getColour( @Nonnull ItemStack stack ); int getColour( @Nonnull ItemStack stack );
} }

View File

@ -18,7 +18,6 @@
import net.minecraft.block.state.IBlockState; import net.minecraft.block.state.IBlockState;
import net.minecraft.creativetab.CreativeTabs; import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack; import net.minecraft.item.ItemStack;
import net.minecraft.tileentity.TileEntity; import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.EnumFacing; import net.minecraft.util.EnumFacing;

View File

@ -73,16 +73,6 @@ public Object[] callMethod( @Nonnull IComputerAccess computer, @Nonnull ILuaCont
} }
} }
@Override
public void attach( @Nonnull IComputerAccess computer )
{
}
@Override
public void detach( @Nonnull IComputerAccess computer )
{
}
@Override @Override
public boolean equals( IPeripheral other ) public boolean equals( IPeripheral other )
{ {

View File

@ -118,9 +118,4 @@ public Pair<IBakedModel, Matrix4f> getModel( ITurtleAccess turtle, @Nonnull Turt
return Pair.of( modelManager.getModel( m_rightModel ), transform ); return Pair.of( modelManager.getModel( m_rightModel ), transform );
} }
} }
@Override
public void update( @Nonnull ITurtleAccess turtle, @Nonnull TurtleSide side )
{
}
} }

View File

@ -88,7 +88,7 @@ public ArrayList<ItemStack> doCrafting( World world, int maxCount )
if( !result.isEmpty() ) if( !result.isEmpty() )
{ {
// Special case: craft(0) just returns an empty list if crafting was possible // Special case: craft(0) just returns an empty list if crafting was possible
ArrayList<ItemStack> results = new ArrayList<ItemStack>(); ArrayList<ItemStack> results = new ArrayList<>();
if( maxCount == 0 ) if( maxCount == 0 )
{ {
return results; return results;

View File

@ -12,7 +12,6 @@
import dan200.computercraft.shared.turtle.core.TurtleBrain; import dan200.computercraft.shared.turtle.core.TurtleBrain;
import dan200.computercraft.shared.turtle.core.TurtlePlaceCommand; import dan200.computercraft.shared.turtle.core.TurtlePlaceCommand;
import dan200.computercraft.shared.turtle.core.TurtlePlayer; import dan200.computercraft.shared.turtle.core.TurtlePlayer;
import dan200.computercraft.shared.util.IEntityDropConsumer;
import dan200.computercraft.shared.util.InventoryUtil; import dan200.computercraft.shared.util.InventoryUtil;
import dan200.computercraft.shared.util.WorldUtil; import dan200.computercraft.shared.util.WorldUtil;
import net.minecraft.block.Block; import net.minecraft.block.Block;
@ -121,11 +120,6 @@ public Pair<IBakedModel, Matrix4f> getModel( ITurtleAccess turtle, @Nonnull Turt
); );
} }
@Override
public void update( @Nonnull ITurtleAccess turtle, @Nonnull TurtleSide side )
{
}
@Nonnull @Nonnull
@Override @Override
public TurtleCommandResult useTool( @Nonnull ITurtleAccess turtle, @Nonnull TurtleSide side, @Nonnull TurtleVerb verb, @Nonnull EnumFacing direction ) public TurtleCommandResult useTool( @Nonnull ITurtleAccess turtle, @Nonnull TurtleSide side, @Nonnull TurtleVerb verb, @Nonnull EnumFacing direction )
@ -186,17 +180,13 @@ private TurtleCommandResult attack( final ITurtleAccess turtle, EnumFacing direc
// Start claiming entity drops // Start claiming entity drops
Entity hitEntity = hit.getKey(); Entity hitEntity = hit.getKey();
ComputerCraft.setEntityDropConsumer( hitEntity, new IEntityDropConsumer() ComputerCraft.setEntityDropConsumer( hitEntity, ( entity, drop ) ->
{
@Override
public void consumeDrop( Entity entity, @Nonnull ItemStack drop )
{ {
ItemStack remainder = InventoryUtil.storeItems( drop, turtle.getItemHandler(), turtle.getSelectedSlot() ); ItemStack remainder = InventoryUtil.storeItems( drop, turtle.getItemHandler(), turtle.getSelectedSlot() );
if( !remainder.isEmpty() ) if( !remainder.isEmpty() )
{ {
WorldUtil.dropItemStack( remainder, world, position, turtle.getDirection().getOpposite() ); WorldUtil.dropItemStack( remainder, world, position, turtle.getDirection().getOpposite() );
} }
}
} ); } );
// Attack the entity // Attack the entity

View File

@ -73,15 +73,10 @@ private static int getNextID( File location, boolean directory )
{ {
isr = new InputStreamReader( in ); isr = new InputStreamReader( in );
} }
BufferedReader br = new BufferedReader( isr ); try( BufferedReader br = new BufferedReader( isr ) )
try
{ {
idString = br.readLine(); idString = br.readLine();
} }
finally
{
br.close();
}
} }
catch( IOException e ) catch( IOException e )
{ {

View File

@ -99,7 +99,7 @@ private static Object fromNBTTag( NBTBase tag )
{ {
NBTTagCompound c = (NBTTagCompound)tag; NBTTagCompound c = (NBTTagCompound)tag;
int len = c.getInteger( "len" ); int len = c.getInteger( "len" );
Map<Object, Object> map = new HashMap<Object, Object>( len ); Map<Object, Object> map = new HashMap<>( len );
for( int i=0; i<len; ++i ) for( int i=0; i<len; ++i )
{ {
Object key = fromNBTTag( c.getTag( "k" + Integer.toString( i ) ) ); Object key = fromNBTTag( c.getTag( "k" + Integer.toString( i ) ) );