Binary Search a sorted array, why return a negative number, why -low -1?

A simple question, I just want to know why when key = 12, return -6? I know 12 is not in the array, but why is it 6?
I want a detailed explanation.
I know low = 0;
when is not found, return -low -1; but i don’t understand why.

int[] list = {2, 4, 7, 10, 11, 45, 50, 59, 60, 66, 69, 70, 79};
        System.out.println("1. Index is " + Arrays.binarySearch(list, 11));
        System.out.println("2. Index is " + Arrays.binarySearch(list, 12));

Print:

 1. Index is 4
 2. Index is -6

How to remove an especific object from an ArrayList of Integers in Java?

I looked a lot through StackOverflow. I seen the same questions and answers over and over again, but they don’t address the real problem.

There is Java. Java has ArrayList. ArrayList has the method remove().
The JDK9 Documentation says it can take the index as a parameter or the object itself that you want to be removed.
The following code does not work though.

import java.util.*;

public class Tea {
    public static void main (String[] args) {

        ArrayList<Integer> myList = new ArrayList<Integer>();

        myList.add(69);

        myList.remove( ( (int) 69 ) );

        System.out.println(myList);

    }
}

It compiles, but it does not run and so it gives the following error message:

“Exception in thread “main” java.lang.IndexOutOfBoundsException: Index 69 out-of-bounds for length 1
at java.base/jdk.internal.util.Preconditions.outOfBounds(Preconditions.java:64)
at java.base/jdk.internal.util.Preconditions.outOfBoundsCheckIndex(Preconditions.java:70)
at java.base/jdk.internal.util.Preconditions.checkIndex(Preconditions.java:248)
at java.base/java.util.Objects.checkIndex(Objects.java:372)
at java.base/java.util.ArrayList.remove(ArrayList.java:517)
at Tea.main(Tea.java:10)”

The JVM is obviously taking the argument as the index and not the object.
Here’s the suggested solution found on the other websites:

myList.remove(new Integer(69));

It doesn’t even compile into bytecode:

“Note: Tea.java uses or overrides a deprecated API.
Note: Recompile with -Xlint:deprecation for details.”

Compiling with:
$javac Tea.java -Xlint:deprecation

Gives us:

warning: [deprecation] Integer(int) in Integer has been deprecated
    myList.remove(new Integer(69));

I looked in the deprecated list on the documentation. Couldn’t find it.
Looked the method’s documentation to have it explained to me. No explanation.

All I want to do is use the parameter as an object and not the index and get my return as a boolean (documentation says so) if it was in the ArrayList and has been removed.

Is there a way to do this? Or is it deprecated and my ctrl + f search on the deprecated methods not enough?

Encapsulation Java Coding Error

I am working on the code but facing an error. My problem is that I have initialized this.tonner_Lvl to 35 but “System.out.println(this.tonner_Lvl )” prints out 0.

