Releasing elasticsearch connection - elasticsearch

I am deploying a webapp, which internally queries elasticsearch. I am creating only one connection, and I want to close it when the webapp shuts down. I am using singleton pattern for creating the ES client and how do I destroy/close ES client? When the application shuts down, will the client get closed or I have to specify it/ where should I have the code to close the connection?
This is my code:
public class ESClientManager {
public static Client client = null;
private static Settings settings = null;
private static Object mutex = new Object();
private static final String CONFIG_CLUSTER_NAME = "cluster.name";
private static final String CLUSTER_NAME = "qatool_es";
private static final String[] transportAddress = {
"127.0.0.1"
};
private static final int transportPort = 9300;
private ESClientManager() {
}
public static Client getClient() {
if (client == null) {
synchronized (mutex) {
settings = ImmutableSettings.settingsBuilder()
.put(CONFIG_CLUSTER_NAME, CLUSTER_NAME).build();
client = new TransportClient(settings);
for (int i = 0; i < transportAddress.length - 1; i++) {
((TransportClient) client).addTransportAddress(new InetSocketTransportAddress(transportAddress[i], transportPort));
}
logger.info("Elastic search client initialized");
}
}
logger.info("Returning the existing client");
return client;
}
}

The sample java code does show a call to client.close();
Call this when your app closes, or look into hooks to force it to be run.

Related

TCP connection in Unity

I'm working on TCP connection between two Windows10 laptops. I made the applications using Unity 2019.2.17f1. However, the TCP connection doesn't work. The Client application connects to the server only when I don't run the server application (this is strange though...), otherwise the client application shows the message "server is not found...".
I put the part of the codes here.
Client Program:
public class TCPClientManager : MonoBehaviour
{
// ip address(server) and port number
public string ipAddress = "192.0.0.1";
public int port = 3000;
private TcpClient m_tcpClient;
private NetworkStream m_networkStream;
private bool m_isConnection;
private string message;
void Start()
{
try
{
// connect to the server
m_tcpClient = new TcpClient(ipAddress, port);
m_networkStream = m_tcpClient.GetStream();
m_isConnection = true;
}
catch (SocketException)
{
m_isConnection = false;
// show a error message
// ...
}
}
void OnGUI()
{
if (m_isConnection)
{
GUILayout.Label("server is not found...");
return;
}
// some codes here
}
// some codes here
}
Server Program:
public class TCPServerManager : MonoBehaviour
{
// ip address(server) and port number
public string ipAddress = "192.0.0.1";
public int port = 3000;
private TcpListener m_tcpListener;
private TcpClient m_tcpClient;
private NetworkStream m_networkStream;
private bool m_isConnection;
private string message = string.Empty;
private void Awake()
{
Task.Run(() => OnProcess());
}
private void OnProcess()
{
var n_IpAddress = IPAddress.Parse(ipAddress);
m_tcpListener = new TcpListener(n_IpAddress, port);
m_tcpListener.Start();
m_tcpClient = m_tcpListener.AcceptTcpClient();
m_networkStream = m_tcpClient.GetStream();
while (true)
{
var buffer = new byte[256];
var count = m_networkStream.Read(buffer, 0, buffer.Length);
if (count == 0)
{
OnDestroy();
Task.Run(() => OnProcess());
break;
}
message += Encoding.UTF8.GetString(buffer, 0, count) + "\n";
}
}
// ....
}
Thank you very much for your comments in advice.
I think you inverted you m_isConnection variables values. You set it to true after connecting the server and false if not. But in OnGUI, if you found the connection then you print an error message and leave. Which means you do your //some code here only if no server was found.

Print in bluetooth device-Xamarin

