Skip to content

Commit

Permalink
generate ps1 code to update hosts file
Browse files Browse the repository at this point in the history
  • Loading branch information
jianglibo committed Dec 20, 2016
1 parent f7b7741 commit 96a56a0
Show file tree
Hide file tree
Showing 17 changed files with 271 additions and 28 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -162,11 +162,11 @@ public static String getMsgFallbackToSelf(MessageSource messageSource, String pr
return name;
}

public static String getMsgWithSubsReturnKeyOnAbsent(MessageSource messageSource, String key, String...substitudes) {
public static String getMsgWithSubsReturnKeyOnAbsent(MessageSource messageSource,String prefix, String key, String...substitudes) {
try {
return messageSource.getMessage(key, substitudes, UI.getCurrent().getLocale());
return messageSource.getMessage(prefix + key, substitudes, UI.getCurrent().getLocale());
} catch (NoSuchMessageException e) {
LOGGER.info("field {} has no localized message", key);
LOGGER.info("field {} has no localized message",prefix + key);
}
return key;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,19 +8,19 @@
public class NotificationUtil {

public static void humanized(MessageSource messageSource, String msg, String...subs) {
Notification.show(MsgUtil.getMsgWithSubsReturnKeyOnAbsent(messageSource, "notification.humanized." + msg, subs), "", Type.HUMANIZED_MESSAGE);
Notification.show(MsgUtil.getMsgWithSubsReturnKeyOnAbsent(messageSource, "notification.humanized." , msg, subs), "", Type.HUMANIZED_MESSAGE);
}

public static void tray(MessageSource messageSource,String msg, String...subs) {
Notification.show(MsgUtil.getMsgWithSubsReturnKeyOnAbsent(messageSource, "notification.tray." + msg, subs), "", Type.TRAY_NOTIFICATION);
Notification.show(MsgUtil.getMsgWithSubsReturnKeyOnAbsent(messageSource, "notification.tray." , msg, subs), "", Type.TRAY_NOTIFICATION);
}

public static void warn(MessageSource messageSource,String msg, String...subs) {
Notification.show(MsgUtil.getMsgWithSubsReturnKeyOnAbsent(messageSource, "notification.warn." + msg, subs), "", Type.WARNING_MESSAGE);
Notification.show(MsgUtil.getMsgWithSubsReturnKeyOnAbsent(messageSource, "notification.warn." , msg, subs), "", Type.WARNING_MESSAGE);
}

public static void error(MessageSource messageSource,String msg, String...subs) {
Notification.show(MsgUtil.getMsgWithSubsReturnKeyOnAbsent(messageSource, "notification.error." + msg, subs), "", Type.ERROR_MESSAGE);
Notification.show(MsgUtil.getMsgWithSubsReturnKeyOnAbsent(messageSource, "notification.error." , msg, subs), "", Type.ERROR_MESSAGE);
}

public static void errorRaw(String msg) {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
package com.jianglibo.vaadin.dashboard.util;

import java.io.File;
import java.io.IOException;
import java.lang.ProcessBuilder.Redirect;
import java.util.Map;

public class ProcessRunner {

public static Process build() throws IOException {
ProcessBuilder pb =
new ProcessBuilder("myCommand", "myArg1", "myArg2");
Map<String, String> env = pb.environment();
env.put("VAR1", "myValue");
env.remove("OTHERVAR");
env.put("VAR2", env.get("VAR1") + "suffix");
pb.directory(new File("myDir"));
File log = new File("log");
pb.redirectErrorStream(true);
pb.redirectOutput(Redirect.appendTo(log));
Process p = pb.start();
return p;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -6,4 +6,9 @@
public class StrUtil {
public static final Splitter commaSplitter = Splitter.on(',').trimResults().omitEmptyStrings();
public static final Joiner commaJoiner = Joiner.on(',').skipNulls();


public static String doubleQuotation(String origin) {
return "\"" + origin + "\"";
}
}
Original file line number Diff line number Diff line change
@@ -1,26 +1,40 @@
package com.jianglibo.vaadin.dashboard.view.boxgroup;

import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.nio.file.Path;
import java.sql.Date;
import java.time.Instant;
import java.util.List;
import java.util.Set;
import java.util.UUID;
import java.util.stream.Collectors;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.MessageSource;
import org.springframework.core.io.Resource;
import org.springframework.data.domain.Sort;

import com.google.common.base.Charsets;
import com.google.common.base.Joiner;
import com.google.common.hash.Hashing;
import com.google.common.io.CharStreams;
import com.google.common.io.Files;
import com.jianglibo.vaadin.dashboard.annotation.VaadinGridColumnWrapper;
import com.jianglibo.vaadin.dashboard.annotation.VaadinGridWrapper;
import com.jianglibo.vaadin.dashboard.config.ApplicationConfig;
import com.jianglibo.vaadin.dashboard.config.CommonMenuItemIds;
import com.jianglibo.vaadin.dashboard.data.container.FreeContainer;
import com.jianglibo.vaadin.dashboard.domain.Domains;
import com.jianglibo.vaadin.dashboard.domain.PkSource;
import com.jianglibo.vaadin.dashboard.domain.BoxGroup;
import com.jianglibo.vaadin.dashboard.repositories.BoxGroupRepository;
import com.jianglibo.vaadin.dashboard.repositories.PkSourceRepository;
import com.jianglibo.vaadin.dashboard.repositories.RepositoryCommonCustom;
import com.jianglibo.vaadin.dashboard.uicomponent.dynmenu.SimpleButtonDescription;
import com.jianglibo.vaadin.dashboard.uicomponent.dynmenu.UnArchiveButtonDescription;
Expand All @@ -38,8 +52,10 @@
import com.jianglibo.vaadin.dashboard.util.ListViewFragmentBuilder;
import com.jianglibo.vaadin.dashboard.util.MsgUtil;
import com.jianglibo.vaadin.dashboard.util.NotificationUtil;
import com.jianglibo.vaadin.dashboard.util.StrUtil;
import com.jianglibo.vaadin.dashboard.view.clustersoftware.ClusterSoftwareView;
import com.jianglibo.vaadin.dashboard.view.envfixture.EnvFixtureCreator;
import com.jianglibo.vaadin.dashboard.view.pksource.PkSourceListView;
import com.vaadin.spring.annotation.SpringView;
import com.vaadin.ui.Component;
import com.vaadin.ui.HorizontalLayout;
Expand All @@ -60,14 +76,20 @@ public class BoxGroupListView extends BaseGridView<BoxGroup, BoxGroupGrid, FreeC
private final BoxGroupRepository repository;

private final EnvFixtureCreator envFixtureCreator;

private final ApplicationConfig applicationConfig;

private final PkSourceRepository pkSourceRepository;


@Autowired
public BoxGroupListView(BoxGroupRepository repository,Domains domains, MessageSource messageSource,
ApplicationContext applicationContext, EnvFixtureCreator envFixtureCreator) {
ApplicationContext applicationContext, EnvFixtureCreator envFixtureCreator, ApplicationConfig applicationConfig, PkSourceRepository pkSourceRepository) {
super(applicationContext, messageSource, domains, BoxGroup.class, BoxGroupGrid.class);
this.repository = repository;
this.envFixtureCreator = envFixtureCreator;
this.applicationConfig = applicationConfig;
this.pkSourceRepository = pkSourceRepository;
delayCreateContent();
}

Expand All @@ -76,7 +98,9 @@ public ButtonGroup[] getButtonGroups() {
new ButtonGroup(new EditButtonDescription(),new AddButtonDescription()),//
new ButtonGroup(new DeleteButtonDescription(), new UnArchiveButtonDescription()),
new ButtonGroup( //
new SimpleButtonDescription("manageClusterSoftware", null, ButtonEnableType.ONE))};
new SimpleButtonDescription("manageClusterSoftware", null, ButtonEnableType.ONE)),
new ButtonGroup( //
new SimpleButtonDescription("createUpdateHostPs1", null, ButtonEnableType.ONE))};
}

@Override
Expand Down Expand Up @@ -121,6 +145,41 @@ public void onDynButtonClicked(ButtonDescription btnDesc) {
case "manageClusterSoftware":
UI.getCurrent().getNavigator().navigateTo(ClusterSoftwareView.VIEW_NAME + "/?boxgroup=" + selected.iterator().next().getId() + "&pv=" + getLvfb().toNavigateString());
break;
case "createUpdateHostPs1":
try {
BoxGroup bg = selected.iterator().next();
String pairs = StrUtil.doubleQuotation(bg.getBoxes().stream().filter(box -> !box.getIp().equals(box.getHostname())).map(box -> box.getIp() + " " + box.getHostname()).collect(Collectors.joining(",")));
Resource rs = getApplicationContext().getResource("classpath:snippets/HostModifier.ps1");
List<String> lines = CharStreams.readLines(new InputStreamReader(rs.getInputStream(), Charsets.UTF_8));
lines = lines.stream().map(l -> {
if (l.contains("---insert-items-here---")) {
return "$items = " + pairs;
} else {
return l;
}
}).collect(Collectors.toList());

String uuid = UUID.randomUUID().toString();
Path tmpPath = applicationConfig.getUploadDstPath().resolve(uuid);
Files.write(Joiner.on(System.lineSeparator()).join(lines), tmpPath.toFile(), StandardCharsets.UTF_8);
String md5 = com.google.common.io.Files.asByteSource(tmpPath.toFile()).hash(Hashing.md5()).toString();
PkSource ps = pkSourceRepository.findByFileMd5(md5);
if (ps == null) {
File nf = new File(tmpPath.toFile().getParentFile(), md5 + ".ps1");
if (!nf.exists()) {
com.google.common.io.Files.move(tmpPath.toFile(), nf);
}
ps = new PkSource.PkSourceBuilder(md5, "HostModifier-" + md5 + ".ps1", nf.length(), "ps1", java.nio.file.Files.probeContentType(nf.toPath())).build();
pkSourceRepository.save(ps);
} else {
ps.setUpdatedAt(Date.from(Instant.now()));
pkSourceRepository.save(ps);
}
NotificationUtil.tray(getMessageSource(), "go to '" + MsgUtil.getViewMenuMsg(getMessageSource(), PkSourceListView.VIEW_NAME) + "', to download ps1 file to execute." );
} catch (IOException e) {
NotificationUtil.errorRaw(e.getMessage());
}
break;
default:
LOGGER.error("unKnown menuName {}", btnDesc.getItemId());
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ public BoxSoftwareView(MessageSource messageSource,BoxRepository boxRepository,
vl.setSpacing(true);
vl.setSizeFull();

Label label = new Label(MsgUtil.getMsgWithSubsReturnKeyOnAbsent(messageSource, "view.boxsoftware.intro"));
Label label = new Label(MsgUtil.getMsgWithSubsReturnKeyOnAbsent(messageSource, "view.boxsoftware.", "intro"));
StyleUtil.setMarginTwenty(label);
Component c = createInstallForm();
vl.addComponents(label, c);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ protected void setupGrid() {
groupingHeader.getCell("name"),
groupingHeader.getCell("ostype"));
HorizontalLayout hl = new HorizontalLayout();
Label lb = new Label(MsgUtil.getMsgWithSubsReturnKeyOnAbsent(getMessageSource(), "view.boxsoftware.gridtitleinstalled"));
Label lb = new Label(MsgUtil.getMsgWithSubsReturnKeyOnAbsent(getMessageSource(), "view.boxsoftware.", "gridtitleinstalled"));
ComboBox cb = new ComboBox();
cb.setEnabled(false);
hl.addComponents(lb, cb);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ protected void setupGrid() {
groupingHeader.getCell("name"),
groupingHeader.getCell("ostype"));
HorizontalLayout hl = new HorizontalLayout();
Label lb = new Label(MsgUtil.getMsgWithSubsReturnKeyOnAbsent(getMessageSource(), "view.boxsoftware.gridtitleall"));
Label lb = new Label(MsgUtil.getMsgWithSubsReturnKeyOnAbsent(getMessageSource(), "view.boxsoftware.", "gridtitleall"));
ComboBox cb = new ComboBox();
cb.setEnabled(false);
hl.addComponents(lb, cb);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -140,9 +140,9 @@ private Component toolbars() {
String mpx = vgw.getVg().messagePrefix();
BoxTwinGridFieldFree boxesToRun = new BoxTwinGridFieldFree(bcInRc, domains, messageSource, boxRepository, 3 , 3, mpx, mpx);

boxesToRun.setCaption(MsgUtil.getMsgWithSubsReturnKeyOnAbsent(messageSource, "view.clustersoftware.selectboxes"));
boxesToRun.setCaption(MsgUtil.getMsgWithSubsReturnKeyOnAbsent(messageSource, "view.clustersoftware.", "selectboxes"));
boxesToRun.setSizeFull();
Button ok = new Button(MsgUtil.getMsgWithSubsReturnKeyOnAbsent(messageSource, "shared.btn.execute"));
Button ok = new Button(MsgUtil.getMsgWithSubsReturnKeyOnAbsent(messageSource, "shared.btn.", "execute"));
ok.addStyleName(ValoTheme.BUTTON_PRIMARY);
ok.addClickListener(new ClickListener() {
@Override
Expand Down Expand Up @@ -216,7 +216,7 @@ private Component createTop() {
backBtn = new Button(FontAwesome.MAIL_REPLY);
StyleUtil.hide(backBtn);

backBtn.setDescription(MsgUtil.getMsgWithSubsReturnKeyOnAbsent( messageSource ,"shared.btn.return"));
backBtn.setDescription(MsgUtil.getMsgWithSubsReturnKeyOnAbsent( messageSource ,"shared.btn.", "return"));

backBtn.addClickListener(event -> {
this.backward();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -63,23 +63,23 @@ protected List<PropertyIdAndField> buildFields() {


private PropertyIdAndField createDescriptionField() {
actionParameterTpl = new TextArea(MsgUtil.getMsgWithSubsReturnKeyOnAbsent(messageSource, "view.clustersoftware.form.actionpatpl"));
actionParameterTpl = new TextArea(MsgUtil.getMsgWithSubsReturnKeyOnAbsent(messageSource, "view.clustersoftware.form.", "actionpatpl"));
actionParameterTpl.setRows(4);
return new PropertyIdAndField("actionParameterTpl", actionParameterTpl);
}

private PropertyIdAndField createOthersField() {
othersField = new TextArea(MsgUtil.getMsgWithSubsReturnKeyOnAbsent(messageSource, "view.clustersoftware.form.others"));
othersField = new TextArea(MsgUtil.getMsgWithSubsReturnKeyOnAbsent(messageSource, "view.clustersoftware.form.", "others"));
othersField.setRows(4);
String desc = MsgUtil.getMsgWithSubsReturnKeyOnAbsent(messageSource, "view.clustersoftware.form.desc.others");
String desc = MsgUtil.getMsgWithSubsReturnKeyOnAbsent(messageSource, "view.clustersoftware.form.desc.", "others");
if (!desc.equals("view.clustersoftware.form.desc.others")) {
othersField.setDescription(desc);
}
return new PropertyIdAndField("others", othersField);
}

private PropertyIdAndField createActionField() {
actionCb = new ComboBox(MsgUtil.getMsgWithSubsReturnKeyOnAbsent(messageSource, "view.clustersoftware.form.action"));
actionCb = new ComboBox(MsgUtil.getMsgWithSubsReturnKeyOnAbsent(messageSource, "view.clustersoftware.form.", "action"));
actionCb.setNewItemsAllowed(false);

if (softwareCb != null) {
Expand Down Expand Up @@ -120,7 +120,7 @@ private void setActionCbItems() {
}

private PropertyIdAndField createSoftwareField() {
softwareCb = new ComboBox(MsgUtil.getMsgWithSubsReturnKeyOnAbsent(messageSource, "view.clustersoftware.form.software"));
softwareCb = new ComboBox(MsgUtil.getMsgWithSubsReturnKeyOnAbsent(messageSource, "view.clustersoftware.form.", "software"));
softwareCb.setNewItemsAllowed(false);
// AllSoftwareContainer fc = new AllSoftwareContainer(domains, 10, Lists.newArrayList());
softwareCb.setItemCaptionMode(ItemCaptionMode.PROPERTY);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ protected void setupGrid() {
HorizontalLayout hl = new HorizontalLayout();
hl.setSpacing(true);

redoBt = new Button(MsgUtil.getMsgWithSubsReturnKeyOnAbsent(getMessageSource(), "view.clustersoftware.button.redo"));
redoBt = new Button(MsgUtil.getMsgWithSubsReturnKeyOnAbsent(getMessageSource(), "view.clustersoftware.button.", "redo"));
hl.addComponent(redoBt);
redoBt.setEnabled(false);

Expand All @@ -89,7 +89,7 @@ protected void setupGrid() {
}
});

dspBt = new Button(MsgUtil.getMsgWithSubsReturnKeyOnAbsent(getMessageSource(), "view.clustersoftware.button.boxhistories"));
dspBt = new Button(MsgUtil.getMsgWithSubsReturnKeyOnAbsent(getMessageSource(), "view.clustersoftware.button.", "boxhistories"));
hl.addComponent(dspBt);
dspBt.setEnabled(false);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -128,7 +128,7 @@ private Component createTop() {
backBtn = new Button(FontAwesome.MAIL_REPLY);
StyleUtil.hide(backBtn);

backBtn.setDescription(MsgUtil.getMsgWithSubsReturnKeyOnAbsent(messageSource, "shared.btn.return"));
backBtn.setDescription(MsgUtil.getMsgWithSubsReturnKeyOnAbsent(messageSource, "shared.btn.", "return"));

backBtn.addClickListener(event -> {
this.backward();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -194,7 +194,7 @@ private Component createTop() {
backBtn = new Button(FontAwesome.MAIL_REPLY);
StyleUtil.hide(backBtn);

backBtn.setDescription(MsgUtil.getMsgWithSubsReturnKeyOnAbsent(messageSource, "shared.btn.return"));
backBtn.setDescription(MsgUtil.getMsgWithSubsReturnKeyOnAbsent(messageSource, "shared.btn.", "return"));

backBtn.addClickListener(event -> {
this.backward();
Expand Down
4 changes: 2 additions & 2 deletions src/main/resources/messages/all_en.properties
Original file line number Diff line number Diff line change
Expand Up @@ -57,8 +57,8 @@ systemmessage.cookiesDisabledMessage=This application requires cookies to functi

view.dashboard.title=DashBoard

view.pksource.list.title=File List
view.pksource.uploadbtn=Upload
view.PkSource.list.title=File List
view.PkSource.uploadbtn=Upload

view.Box.list.title=Server List
view.Box.newtitle=Create Box
Expand Down
4 changes: 2 additions & 2 deletions src/main/resources/messages/all_zh.properties
Original file line number Diff line number Diff line change
Expand Up @@ -57,8 +57,8 @@ systemmessage.cookiesDisabledMessage=\u6211\u53EA\u6709\u5728\u542F\u52A8Cookie\

view.dashboard.title=\u63A7\u5236\u53F0

view.pksource.list.title=\u6587\u4EF6\u5217\u8868
view.pksource.uploadbtn=\u5F00\u59CB\u4E0A\u4F20
view.PkSource.list.title=\u6587\u4EF6\u5217\u8868
view.PkSource.uploadbtn=\u5F00\u59CB\u4E0A\u4F20

view.Box.list.title=\u670D\u52A1\u5668\u5217\u8868
view.Box.newtitle=\u65B0\u5EFA\u4E3B\u673A
Expand Down
54 changes: 54 additions & 0 deletions src/main/resources/snippets/HostModifier.ps1
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
Param(
[string]$hostfile,
[switch]$delete,
[string]$items,
[bool]$writeback=$true
)

# ---insert-items-here---

function Update-HostsItems {
Param(
[string]$hostfile,
[switch]$delete,
[string]$items,
[bool]$writeback=$true)
if (!$hostfile) {
$hostfile = $env:windir | Join-Path -ChildPath "System32\drivers\etc\hosts"
}

[array]$lines = Get-Content $hostfile | ForEach-Object {$_.ToString().trim()}

[array]$items = $items -split "," | ForEach-Object {$_.ToString().Trim()}

foreach ($item in $items) {
[array]$pair = $item -split "\s+"
if ($delete) {
$lines = $lines | Where-Object {$_ -notmatch $pair[0].ToString().Trim()}
} else {
if ($pair.Count -eq 2) {
$lines = $lines | Where-Object {$_ -notmatch $pair[0].ToString().Trim()}
}
}
}
if ($writeback) {
if ($delete) {
$lines | Out-File $hostfile -Encoding ascii
} else {
$lines + $items | Out-File $hostfile -Encoding ascii
}
} else {
if ($delete) {
$lines
} else {
$lines + $items
}
}
}
if ($items) {
if ($delete) {
Update-HostsItems -hostfile $hostfile -items $items -writeback $writeback -delete
} else {
Update-HostsItems -hostfile $hostfile -items $items -writeback $writeback
}
}
Loading

0 comments on commit 96a56a0

Please sign in to comment.