public class Printer {
    private int tonner_Lvl;
    private int pgs;
    private boolean is_duplex;
    Scanner sc = new Scanner(System.in);

public Printer(int tonner_Lvl, int pgs, boolean is_duplex) {

    if(this.tonner_Lvl <= 0 ) {
        this.tonner_Lvl = 0;

    }
    else if (this.tonner_Lvl >= 100)
    {
        this.tonner_Lvl =100;
    }
    else 
        this.tonner_Lvl = tonner_Lvl;
    System.out.println(this.tonner_Lvl ); // Why is it printing 0 while I 
                                           // have initialised it
    this.pgs = pgs;
    System.out.println(this.pgs);
    this.is_duplex = is_duplex;
    System.out.println(this.is_duplex);
}


public class Main {
    public static void main(String[] args) {
        Printer printer = new Printer(35, 12, true);
       //printer.print();
        printer.tonner();

     }
 } 

How to format java string of this pattern in android Mon Jan 01 01:48:31 EAT 2018

I need to make some date manipulation using Joda library, however I do have some date string from my data source,
How can I simply format this this date string Mon Jan 01 01:48:31 EAT 2018 To DateTime

I have tried DateTimeFormatter formatter = DateTimeFormat.forPattern(" MMM d h:mm:ss yyyy a"); But it gives java.lang.IllegalArgumentException: Invalid format

Any help will be appreciated.

How to decompress a Flux (and how to write one)?

I have a requirement to read and write compressed (GZIP) streams without intermediate storage. Currently, I’m using Spring RestTemplate to do the writing, and Apache HTTP client to do the reading (see my answer here for an explanation of why RestTemplate can’t be used for reading large streams). The implementation is fairly straightforward, where I slap a GZIPInputStream on the response InputStream and move on.

Now, I’d like to switch to using Spring 5 WebClient (just because I’m not a fan of status quo). However, WebClient is reactive in nature and deals with Flux<Stuff>; I believe it’s possible to get a Flux<DataBuffer>, where DataBuffer is an abstraction over ByteBuffer. Question is, how do I decompress it on the fly without having to store the full stream in memory (OutOfMemoryError, I’m looking at you), or writing to local disk? It’s worth mentioning that WebClient uses Netty under the hood.

I’ll admit to not knowing much about (de)compression, however, I did do my research, but none of the material available online seemed particularly helpful.

compression on java nio direct buffers

Writing GZIP file with nio

Reading a GZIP file from a FileChannel (Java NIO)

(de)compressing files using NIO

Iterable gzip deflate/inflate in Java

Also related to Spring integration issue 2300

How to make Java Swing components fill available space?

I cannot seem to get my Java Swing components to work together correctly.

What I want to do, is have a JPanel fill ALL the space available inside a JTabbedPane. At the moment, my setup is as follows:

public class Gui extends JFrame {
    private final EventBus eventBus = EventBus.getInstance();
    private final ToolkitUtil toolkitUtil;
    private final Menu menu;
    private final InfoBar infoBar;
    private final JTabbedPane pane;

    ...

    private void buildLayout() {
        GridBagConstraints gbc = new GridBagConstraints();

        setJMenuBar(menu);

        add(pane, BorderLayout.CENTER);
        add(infoBar, BorderLayout.SOUTH);

        pane.addTab("Plugins", new PluginPanel());
    }
}

public class PluginPanel extends JPanel {
    private final JPanel modelPanel;
    private final JPanel editorPanel;

    public PluginPanel() {
        setLayout(new GridBagLayout());

        modelPanel = new JPanel(new GridBagLayout());
        editorPanel = new JPanel(new GridBagLayout());

        buildLayout();
    }