I am developing a cross platform app.
I need print in printer Intermec PR2
I use this codes:
Class in .Droid
[assembly: Xamarin.Forms.Dependency(typeof(clsBluetooth))]
namespace Bluetooth.Droid
{
public class clsBluetooth : IBluetooth
{
private BluetoothAdapter adapter = BluetoothAdapter.DefaultAdapter;
private BluetoothSocket socket = null;
private BufferedWriter outReader = null;
private BluetoothDevice device = null;
public void Imprimir(string pStrNomBluetooth, int intSleepTime, string pStrTextoImprimir)
{
try
{
string bt_printer = (from d in adapter.BondedDevices
where d.Name == pStrNomBluetooth
select d).FirstOrDefault().ToString();
device = adapter.GetRemoteDevice(bt_printer);
UUID applicationUUID = UUID.FromString("00001101-0000-1000-8000-00805f9b34fb");
socket = device.CreateRfcommSocketToServiceRecord(applicationUUID);
socket.Connect();
outReader = new BufferedWriter(new OutputStreamWriter(socket.InputStream));
outReader.WriteAsync(pStrTextoImprimir);
}
catch (Exception)
{
throw;
}
finally
{
}
}
public ObservableCollection<string> PairedDevices()
{
ObservableCollection<string> devices = new ObservableCollection<string>();
foreach (var bd in adapter.BondedDevices)
devices.Add(bd.Name);
return devices;
}
}
}
Interface in Potable
public interface IBluetooth
{
ObservableCollection<string> PairedDevices();
void Imprimir(string pStrNomBluetooth, int intSleepTime, string pStrTextoImprimir);
}
Call of method
DependencyService.Get<IBluetooth>().Imprimir(SelectedBthDevice,200,"HolaMundo");
My error happens when I enter the class in the .Droid and it executes the sentence socket.Connect (); Does not seem to connect to the device.
Someone could help me to see the script or how the code could change so that the connection to the device works correctly
Try creating the insecure socket communication like:
socket = device.CreateInsecureRfcommSocketToServiceRecord(applicationUUID);
instead of the existing secure one:
socket = device.CreateRfcommSocketToServiceRecord(applicationUUID);
If you are able to connect after that you can write to printer as follows:
byte[] buffer = Encoding.UTF8.GetBytes(pStrTextoImprimir);
socket.OutputStream.Write(buffer, 0, buffer.Length);
For further details refer to.

Can CRM OrgService and Context be static?

This is design question/query so I hope it's Ok to post...
Pretty much every CRM OrgService and Context example you see is not static. Normally uses a using block. Which works of course, but could this be a static class rather than creating/destroying this over and over and over with using blocks everywhere? Is there any issue doing this?
Thanks for your advice :-)
Edit: Here's the code. Do you see any issue with this?...
CrmServiceContext is created by the early-bound entities generator.
static public class CRMOrgService
{
static private IOrganizationService _orgService = null;
static private CrmServiceContext _context = null;
static public IOrganizationService OrgService {
get
{
if (_orgService == null)
{
var reader = new AppSettingsReader();
Uri crmUri = new Uri(reader.GetValue("CRMOrgSvc", typeof(string)).ToString());
string crmUser = reader.GetValue("CRMUser", typeof(string)).ToString();
string crmPass = reader.GetValue("CRMPass", typeof(string)).ToString();
// Your client credentials
ClientCredentials clientCredentials = new ClientCredentials();
clientCredentials.UserName.UserName = crmUser;
clientCredentials.UserName.Password = crmPass;
// Create your Organization Service Proxy
var proxy = new OrganizationServiceProxy(crmUri, null, clientCredentials, null);
proxy.EnableProxyTypes();
_orgService = (IOrganizationService)proxy;
}
return _orgService;
}
}
static public CrmServiceContext Context
{
get
{
if (_context == null)
{
_context = new CrmServiceContext(OrgService);
}
return _context;
}
}
static public void CloseCleanUp()
{
_context.ClearChanges();
_context.Dispose();
_context = null;
_orgService = null;
}
} // end class
Yes, it can be static. However, you have to keep in mind this instance will not be thread safe. This means, the connection instance can not be used simultaneous by multiple threads.

GWT application crashes in latest Firefox versions 21 and above

