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;
// API users
private static List<IPeripheralProvider> peripheralProviders = new ArrayList<IPeripheralProvider>();
private static List<IBundledRedstoneProvider> bundledRedstoneProviders = new ArrayList<IBundledRedstoneProvider>();
private static List<IMediaProvider> mediaProviders = new ArrayList<IMediaProvider>();
private static List<ITurtlePermissionProvider> permissionProviders = new ArrayList<ITurtlePermissionProvider>();
private static final Map<String, IPocketUpgrade> pocketUpgrades = new HashMap<String, IPocketUpgrade>();
private static List<IPeripheralProvider> peripheralProviders = new ArrayList<>();
private static List<IBundledRedstoneProvider> bundledRedstoneProviders = new ArrayList<>();
private static List<IMediaProvider> mediaProviders = new ArrayList<>();
private static List<ITurtlePermissionProvider> permissionProviders = new ArrayList<>();
private static final Map<String, IPocketUpgrade> pocketUpgrades = new HashMap<>();
// Implementation
@Mod.Instance( value = ComputerCraft.MOD_ID )
@ -755,7 +755,7 @@ public static IPocketUpgrade getPocketUpgrade( @Nonnull ItemStack stack )
}
public static Iterable<IPocketUpgrade> getVanillaPocketUpgrades() {
List<IPocketUpgrade> upgrades = new ArrayList<IPocketUpgrade>();
List<IPocketUpgrade> upgrades = new ArrayList<>();
for(IPocketUpgrade upgrade : pocketUpgrades.values()) {
if(upgrade instanceof PocketModem || upgrade instanceof PocketSpeaker) {
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 )
{
// Start building list of mounts
List<IMount> mounts = new ArrayList<IMount>();
List<IMount> mounts = new ArrayList<>();
subPath = "assets/" + domain + "/" + subPath;
// Mount from debug dir

View File

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

View File

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

View File

@ -91,7 +91,9 @@ public interface IPeripheral
* computers can be attached to a peripheral at once.
* @see #detach
*/
void attach( @Nonnull IComputerAccess computer );
default void attach( @Nonnull IComputerAccess computer )
{
}
/**
* 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.
* @see #detach
*/
void detach( @Nonnull IComputerAccess computer );
default void detach( @Nonnull IComputerAccess computer )
{
}
/**
* Determine whether this peripheral is equivalent to another one.

View File

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

View File

@ -74,7 +74,9 @@ public interface IPocketUpgrade
* @param peripheral The peripheral for this upgrade.
* @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.
@ -87,5 +89,8 @@ public interface IPocketUpgrade
* access the GUI.
* @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)
*/
@FunctionalInterface
public interface IBundledRedstoneProvider
{
/**

View File

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

View File

@ -136,5 +136,7 @@ public interface ITurtleUpgrade
* @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.
*/
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.core.ComputerFamily;
import dan200.computercraft.shared.computer.core.IComputer;
import dan200.computercraft.shared.computer.core.IComputerContainer;
import dan200.computercraft.shared.computer.inventory.ContainerComputer;
import net.minecraft.client.gui.inventory.GuiContainer;
import net.minecraft.client.renderer.GlStateManager;
@ -61,14 +60,7 @@ public void initGui()
super.initGui();
Keyboard.enableRepeatEvents( true );
m_terminal = new WidgetTerminal( 0, 0, m_termWidth, m_termHeight, new IComputerContainer()
{
@Override
public IComputer getComputer()
{
return m_computer;
}
}, 2, 2, 2, 2 );
m_terminal = new WidgetTerminal( 0, 0, m_termWidth, m_termHeight, () -> m_computer, 2, 2, 2, 2 );
m_terminal.setAllowFocusLoss( false );
xSize = m_terminal.getWidth() + 24;
ySize = m_terminal.getHeight() + 24;

View File

@ -23,7 +23,7 @@ public GuiConfigCC( GuiScreen parentScreen )
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())
{
elements.add( new ConfigElement( property ) );

View File

@ -11,7 +11,6 @@
import dan200.computercraft.client.gui.widgets.WidgetTerminal;
import dan200.computercraft.shared.computer.core.ComputerFamily;
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.inventory.ContainerTurtle;
import net.minecraft.client.Minecraft;
@ -67,14 +66,7 @@ public void initGui()
( height - ySize ) / 2 + 8,
ComputerCraft.terminalWidth_turtle,
ComputerCraft.terminalHeight_turtle,
new IComputerContainer()
{
@Override
public IComputer getComputer()
{
return m_computer;
}
},
() -> m_computer,
2, 2, 2, 2
);
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 )
{
super( x, y, w, h );
m_widgets = new ArrayList<Widget>();
m_widgets = new ArrayList<>();
m_modalWidget = null;
}
@ -203,7 +203,8 @@ public boolean suppressItemTooltips( Minecraft mc, int xOrigin, int yOrigin, int
return false;
}
public boolean suppressKeyPress( char c, int k )
@Override
public boolean suppressKeyPress( char c, int k )
{
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_bottomMargin = bottomMargin;
m_keysDown = new ArrayList<Integer>();
m_keysDown = new ArrayList<>();
}
public void setAllowFocusLoss( boolean allowFocusLoss )

View File

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

View File

@ -198,28 +198,24 @@ public void init()
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 IItemColor()
mc.getItemColors().registerItemColorHandler( ( stack, layer ) ->
{
@Override
public int getColorFromItemstack( @Nonnull ItemStack stack, int layer )
switch( layer )
{
switch( layer )
case 0:
default:
return 0xFFFFFF;
case 1:
{
case 0:
default:
return 0xFFFFFF;
case 1:
{
// Frame colour
int colour = ComputerCraft.Items.pocketComputer.getColour( stack );
return colour == -1 ? 0xFFFFFF : colour;
}
case 2:
{
// Light colour
int colour = ComputerCraft.Items.pocketComputer.getLightState( stack );
return colour == -1 ? Colour.Black.getHex() : colour;
}
// Frame colour
int colour = ComputerCraft.Items.pocketComputer.getColour( stack );
return colour == -1 ? 0xFFFFFF : colour;
}
case 2:
{
// Light colour
int colour = ComputerCraft.Items.pocketComputer.getLightState( stack );
return colour == -1 ? Colour.Black.getHex() : colour;
}
}
}, ComputerCraft.Items.pocketComputer );
@ -309,7 +305,7 @@ public Object getFixedWidthFontRenderer()
@Override
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 );
if( info.size() > 0 ) {
return info.get( 0 );
@ -399,14 +395,7 @@ public void handlePacket( final ComputerCraftPacket packet, final EntityPlayer p
}
else
{
listener.addScheduledTask( new Runnable()
{
@Override
public void run()
{
processPacket( packet, player );
}
} );
listener.addScheduledTask( () -> processPacket( packet, player ) );
}
}
break;

View File

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

View File

@ -96,9 +96,9 @@ public int hashCode()
public TurtleSmartItemModel()
{
m_cachedModels = new HashMap<TurtleModelCombination, IBakedModel>();
m_cachedModels = new HashMap<>();
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
@Override

View File

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

View File

@ -26,7 +26,7 @@ public class HTTPAPI implements ILuaAPI
public HTTPAPI( IAPIEnvironment environment )
{
m_apiEnvironment = environment;
m_httpTasks = new ArrayList<HTTPTask>();
m_httpTasks = new ArrayList<>();
}
@Override
@ -103,7 +103,7 @@ public Object[] callMethod( @Nonnull ILuaContext context, int method, @Nonnull O
Map<Object, Object> table = optTable( args, 2, null );
if( table != null )
{
headers = new HashMap<String, String>( table.size() );
headers = new HashMap<>( table.size() );
for( Object key : table.keySet() )
{
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_nextTimerToken = 0;
m_nextAlarmToken = 0;
m_timers = new HashMap<Integer, Timer>();
m_alarms = new HashMap<Integer, Alarm>();
m_timers = new HashMap<>();
m_alarms = new HashMap<>();
}
// ILuaAPI implementation
@ -303,49 +303,56 @@ public Object[] callMethod( @Nonnull ILuaContext context, int method, @Nonnull O
{
// time
String param = optString( args, 0, "ingame" );
if (param.equals("utc")) {
// Get Hour of day (UTC)
Calendar c = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
return new Object[] {getTimeForCalendar(c)};
} else if (param.equals("local")) {
// Get Hour of day (local time)
Calendar c = Calendar.getInstance();
return new Object[] {getTimeForCalendar(c)};
} else if (param.equals("ingame")) {
// Get ingame hour
synchronized (m_alarms) {
return new Object[]{m_time};
switch( param )
{
case "utc":
{
// Get Hour of day (UTC)
Calendar c = Calendar.getInstance( TimeZone.getTimeZone( "UTC" ) );
return new Object[] { getTimeForCalendar( c ) };
}
} else {
throw new LuaException("Unsupported operation");
case "local":
{
// Get Hour of day (local time)
Calendar c = Calendar.getInstance();
return new Object[] { getTimeForCalendar( c ) };
}
case "ingame":
// Get ingame hour
synchronized( m_alarms )
{
return new Object[] { m_time };
}
default:
throw new LuaException( "Unsupported operation" );
}
}
case 12:
{
// day
String param = optString( args, 0, "ingame" );
if (param.equals("utc")) {
// Get numbers of days since 1970-01-01 (utc)
Calendar c = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
return new Object[] {getDayForCalendar(c)};
} else if (param.equals("local")) {
// Get numbers of days since 1970-01-01 (local time)
Calendar c = Calendar.getInstance();
return new Object[] {getDayForCalendar(c)};
} else if (param.equals("ingame")){
// Get game day
synchronized (m_alarms) {
return new Object[]{m_day};
switch( param )
{
case "utc":
{
// Get numbers of days since 1970-01-01 (utc)
Calendar c = Calendar.getInstance( TimeZone.getTimeZone( "UTC" ) );
return new Object[] { getDayForCalendar( c ) };
}
} else {
throw new LuaException("Unsupported operation");
case "local":
{
// Get numbers of days since 1970-01-01 (local time)
Calendar c = Calendar.getInstance();
return new Object[] { getDayForCalendar( c ) };
}
case "ingame":
// Get game day
synchronized( m_alarms )
{
return new Object[] { m_day };
}
default:
throw new LuaException( "Unsupported operation" );
}
}
case 13:
@ -378,26 +385,30 @@ public Object[] callMethod( @Nonnull ILuaContext context, int method, @Nonnull O
{
// epoch
String param = optString( args, 0, "ingame" );
if (param.equals("utc")) {
// Get utc epoch
Calendar c = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
return new Object[] {getEpochForCalendar(c)};
} else if (param.equals("local")) {
// Get local epoch
Calendar c = Calendar.getInstance();
return new Object[] {getEpochForCalendar(c)};
} else if (param.equals("ingame")){
// Get in-game epoch
synchronized (m_alarms) {
return new Object[] {
m_day * 86400000 + (int)(m_time * 3600000.0f)
};
switch( param )
{
case "utc":
{
// Get utc epoch
Calendar c = Calendar.getInstance( TimeZone.getTimeZone( "UTC" ) );
return new Object[] { getEpochForCalendar( c ) };
}
} else {
throw new LuaException("Unsupported operation");
case "local":
{
// Get local epoch
Calendar c = Calendar.getInstance();
return new Object[] { getEpochForCalendar( c ) };
}
case "ingame":
// Get in-game epoch
synchronized( m_alarms )
{
return new Object[] {
m_day * 86400000 + (int) (m_time * 3600000.0f)
};
}
default:
throw new LuaException( "Unsupported operation" );
}
}
default:

View File

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

View File

@ -78,7 +78,7 @@ public Object[] callMethod( @Nonnull ILuaContext context, int method, @Nonnull O
case 0:
{
// 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 )
{
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_machine = null;
m_apis = new ArrayList<ILuaAPI>();
m_apis = new ArrayList<>();
m_apiEnvironment = new APIEnvironment( this );
m_internalOutput = new int[6];

View File

@ -31,9 +31,9 @@ public class ComputerThread
{
m_lock = new Object();
m_thread = null;
m_computerTasks = new WeakHashMap<Object, LinkedBlockingQueue<ITask>>();
m_computerTasksPending = new ArrayList<LinkedBlockingQueue<ITask>>();
m_computerTasksActive = new ArrayList<LinkedBlockingQueue<ITask>>();
m_computerTasks = new WeakHashMap<>();
m_computerTasksPending = new ArrayList<>();
m_computerTasksActive = new ArrayList<>();
m_defaultQueue = new Object();
m_monitor = new Object();
m_running = false;
@ -50,126 +50,123 @@ public static void start()
return;
}
m_thread = new Thread( new Runnable() {
public void run()
m_thread = new Thread( () ->
{
while( true )
{
while( true )
synchronized( m_computerTasksPending )
{
synchronized( m_computerTasksPending )
if (!m_computerTasksPending.isEmpty())
{
if (!m_computerTasksPending.isEmpty())
Iterator<LinkedBlockingQueue<ITask>> it = m_computerTasksPending.iterator();
while(it.hasNext())
{
Iterator<LinkedBlockingQueue<ITask>> it = m_computerTasksPending.iterator();
while(it.hasNext())
LinkedBlockingQueue<ITask> queue = it.next();
if (!m_computerTasksActive.contains(queue))
{
LinkedBlockingQueue<ITask> queue = it.next();
if (!m_computerTasksActive.contains(queue))
{
m_computerTasksActive.add(queue);
}
it.remove();
m_computerTasksActive.add(queue);
}
/*
m_computerTasksActive.addAll(m_computerTasksPending); // put any that have been added since
m_computerTasksPending.clear();
*/
it.remove();
}
/*
m_computerTasksActive.addAll(m_computerTasksPending); // put any that have been added since
m_computerTasksPending.clear();
*/
}
}
Iterator<LinkedBlockingQueue<ITask>> it = m_computerTasksActive.iterator();
while (it.hasNext())
{
LinkedBlockingQueue<ITask> queue = it.next();
if (queue == null || queue.isEmpty()) // we don't need the blocking part of the queue. Null check to ensure it exists due to a weird NPE I got
{
continue;
}
synchronized( m_lock )
{
if( m_stopped )
{
m_running = false;
m_thread = null;
return;
}
}
Iterator<LinkedBlockingQueue<ITask>> it = m_computerTasksActive.iterator();
while (it.hasNext())
try
{
LinkedBlockingQueue<ITask> queue = it.next();
if (queue == null || queue.isEmpty()) // we don't need the blocking part of the queue. Null check to ensure it exists due to a weird NPE I got
{
continue;
}
synchronized( m_lock )
{
if( m_stopped )
{
m_running = false;
m_thread = null;
return;
}
}
try
{
final ITask task = queue.take();
final ITask task = queue.take();
// Create the task
Thread worker = new Thread( new Runnable() {
public void run() {
try {
task.execute();
} catch( Throwable e ) {
ComputerCraft.log.error( "Error running task", e );
}
}
} );
// Run the task
worker.setDaemon(true);
worker.start();
worker.join( 7000 );
if( worker.isAlive() )
// Create the task
Thread worker = new Thread( () ->
{
try {
task.execute();
} catch( Throwable e ) {
ComputerCraft.log.error( "Error running task", e );
}
} );
// Run the task
worker.setDaemon(true);
worker.start();
worker.join( 7000 );
if( worker.isAlive() )
{
// Task ran for too long
// Initiate escape plan
Computer computer = task.getOwner();
if( computer != null )
{
// Task ran for too long
// Initiate escape plan
Computer computer = task.getOwner();
if( computer != null )
{
// Step 1: Soft abort
computer.abort( false );
worker.join( 1500 );
if( worker.isAlive() )
{
// Step 2: Hard abort
computer.abort( true );
worker.join( 1500 );
}
}
// Step 3: abandon
// Step 1: Soft abort
computer.abort( false );
worker.join( 1500 );
if( worker.isAlive() )
{
// ComputerCraft.log.warn( "Failed to abort Computer " + computer.getID() + ". Dangling lua thread could cause errors." );
worker.interrupt();
// Step 2: Hard abort
computer.abort( true );
worker.join( 1500 );
}
}
}
// Step 3: abandon
if( worker.isAlive() )
{
// ComputerCraft.log.warn( "Failed to abort Computer " + computer.getID() + ". Dangling lua thread could cause errors." );
worker.interrupt();
}
}
}
catch( InterruptedException e )
{
continue;
}
synchronized (queue)
{
if (queue.isEmpty())
{
it.remove();
}
}
}
while (m_computerTasksActive.isEmpty() && m_computerTasksPending.isEmpty())
{
synchronized (m_monitor)
{
try
{
m_monitor.wait();
}
catch( InterruptedException e )
{
continue;
}
synchronized (queue)
{
if (queue.isEmpty())
{
it.remove();
}
}
}
while (m_computerTasksActive.isEmpty() && m_computerTasksPending.isEmpty())
{
synchronized (m_monitor)
{
try
{
m_monitor.wait();
}
catch( InterruptedException e )
{
}
}
}
}
@ -207,7 +204,7 @@ public static void queueTask( ITask _task, Computer computer )
if (queue == null)
{
m_computerTasks.put(queueObject, queue = new LinkedBlockingQueue<ITask>(256));
m_computerTasks.put(queueObject, queue = new LinkedBlockingQueue<>( 256 ));
}
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_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 long m_nextUnusedTaskID = 0;

View File

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

View File

@ -9,7 +9,6 @@
import dan200.computercraft.ComputerCraft;
import dan200.computercraft.api.filesystem.IMount;
import dan200.computercraft.api.filesystem.IWritableMount;
import net.minecraftforge.fml.common.FMLLog;
import java.io.*;
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>() );
public FileSystem( String rootLabel, IMount rootMount ) throws FileSystemException
@ -424,7 +423,7 @@ public synchronized String[] list( String path ) throws FileSystemException
MountWrapper mount = getMount( path );
// Gets a list of the files in the mount
List<String> list = new ArrayList<String>();
List<String> list = new ArrayList<>();
mount.list( path, list );
// 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
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 );
// Return matches
@ -585,7 +584,7 @@ private synchronized void copyRecursive( String sourcePath, MountWrapper sourceM
destinationMount.makeDirectory( destinationPath );
// Copy the source contents into it
List<String> sourceChildren = new ArrayList<String>();
List<String> sourceChildren = new ArrayList<>();
sourceMount.list( sourcePath, 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
String[] parts = path.split("/");
Stack<String> outputParts = new Stack<String>();
Stack<String> outputParts = new Stack<>();
for( String part : parts )
{
if( part.length() == 0 || part.equals( "." ) )

View File

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

View File

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

View File

@ -88,7 +88,7 @@ public final void dropAllItems( World world, BlockPos pos, boolean creative )
TileEntity tile = world.getTileEntity( pos );
if( tile != null && tile instanceof TileGeneric )
{
TileGeneric generic = (TileGeneric)tile;
TileGeneric generic = (TileGeneric) tile;
generic.getDroppedItems( drops, creative );
}
@ -234,7 +234,7 @@ public final AxisAlignedBB getCollisionBoundingBox( IBlockState state, @Nonnull
TileGeneric generic = (TileGeneric)tile;
// Get collision bounds
List<AxisAlignedBB> collision = new ArrayList<AxisAlignedBB>( 1 );
List<AxisAlignedBB> collision = new ArrayList<>( 1 );
generic.getCollisionBounds( collision );
// Return the union of the collision bounds
@ -262,7 +262,7 @@ public final void addCollisionBoxToList( IBlockState state, @Nonnull World world
TileGeneric generic = (TileGeneric)tile;
// Get collision bounds
List<AxisAlignedBB> collision = new ArrayList<AxisAlignedBB>( 1 );
List<AxisAlignedBB> collision = new ArrayList<>( 1 );
generic.getCollisionBounds( collision );
// Add collision bounds to list

View File

@ -9,7 +9,6 @@
import com.google.common.collect.ImmutableMap;
import dan200.computercraft.ComputerCraft;
import dan200.computercraft.api.lua.ILuaContext;
import dan200.computercraft.api.lua.ILuaTask;
import dan200.computercraft.api.lua.LuaException;
import dan200.computercraft.core.apis.ILuaAPI;
import dan200.computercraft.shared.computer.blocks.TileCommandComputer;
@ -81,7 +80,7 @@ public String[] getMethodNames()
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 );
return result;
}
@ -123,11 +122,11 @@ private Object getBlockInfo( World world, BlockPos pos )
String name = Block.REGISTRY.getNameForObject( block ).toString();
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( "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() )
{
String propertyName = entry.getKey().getName();
@ -155,68 +154,50 @@ public Object[] callMethod( @Nonnull ILuaContext context, int method, @Nonnull O
{
// exec
final String command = getString( arguments, 0 );
return context.executeMainThreadTask( new ILuaTask()
{
@Override
public Object[] execute() throws LuaException
{
return doCommand( command );
}
} );
return context.executeMainThreadTask( () -> doCommand( command ) );
}
case 1:
{
// execAsync
final String command = getString( arguments, 0 );
long taskID = context.issueMainThreadTask( new ILuaTask()
{
@Override
public Object[] execute() throws LuaException
{
return doCommand( command );
}
} );
long taskID = context.issueMainThreadTask( () -> doCommand( command ) );
return new Object[] { taskID };
}
case 2:
{
// list
return context.executeMainThreadTask( new ILuaTask()
return context.executeMainThreadTask( () ->
{
@Override
public Object[] execute() throws LuaException
int i = 1;
Map<Object, Object> result = new HashMap<>();
MinecraftServer server = m_computer.getWorld().getMinecraftServer();
if( server != null )
{
int i = 1;
Map<Object, Object> result = new HashMap<Object, Object>();
MinecraftServer server = m_computer.getWorld().getMinecraftServer();
if( server != null )
ICommandManager commandManager = server.getCommandManager();
ICommandSender commmandSender = m_computer.getCommandSender();
Map<String, ICommand> commands = commandManager.getCommands();
for( Map.Entry<String, ICommand> entry : commands.entrySet() )
{
ICommandManager commandManager = server.getCommandManager();
ICommandSender commmandSender = m_computer.getCommandSender();
Map<String, ICommand> commands = commandManager.getCommands();
for( Map.Entry<String, ICommand> entry : commands.entrySet() )
String name = entry.getKey();
ICommand command = entry.getValue();
try
{
String name = entry.getKey();
ICommand command = entry.getValue();
try
if( command.checkPermission( server, commmandSender ) )
{
if( command.checkPermission( server, commmandSender ) )
{
result.put( i++, name );
}
result.put( i++, name );
}
catch( Throwable t )
}
catch( Throwable t )
{
// Ignore buggy command
if( ComputerCraft.logPeripheralErrors )
{
// Ignore buggy command
if( ComputerCraft.logPeripheralErrors )
{
ComputerCraft.log.error( "Error checking permissions of command.", t );
}
ComputerCraft.log.error( "Error checking permissions of command.", t );
}
}
}
return new Object[]{ result };
}
return new Object[]{ result };
} );
}
case 3:
@ -235,46 +216,42 @@ public Object[] execute() throws LuaException
final int maxx = getInt( arguments, 3 );
final int maxy = getInt( arguments, 4 );
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
World world = m_computer.getWorld();
BlockPos min = new BlockPos(
Math.min( minx, maxx ),
Math.min( miny, maxy ),
Math.min( minz, maxz )
);
BlockPos max = new BlockPos(
Math.max( minx, maxx ),
Math.max( miny, maxy ),
Math.max( minz, maxz )
);
if( !WorldUtil.isBlockInWorld( world, min ) || !WorldUtil.isBlockInWorld( world, max ) )
{
// Get the details of the block
World world = m_computer.getWorld();
BlockPos min = new BlockPos(
Math.min( minx, maxx ),
Math.min( miny, maxy ),
Math.min( minz, maxz )
);
BlockPos max = new BlockPos(
Math.max( minx, maxx ),
Math.max( miny, maxy ),
Math.max( minz, maxz )
);
if( !WorldUtil.isBlockInWorld( world, min ) || !WorldUtil.isBlockInWorld( world, max ) )
throw new LuaException( "Co-ordinates out or range" );
}
if( ( max.getX() - min.getX() + 1 ) * ( max.getY() - min.getY() + 1 ) * ( max.getZ() - min.getZ() + 1 ) > 4096 )
{
throw new LuaException( "Too many blocks" );
}
int i=1;
Map<Object, Object> results = new HashMap<>();
for( int y=min.getY(); y<= max.getY(); ++y )
{
for( int z = min.getZ(); z <= max.getZ(); ++z )
{
throw new LuaException( "Co-ordinates out or range" );
}
if( ( max.getX() - min.getX() + 1 ) * ( max.getY() - min.getY() + 1 ) * ( max.getZ() - min.getZ() + 1 ) > 4096 )
{
throw new LuaException( "Too many blocks" );
}
int i=1;
Map<Object, Object> results = new HashMap<Object, Object>();
for( int y=min.getY(); y<= max.getY(); ++y )
{
for( int z = min.getZ(); z <= max.getZ(); ++z )
for( int x = min.getX(); x <= max.getX(); ++x )
{
for( int x = min.getX(); x <= max.getX(); ++x )
{
BlockPos pos = new BlockPos( x, y, z );
results.put( i++, getBlockInfo( world, pos ) );
}
BlockPos pos = new BlockPos( x, y, z );
results.put( i++, getBlockInfo( world, pos ) );
}
}
return new Object[]{ results };
}
return new Object[]{ results };
} );
}
case 5:
@ -283,22 +260,18 @@ public Object[] execute() throws LuaException
final int x = getInt( arguments, 0 );
final int y = getInt( arguments, 1 );
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
World world = m_computer.getWorld();
BlockPos position = new BlockPos( x, y, z );
if( WorldUtil.isBlockInWorld( world, position ) )
{
// Get the details of the block
World world = m_computer.getWorld();
BlockPos position = new BlockPos( x, y, z );
if( WorldUtil.isBlockInWorld( world, position ) )
{
return new Object[]{ getBlockInfo( world, position ) };
}
else
{
throw new LuaException( "co-ordinates out or range" );
}
return new Object[]{ getBlockInfo( world, position ) };
}
else
{
throw new LuaException( "co-ordinates out or range" );
}
} );
}

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
public boolean equals( IPeripheral other )
{

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -131,7 +131,7 @@ public Object[] callMethod( @Nonnull IComputerAccess computer, @Nonnull ILuaCont
synchronized( m_entity.m_peripheralsByName )
{
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() )
{
table.put( idx++, name );
@ -161,7 +161,7 @@ public Object[] callMethod( @Nonnull IComputerAccess computer, @Nonnull ILuaCont
String[] methodNames = m_entity.getMethodNamesRemote( getString( arguments, 0 ) );
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 ) {
table.put( i+1, methodNames[i] );
}
@ -247,14 +247,14 @@ public boolean equals( IPeripheral other )
public TileCable()
{
m_receivers = new HashSet<IPacketReceiver>();
m_transmitQueue = new LinkedList<PacketWrapper>();
m_receivers = new HashSet<>();
m_transmitQueue = new LinkedList<>();
m_peripheralAccessAllowed = false;
m_attachedPeripheralID = -1;
m_peripheralsByName = new HashMap<String, IPeripheral>();
m_peripheralWrappersByName = new HashMap<String, RemotePeripheralWrapper>();
m_peripheralsByName = new HashMap<>();
m_peripheralWrappersByName = new HashMap<>();
m_peripheralsKnown = false;
m_destroyed = false;
@ -685,13 +685,11 @@ public void networkChanged()
if( !m_destroyed )
{
// If this modem is alive, rebuild the network
searchNetwork( new ICableVisitor() {
public void visit( TileCable modem, int distance )
searchNetwork( ( modem, distance ) ->
{
synchronized( modem.m_peripheralsByName )
{
synchronized( modem.m_peripheralsByName )
{
modem.m_peripheralsKnown = false;
}
modem.m_peripheralsKnown = false;
}
} );
}
@ -733,13 +731,11 @@ private PacketWrapper( Packet m_packet, double m_range )
private void dispatchPacket( final PacketWrapper packet )
{
searchNetwork( new ICableVisitor() {
public void visit( TileCable modem, int distance )
searchNetwork( ( modem, 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_methods != null );
m_methodMap = new HashMap<String, Integer>();
m_methodMap = new HashMap<>();
for( int i=0; i<m_methods.length; ++i ) {
if( m_methods[i] != null ) {
m_methodMap.put( m_methods[i], i );
@ -876,22 +872,20 @@ private void findPeripherals( )
synchronized( m_peripheralsByName )
{
// Collect the peripherals
final Map<String, IPeripheral> newPeripheralsByName = new HashMap<String, IPeripheral>();
final Map<String, IPeripheral> newPeripheralsByName = new HashMap<>();
if( getPeripheralType() == PeripheralType.WiredModemWithCable )
{
searchNetwork( new ICableVisitor() {
public void visit( TileCable modem, int distance )
searchNetwork( ( modem, distance ) ->
{
if( modem != origin )
{
IPeripheral peripheral = modem.getConnectedPeripheral();
String periphName = modem.getConnectedPeripheralName();
if( peripheral != null && periphName != null )
{
if( modem != origin )
{
IPeripheral peripheral = modem.getConnectedPeripheral();
String periphName = modem.getConnectedPeripheralName();
if( peripheral != null && periphName != null )
{
newPeripheralsByName.put( periphName, peripheral );
}
}
newPeripheralsByName.put( periphName, peripheral );
}
}
} );
}
//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 )
{
int searchID = ++s_nextUniqueSearchID;
Queue<SearchLoc> queue = new LinkedList<SearchLoc>();
Queue<SearchLoc> queue = new LinkedList<>();
enqueue( queue, getWorld(), getPos(), 1 );
int visited = 0;

View File

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

View File

@ -65,7 +65,7 @@ public class TileMonitor extends TilePeripheralBase
public TileMonitor()
{
m_computers = new HashSet<IComputerAccess>();
m_computers = new HashSet<>();
m_destroyed = 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
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
@Override
public String getType()

View File

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

View File

@ -8,7 +8,6 @@
import dan200.computercraft.ComputerCraft;
import dan200.computercraft.api.lua.ILuaContext;
import dan200.computercraft.api.lua.ILuaTask;
import dan200.computercraft.api.lua.LuaException;
import dan200.computercraft.api.pocket.IPocketUpgrade;
import dan200.computercraft.core.apis.ILuaAPI;
@ -72,84 +71,76 @@ public Object[] callMethod( @Nonnull ILuaContext context, int method, @Nonnull O
{
case 0:
// 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) )
{
throw new LuaException( "Cannot find player" );
}
EntityPlayer player = (EntityPlayer) m_computer.getEntity();
InventoryPlayer inventory = player.inventory;
IPocketUpgrade previousUpgrade = m_computer.getUpgrade();
// Attempt to find the upgrade, starting in the main segment, and then looking in the opposite
// one. We start from the position the item is currently in and loop round to the start.
IPocketUpgrade newUpgrade = findUpgrade( inventory.mainInventory, inventory.currentItem, previousUpgrade );
if( newUpgrade == null )
{
newUpgrade = findUpgrade( inventory.offHandInventory, 0, previousUpgrade );
}
if( newUpgrade == null ) throw new LuaException( "Cannot find a valid upgrade" );
// Remove the current upgrade
if( previousUpgrade != null )
{
ItemStack stack = previousUpgrade.getCraftingItem();
if( !stack.isEmpty() )
{
stack = InventoryUtil.storeItems( stack, new PlayerMainInvWrapper( inventory ), inventory.currentItem );
if( !stack.isEmpty() )
{
WorldUtil.dropItemStack( stack, player.getEntityWorld(), player.posX, player.posY, player.posZ );
}
}
}
// Set the new upgrade
m_computer.setUpgrade( newUpgrade );
return null;
throw new LuaException( "Cannot find player" );
}
} );
case 1:
// unequipBack
return context.executeMainThreadTask( new ILuaTask()
{
@Override
public Object[] execute() throws LuaException
EntityPlayer player = (EntityPlayer) m_computer.getEntity();
InventoryPlayer inventory = player.inventory;
IPocketUpgrade previousUpgrade = m_computer.getUpgrade();
// Attempt to find the upgrade, starting in the main segment, and then looking in the opposite
// one. We start from the position the item is currently in and loop round to the start.
IPocketUpgrade newUpgrade = findUpgrade( inventory.mainInventory, inventory.currentItem, previousUpgrade );
if( newUpgrade == null )
{
if( !(m_computer.getEntity() instanceof EntityPlayer) )
{
throw new LuaException( "Cannot find player" );
}
EntityPlayer player = (EntityPlayer) m_computer.getEntity();
InventoryPlayer inventory = player.inventory;
IPocketUpgrade previousUpgrade = m_computer.getUpgrade();
if( previousUpgrade == null ) throw new LuaException( "Nothing to unequip" );
m_computer.setUpgrade( null );
newUpgrade = findUpgrade( inventory.offHandInventory, 0, previousUpgrade );
}
if( newUpgrade == null ) throw new LuaException( "Cannot find a valid upgrade" );
// Remove the current upgrade
if( previousUpgrade != null )
{
ItemStack stack = previousUpgrade.getCraftingItem();
if( !stack.isEmpty() )
{
stack = InventoryUtil.storeItems( stack, new PlayerMainInvWrapper( inventory ), inventory.currentItem );
if( stack.isEmpty() )
if( !stack.isEmpty() )
{
WorldUtil.dropItemStack( stack, player.getEntityWorld(), player.posX, player.posY, player.posZ );
}
}
return null;
}
// Set the new upgrade
m_computer.setUpgrade( newUpgrade );
return null;
} );
case 1:
// unequipBack
return context.executeMainThreadTask( () ->
{
if( !(m_computer.getEntity() instanceof EntityPlayer) )
{
throw new LuaException( "Cannot find player" );
}
EntityPlayer player = (EntityPlayer) m_computer.getEntity();
InventoryPlayer inventory = player.inventory;
IPocketUpgrade previousUpgrade = m_computer.getUpgrade();
if( previousUpgrade == null ) throw new LuaException( "Nothing to unequip" );
m_computer.setUpgrade( null );
ItemStack stack = previousUpgrade.getCraftingItem();
if( !stack.isEmpty() )
{
stack = InventoryUtil.storeItems( stack, new PlayerMainInvWrapper( inventory ), inventory.currentItem );
if( stack.isEmpty() )
{
WorldUtil.dropItemStack( stack, player.getEntityWorld(), player.posX, player.posY, player.posZ );
}
}
return null;
} );
default:
return null;

View File

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

View File

@ -9,7 +9,6 @@
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.item.ItemStack;
import net.minecraft.util.ResourceLocation;
import net.minecraft.world.World;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
@ -79,10 +78,4 @@ else if( entity != null )
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.item.ItemStack;
import net.minecraft.util.ResourceLocation;
import net.minecraft.world.World;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
@ -76,12 +75,4 @@ else if ( entity != null )
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()
{
m_legacyTurtleUpgrades = new HashMap<Integer, ITurtleUpgrade>();
m_turtleUpgrades = new HashMap<String, ITurtleUpgrade>();
m_dropConsumers = new WeakHashMap<Entity, IEntityDropConsumer>();
m_legacyTurtleUpgrades = new HashMap<>();
m_turtleUpgrades = new HashMap<>();
m_dropConsumers = new WeakHashMap<>();
}
// ICCTurtleProxy implementation

View File

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

View File

@ -6,7 +6,6 @@
package dan200.computercraft.shared.turtle.apis;
import com.google.common.base.Optional;
import dan200.computercraft.api.lua.ILuaContext;
import dan200.computercraft.api.lua.LuaException;
import dan200.computercraft.api.turtle.ITurtleAccess;
@ -21,6 +20,7 @@
import javax.annotation.Nonnull;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
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 );
if( side == null )
{
return Optional.absent();
return Optional.empty();
}
else if( side.equalsIgnoreCase( "left" ) )
{
@ -435,7 +435,7 @@ public Object[] callMethod( @Nonnull ILuaContext context, int method, @Nonnull O
int damage = stack.getItemDamage();
int count = stack.getCount();
Map<Object, Object> table = new HashMap<Object, Object>();
Map<Object, Object> table = new HashMap<>();
table.put( "name", name );
table.put( "damage", damage );
table.put( "count", count );

View File

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

View File

@ -41,7 +41,7 @@
public class TurtleBrain implements ITurtleAccess
{
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()
{
@ -75,7 +75,7 @@ public static void setClientBrain( int instanceID, TurtleBrain 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_commandQueue = new LinkedList<TurtleCommandQueueEntry>();
m_commandQueue = new LinkedList<>();
m_commandsIssued = 0;
m_upgrades = new HashMap<TurtleSide, ITurtleUpgrade>();
m_peripherals = new HashMap<TurtleSide, IPeripheral>();
m_upgradeNBTData = new HashMap<TurtleSide, NBTTagCompound>();
m_upgrades = new HashMap<>();
m_peripherals = new HashMap<>();
m_upgradeNBTData = new HashMap<>();
m_selectedSlot = 0;
m_fuelLevel = 0;

View File

@ -6,10 +6,11 @@
package dan200.computercraft.shared.turtle.core;
import com.google.common.base.Optional;
import dan200.computercraft.api.turtle.TurtleSide;
import dan200.computercraft.api.turtle.TurtleVerb;
import java.util.Optional;
public class TurtleDigCommand extends TurtleToolCommand
{
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();
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( "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() )
{
String propertyName = entry.getKey().getName();
@ -79,10 +79,10 @@ public TurtleCommandResult execute( @Nonnull ITurtleAccess turtle )
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( "metadata", 0 );
table.put( "state", new HashMap<Object, Object>() );
table.put( "state", new HashMap<>() );
return TurtleCommandResult.success( new Object[]{ table } );
}
return TurtleCommandResult.failure( "No block to inspect" );

View File

@ -12,7 +12,6 @@
import dan200.computercraft.api.turtle.TurtleAnimation;
import dan200.computercraft.api.turtle.TurtleCommandResult;
import dan200.computercraft.shared.util.DirectionUtil;
import dan200.computercraft.shared.util.IEntityDropConsumer;
import dan200.computercraft.shared.util.InventoryUtil;
import dan200.computercraft.shared.util.WorldUtil;
import net.minecraft.block.Block;
@ -225,16 +224,12 @@ private static ItemStack deployOnEntity( @Nonnull ItemStack stack, final ITurtle
// Start claiming entity drops
Entity hitEntity = hit.getKey();
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() );
if( !remainder.isEmpty() )
{
ItemStack remainder = InventoryUtil.storeItems( drop, turtle.getItemHandler(), turtle.getSelectedSlot() );
if( !remainder.isEmpty() )
{
WorldUtil.dropItemStack( remainder, world, position, turtle.getDirection().getOpposite() );
}
WorldUtil.dropItemStack( remainder, world, position, turtle.getDirection().getOpposite() );
}
} );

View File

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

View File

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

View File

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

View File

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

View File

@ -72,16 +72,6 @@ public Object[] callMethod( @Nonnull IComputerAccess computer, @Nonnull ILuaCont
}
}
}
@Override
public void attach( @Nonnull IComputerAccess computer )
{
}
@Override
public void detach( @Nonnull IComputerAccess computer )
{
}
@Override
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 );
}
}
@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() )
{
// 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 )
{
return results;

View File

@ -12,7 +12,6 @@
import dan200.computercraft.shared.turtle.core.TurtleBrain;
import dan200.computercraft.shared.turtle.core.TurtlePlaceCommand;
import dan200.computercraft.shared.turtle.core.TurtlePlayer;
import dan200.computercraft.shared.util.IEntityDropConsumer;
import dan200.computercraft.shared.util.InventoryUtil;
import dan200.computercraft.shared.util.WorldUtil;
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
@Override
public TurtleCommandResult useTool( @Nonnull ITurtleAccess turtle, @Nonnull TurtleSide side, @Nonnull TurtleVerb verb, @Nonnull EnumFacing direction )
@ -186,16 +180,12 @@ private TurtleCommandResult attack( final ITurtleAccess turtle, EnumFacing direc
// Start claiming entity drops
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() );
if( !remainder.isEmpty() )
{
ItemStack remainder = InventoryUtil.storeItems( drop, turtle.getItemHandler(), turtle.getSelectedSlot() );
if( !remainder.isEmpty() )
{
WorldUtil.dropItemStack( remainder, world, position, turtle.getDirection().getOpposite() );
}
WorldUtil.dropItemStack( remainder, world, position, turtle.getDirection().getOpposite() );
}
} );

View File

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

View File

@ -99,7 +99,7 @@ private static Object fromNBTTag( NBTBase tag )
{
NBTTagCompound c = (NBTTagCompound)tag;
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 )
{
Object key = fromNBTTag( c.getTag( "k" + Integer.toString( i ) ) );