    private void buildLayout() {
        GridBagConstraints gbc = new GridBagConstraints();

        modelPanel.setBorder(BorderFactory.createTitledBorder("Models"));
        editorPanel.setBorder(BorderFactory.createTitledBorder("Editors"));

        gbc.gridx = 0;
        gbc.fill = GridBagConstraints.BOTH;

        modelPanel.add(new JLabel("test label"), gbc);
        add(modelPanel, gbc);

        gbc.gridx = 1;
        add(editorPanel, gbc);
    }
}

This creates a windows that is my desired size (dynamically proportional to the screen size, not included in above code). The tab panel that is placed in the center is expanded to fill all the space required, which is exactly what I want. But, the panels I add inside the tab panel are only as big as their content. If I add labels or anything, it only grows as big as the components. I want them to always be expanded to fill the tab panel.

delete full arraylist element if it has specific integer code

I have an ArrayList whose output is given as:

[, bd33b056-7a24-490f-a4bb-88cb2687facb%1514759804437%New York, USA%Florida, USA%2018-01-01%2018-01-10%UM-66%3050.0, bd33b056-7a24-490f-a4bb-88cb2687facb%1514759837907%New York, USA%California, USA%2018-01-01%2018-01-10%UM-66%8770.0]

Now I am creating a method to have a string id as parameter, when ever is matches with the id of booking it will remove that index.
The id is after first %, is there any way to find out index of that specific booking?
Here is method

public static void removeElement(String id) throws FileNotFoundException, IOException{
    BufferedReader b = new BufferedReader(new FileReader("Booking.dat"));
    String d = b.readLine();
    String[] allB = d.split("£");
    ArrayList<String> data = new ArrayList<String>(Arrays.asList(allB));
    data.remove(id);// need to have specific index of id inside the full arraylist
    System.out.println(data);
}

Protocol message contained an invalid tag 0

My goal is to create a realtime service alert feed and send it over to a server that I made in Java with an HTTP post request. The first step I did was to create a copy of the example alert feed posted here and it seems I was successfully able to do that as I was able to print it out the message. https://developers.google.com/transit/gtfs-realtime/examples/alerts

The next step that I did is to create an HTTP connection and send the feed over with the POST request. This is what I have in my client code and example here is the feed name.

String url = "https://localhost:8080";
URL obj = new URL(url);
HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
//add reuqest header
con.setRequestMethod("POST");
con.setRequestProperty("User-Agent", "Mozilla/5.0");
con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
con.setRequestProperty("Content-Type", "application/x-protobuf");
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
example.build().writeDelimitedTo(wr);
wr.flush();
wr.close();

My server code is simply this so far.

ServerSocket server = new ServerSocket(8080); 
System.out.println("Listening for connection on port 8080 ...."); 
while (true) { 
    try (Socket socket = server.accept()) {
      FeedMessage feed = FeedMessage.parseDelimitedFrom(socket.getInputStream());
      Date today = new Date(); 
      String httpResponse = "HTTP/1.1 200 OKrnrn" + today; 
      socket.getOutputStream().write(httpResponse.getBytes("UTF-8")); 
      }     
} 

The question here is that I get the Protocol message contained an invalid tag 0 on the server side. I would like some help on trying to resolve this issue. Maybe I am not parsing it correctly.

@Autowired using the wrong implementation despite @ConditionalOnProperty

I followed a tutorial I found online to use @ConditionalOnProperty with @Bean to choose an implementation for @Autowired.

For completeness (though it isn’t relevant to the issue), the purpose of this is to choose an “ICE Server List” provider – either as configured locally in a config file or using the Twilio API to get a list of STUN and TURN servers for WebRTC.

Here is the relevant code:

application.properties

ice.provider = twilio

Controller.java

@ComponentScan
@RestController
@EnableAutoConfiguration
@EnableWebSocket
public class Controller {

    @Autowired
    private IceProvider iceProvider;

    @Bean
    @ConditionalOnProperty(name = "ice.provider", havingValue = "local")
    public IceProvider localIceProvider() {
        logger.info("Creating ICE server provider - LOCAL");
        return new LocalIceProvider();
    }

    @Bean
    @ConditionalOnProperty(name = "ice.provider", havingValue = "twilio")
    public IceProvider twilioIceProvider() {
        logger.info("Creating ICE server provider - TWILIO");
        return new TwilioIceProvider();
    }
}

IceProvider.java

public interface IceProvider {
    List<ICEServer> getIceServers(String username);
}

LocalIceProvider.java

@Component
public class LocalIceProvider implements IceProvider {

    private final static Logger logger = Logger.getLogger(LocalIceProvider.class);

    @PostConstruct
    void init() {
        logger.info("Reading local ICE Server list config file");

        // ...
    }

    @Override
    public List<ICEServer> getIceServers(String username) {
        logger.info("Returning locally configured ICE servers");

        // ...    
    }
}

TwilioIceProvider.java

@Component
public class TwilioIceProvider implements IceProvider {

    private final static Logger logger = Logger.getLogger(TwilioIceProvider.class);

    @Override
    public List<ICEServer> getIceServers(String username) {
        logger.info("Doing Twilio API call and returning result");

        // ...
    }
}

Despite the application.properties setting to use the twilio provider, the application is using the local provider. However, only the twilioIceProvider factory method is being called, not the localIceProvider method.

Here is a snippet from the logs:

On application start

[2017-12-31 21:11:53 INFO ] [localhost-startStop-1] [ice.LocalIceProvider] Reading local ICE Server list config file
[2017-12-31 21:11:55 INFO ] [main] [com.example.Controller] Creating ICE server provider - TWILIO

On a request from the client that calls iceProvider.getIceServers()

[2017-12-31 21:14:40 INFO ] [http-nio-9083-exec-5] [ice.LocalIceProvider] Returning locally configured ICE servers

Since only the twilioIceProvider factory method is being called and the localIceProvider method is not, why is the LocalIceProvider being @Autowired?