We have a GWT application which crashes in Firefox versions 21 and above, including in the latest version 23.0.1. In earlier versions of Firefox and IE 9, it works fine. This is in deployed mode and not because of the GWT plugin. The situation it crashes is when there are huge number of RPC calls, may be around 300 to 400.
As the application in which it happens is fairly complex, I tried to simulate this issue with a simple prototype. I observed that my prototype crashes when the number of RPC calls reach 100000. But this scenario is very unlikely in my application where RPC calls are around 300-400 as observed using Firebug.
I am trying to find out what else I am missing in my prototype so that it also crashes with 300-400 RPC calls.
GWT version - 2.4
GXT version - 2.2.5
package com.ganesh.check.firefox.client;
public class FirefoxCrash implements EntryPoint {
private static final String SERVER_ERROR = "An error occurred while "
+ "attempting to contact the server. Please check your network "
+ "connection and try again.";
private final GreetingServiceAsync greetingService = GWT
.create(GreetingService.class);
public native static void consoleLog(String text)/*-{
$wnd.console.log(text);
}-*/;
public void onModuleLoad() {
final Button sendButton = new Button("Send");
final TextBox nameField = new TextBox();
nameField.setText("GWT User");
final Label errorLabel = new Label();
final Label countLabel = new Label();
// We can add style names to widgets
sendButton.addStyleName("sendButton");
// Add the nameField and sendButton to the RootPanel
// Use RootPanel.get() to get the entire body element
RootPanel.get("nameFieldContainer").add(nameField);
RootPanel.get("sendButtonContainer").add(sendButton);
RootPanel.get("errorLabelContainer").add(errorLabel);
RootPanel.get("count").add(countLabel);
// Focus the cursor on the name field when the app loads
nameField.setFocus(true);
nameField.selectAll();
// Create the popup dialog box
final DialogBox dialogBox = new DialogBox();
dialogBox.setText("Remote Procedure Call");
dialogBox.setAnimationEnabled(true);
final Button closeButton = new Button("Close");
// We can set the id of a widget by accessing its Element
closeButton.getElement().setId("closeButton");
final Label textToServerLabel = new Label();
final HTML serverResponseLabel = new HTML();
VerticalPanel dialogVPanel = new VerticalPanel();
dialogVPanel.addStyleName("dialogVPanel");
dialogVPanel.add(new HTML("<b>Sending name to the server:</b>"));
dialogVPanel.add(textToServerLabel);
dialogVPanel.add(new HTML("<br><b>Server replies:</b>"));
dialogVPanel.add(serverResponseLabel);
dialogVPanel.setHorizontalAlignment(VerticalPanel.ALIGN_RIGHT);
dialogVPanel.add(closeButton);
dialogBox.setWidget(dialogVPanel);
// Add a handler to close the DialogBox
closeButton.addClickHandler(new ClickHandler() {
public void onClick(ClickEvent event) {
dialogBox.hide();
sendButton.setEnabled(true);
sendButton.setFocus(true);
}
});
class MyHandler implements ClickHandler, KeyUpHandler {
private int resultCount = 0;
/**
* Fired when the user clicks on the sendButton.
*/
public void onClick(ClickEvent event) {
sendNameToServer();
}
public void onKeyUp(KeyUpEvent event) {
if (event.getNativeKeyCode() == KeyCodes.KEY_ENTER) {
sendNameToServer();
}
}
private void sendNameToServer() {
// First, we validate the input.
errorLabel.setText("");
String textToServer = nameField.getText();
// Then, we send the input to the server.
textToServerLabel.setText(textToServer);
serverResponseLabel.setText("");
final int loopCount = Integer.parseInt(textToServer);
resultCount=0;
for (int i = 0; i < loopCount; i++) {
greetingService.getResult(textToServer,
new AsyncCallback<ResultBean>() {
public void onFailure(Throwable caught) {
consoleLog(caught.getMessage());
}
public void onSuccess(ResultBean result) {
//countLabel.setText(++resultCount + "");
resultCount++;
if(resultCount==loopCount){
countLabel.setText(resultCount + "");
}
consoleLog("Result returned for "+resultCount);
}
});
}
}
}
// Add a handler to send the name to the server
MyHandler handler = new MyHandler();
sendButton.addClickHandler(handler);
nameField.addKeyUpHandler(handler);
}
}
public class GreetingServiceImpl extends RemoteServiceServlet implements
GreetingService {
public ResultBean getResult(String name) {
ResultBean result = new ResultBean();
Random random = new Random();
int suffix = random.nextInt();
result.setName("Name "+suffix);
result.setAddress("Address "+suffix);
result.setZipCode(suffix);
result.setDoorNumber("Door "+suffix);
return result;
}
public class ResultBean implements Serializable {
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public int getZipCode() {
return zipCode;
}
public void setZipCode(int zipCode) {
this.zipCode = zipCode;
}
public String getDoorNumber() {
return doorNumber;
}
public void setDoorNumber(String doorNumber) {
this.doorNumber = doorNumber;
}
private String name;
private String address;
private int zipCode;
private String doorNumber;
}

Wicket serving images from File System

I am pretty new to Wicket and i have some difficulties with using resource references. I am using wicket 1.5.4 and have following problem: I store images on the file system. I have class ImageElement which holds part of the file path relative to configured rootFilePath (i.e dir1/dir2/img1.png). On the page I add Image as follows:
new Image("id",ImagesResourceReference.get(), pageParameters)
where page parameters includes image path parameter (path="/dir1/dir2/img1.png"). My questions are:
Is it the simplest way of serving images from the file system?
Is it ok to use ResourceReference with static method? or I should construct each time new ResourceReference? I saw that in previous version it was possible to use new ResourceReference(globalId), but it seems not to be the case anymore. If so what is the global resource reference for? So far as I understand resource reference is supposed to be factory for resources so it would be rather strange to create new factory for each resource request.
The last question is, how can i pass the path to the image in a better way so that i do not have to concatenate indexed parameters to build the path once respond method is invoked on ImageResource.
What would be the best scenario to get it working in efficient and simple way, i saw the example in 'Wicket in action', but this is meant for dynamic image generation from db and am not sure if it suites for my case
My implementation of ResourceReference which I mounted in Application under "/images" path, looks as follows:
public class ImagesResourceReference extends ResourceReference {
private static String rootFileDirectory;
private static ImagesResourceReference instance;
private ImagesResourceReference() {
super(ImagesResourceReference.class, "imagesResourcesReference");
}
public static ImagesResourceReference get() {
if(instance == null) {
if(StringUtils.isNotBlank(rootFileDirectory)) {
instance = new ImagesResourceReference();
} else {
throw new IllegalStateException("Parameter configuring root directory " +
"where images are saved is not set");
}
}
return instance;
}
public static void setRootFileDirectory(String rootFileDirectory) {
ImagesResourceReference.rootFileDirectory = rootFileDirectory;
}
private static final long serialVersionUID = 1L;
#Override
public IResource getResource() {
return new ImageResource(rootFileDirectory);
}
private static class ImageResource implements IResource {
private static final long serialVersionUID = 1L;
private final String rootFileDirectory;
public ImageResource(String rootFileDirectory) {
this.rootFileDirectory = rootFileDirectory;
}
#Override
public void respond(Attributes attributes) {
PageParameters parameters = attributes.getParameters();
List<String> indexedParams = getAllIndexedParameters(parameters);
if(!indexedParams.isEmpty() && isValidImagePath(indexedParams)) {
String pathToRequestedImage = getImagePath(indexedParams);
FileResourceStream fileResourceStream = new FileResourceStream(new File(pathToRequestedImage));
ResourceStreamResource resource = new ResourceStreamResource(fileResourceStream);
resource.respond(attributes);
}
}
private boolean isValidImagePath(List<String> indexedParams) {
String fileName = indexedParams.get(indexedParams.size() -1);
return !FilenameUtils.getExtension(fileName).isEmpty();
}
private List<String> getAllIndexedParameters(PageParameters parameters) {
int indexedparamCount = parameters.getIndexedCount();
List<String> indexedParameters = new ArrayList<String>();
for(int i=0; i<indexedparamCount ;i++) {
indexedParameters.add(parameters.get(i).toString());
}
return indexedParameters;
}
private String getImagePath(List<String> indexedParams) {
return rootFileDirectory + File.separator + StringUtils.join(indexedParams, File.separator);
}
}
Any help and advices appreciated! Thanks in advance.
You could use it as a shared resource:
public class WicketApplication extends WebApplication {
#Override
public Class<HomePage> getHomePage() {
return HomePage.class;
}
#Override
public void init() {
super.init();
getSharedResources().add("downloads", new FolderContentResource(new File("C:\\Users\\ronald.tetsuo\\Downloads")));
mountResource("downloads", new SharedResourceReference("downloads"));
}
static class FolderContentResource implements IResource {
private final File rootFolder;
public FolderContentResource(File rootFolder) {
this.rootFolder = rootFolder;
}
public void respond(Attributes attributes) {
PageParameters parameters = attributes.getParameters();
String fileName = parameters.get(0).toString();
File file = new File(rootFolder, fileName);
FileResourceStream fileResourceStream = new FileResourceStream(file);
ResourceStreamResource resource = new ResourceStreamResource(fileResourceStream);
resource.respond(attributes);
}
}
}
You can still use ResourceReferences with global IDs. You just have to use a SharedResourceReference. This is probably better, too.
add(new Image("image", new SharedResourceReference("mySharedResourceRef", parameters));
I would try to avoid building paths from URL parameters. This can easily end up in security leaks.

Resources